<template>
    <div class="home">
        <p class="title" style="pointer-events: none;">事件设置</p>
        <div class="slider-container">
            <p class="set-title">触发阈值</p>
            <van-slider v-model="value" range @change="onChange" :min="0" :max="160" />
        </div>
        <div class="input-container">
            <van-field v-model="value[0]" type="number" label="最小值" placeholder="最小值" />
            <van-field v-model="value[1]" type="number" label="最大值" placeholder="最大值" />
        </div>
        <div class="slider-container">
            <p class="set-title">超速阈值</p>
            <van-slider v-model="overSpeedValue" range @change="onOverSpeedChange" :min="0" :max="160" />
        </div>
        <div class="input-container">
            <van-field v-model="overSpeedValue[0]" type="number" label="最小值" placeholder="最小值" />
            <van-field v-model="overSpeedValue[1]" type="number" label="最大值" placeholder="最大值" />
        </div>
        <div class="control">
            <p class="title-control">双色屏控制</p>
            <van-switch v-model="screencontrol" class="switch-control" />
        </div>
        <div class="control">
            <p class="title-control">设备地址</p>
            <van-field v-model="addr" placeholder="请输入设备地址" />
        </div>
        <div v-if="!screencontrol">
            <van-button round type="success" size="large" @click="uploadthreshold">设置</van-button>
        </div>
        <div v-if="screencontrol" class="control">
            <p class="title-control">事件列表</p>
            <van-icon name="plus" @click="addEvent" />
        </div>
        <div v-if="screencontrol">
            <div v-for="(event, index) in events" :key="index" :ref="'event' + index" class="event-item">
                <van-swipe-cell :right-width="65" @close="onClose">
                    <template v-slot:right>
                        <van-button square type="danger" @click="removeEvent(index)"
                            class="delete-button">删除</van-button>
                    </template>
                    <van-cell is-link title="事件类型" @click="event.showTypePicker = true">
                        {{ event.type }}
                    </van-cell>
                    <van-field v-if="event.type === '其他'" v-model="event.code" label="事件编码" placeholder="请输入事件编码" />

                    <van-cell is-link title="事件来源" @click="event.showsourcePicker = true">
                        {{ event.sourcename }}
                    </van-cell>
                    <van-field v-if="event.sourcename === '其他'" v-model="event.source" label="来源编码"
                        placeholder="请输入事件来源" />

                    <van-field v-model="event.priority" label="优先级" placeholder="请输入优先级" />
                    <van-field v-model="event.showItem" is-link readonly label="显示节目" placeholder="选择显示节目"
                        @click="showItemPicker = index" />
                    <van-field v-model="event.showDuration" label="显示时长" placeholder="请输入显示时长" />
                    <van-field v-model="event.outputPin" is-link readonly label="输出引脚" placeholder="请输入输出引脚"
                        @click="showpinpicker = index" />
                    <van-cell v-if="event.outputPin !== '-1'" is-link title="输出电平" @click="event.showoutlevel = true">
                        {{ event.outlevel }}
                    </van-cell>
                </van-swipe-cell>

                <van-action-sheet v-model:show="event.showoutlevel" :actions="levelactions"
                    @select="onSelectlevel(event, $event)" />
                <van-action-sheet v-model:show="event.showTypePicker" :actions="typeaction"
                    @select="onSelecttype(event, $event)" />
                <van-action-sheet v-model:show="event.showsourcePicker" :actions="sourceaction"
                    @select="onSelectsource(event, $event)" />

                <van-popup v-model="showItemPicker" :show="showItemPicker === index" round position="bottom">
                    <van-picker :columns="progremcolums" @cancel="() => showItemPicker = -1"
                        @confirm="value => onConfirmShowItem(index, value)" />
                </van-popup>
                <van-popup v-model="showpinpicker" :show="showpinpicker === index" round position="bottom">
                    <van-picker :columns="outpincolumns" @cancel="() => showpinpicker = -1"
                        @confirm="value => onConfirmoutpin(index, value)" />
                </van-popup>
            </div>
        </div>

        <div v-if="screencontrol && events.length > 0" class="button-container">
            <van-button round type="success" size="large" @click="uploadEventSettings">设置</van-button>
        </div>
    </div>
</template>

<script>
import { onMounted, ref } from 'vue';
// import { showToast } from 'vant';
import axios from 'axios';
import { connectMQTT, client } from "../../components/MQTT/mqttclient";

export default {
    name: 'EventSettings',
    methods: {
        eventfilldata(data) {
            // 处理数据的逻辑
            console.log('Data received in EventSettings:', data);
        },
    },
    components: {
        connectMQTT,
        client,

    },
    setup() {
        const value = ref([10, 50]);
        const overSpeedValue = ref([60, 160]);
        const screencontrol = ref(false);
        const addr = ref('');
        const events = ref([]);
        const showItemPicker = ref(-1);
        const showpinpicker = ref(-1);
        const isLocal = ref(true);
        const jsonId = ref(1); // 初始 JSON ID
        const addEvent = () => {
            events.value.push({
                type: '',
                code: '',
                source: '',
                priority: '',
                showItem: '',
                showDuration: '',
                outputPin: '',
                outlevel: '',
                sourcename: '',
                showTypePicker: false,
                showoutlevel: false,
                showsourcePicker: false,
            });
            showToast('添加成功');
        };
        const checkEnvironment = () => {
            if (window.location.hostname === '192.168.4.1') {
                console.log('in local');
                // 本地开发环境，设置 isLocal 为 true
                isLocal.value = true;
            } else {
                // 生产环境，设置 isLocal 为 false
                isLocal.value = false;
            }
        };

        const removeEvent = (index) => {
            events.value.splice(index, 1);
            uploadEventSettings();
        };

        const onSelectlevel = (event, selectedItem) => {
            event.outlevel = selectedItem.value.toString();
            event.showoutlevel = false;
            showToast(selectedItem.name);
        };

        const onSelecttype = (event, selectedItem) => {
            event.type = selectedItem.name;
            event.code = selectedItem.code.toString();
            event.showTypePicker = false;
            showToast(selectedItem.name);
        };
        const onOverSpeedChange = (value) => showToast('当前超速值：' + value);

        const onSelectsource = (event, selectedItem) => {
            event.sourcename = selectedItem.name;
            event.source = selectedItem.code.toString();
            event.showsourcePicker = false;
            showToast(selectedItem.name);
        };
        const onClose = (position, instance) => {
            if (position === 'right') {
                instance.close();
            }
        };
        const onConfirmShowItem = (index, value) => {
            events.value[index].showItem = value.selectedOptions[0].value;
            showItemPicker.value = -1;
        };

        const onConfirmoutpin = (index, value) => {
            events.value[index].outputPin = value.selectedOptions[0].value;
            showpinpicker.value = -1;
        };

        const onChange = (value) => {
            showToast('当前值：' + value);
        };
        const uploadthreshold = () => {
            if (!addr.value) {
                showToast('请填写设备地址');
                return;
            }
            const threshold = {
                JSON_id: jsonId.value,
                board_id: 105,
                LoRa_card: {
                    trig_cfg: {
                        trig_spd_L: parseInt(value.value[0]),
                        trig_spd_H: parseInt(value.value[1]),
                        lmt_spd_L: parseInt(overSpeedValue.value[0]),
                        lmt_spd_H: parseInt(overSpeedValue.value[1]),
                        screen_ctrl_en: screencontrol.value ? 1 : 0,
                        addr: parseInt(addr.value),
                    },
                },
            };
            console.log(JSON.stringify(threshold)); // 打印构造的 JSON 数据
            if (isLocal.value) {
                axios.post(`/communication`, threshold, {
                    headers: {
                        "content-type": "application/json"
                    }
                })
                    .then(response => {
                        console.log('Response data:', response.data);
                        showToast('设置成功');
                        jsonId.value++;
                    })
                    .catch(error => {
                        // 处理错误
                        console.error('Upload error:', error);
                        showToast('设置失败');
                        jsonId.value++;
                    });
            }
            else {
                MQTT_send(threshold);
            }
        };


        const uploadEventSettings = () => {
            for (const event of events.value) {
                if (!event.type || !event.code || !event.source || !event.priority || !event.showItem || !event.showDuration || !event.outputPin || !addr.value) {
                    showToast('请填写完整事件信息');
                    return;
                }
            }

            const eventPayload = {
                "JSON_id": jsonId.value,
                board_id: 105,
                LoRa_card: {
                    trig_cfg: {
                        trig_spd_L: parseInt(value.value[0]),
                        trig_spd_H: parseInt(value.value[1]),
                        lmt_spd_L: parseInt(overSpeedValue.value[0]),
                        lmt_spd_H: parseInt(overSpeedValue.value[1]),
                        screen_ctrl_en: screencontrol.value ? 1 : 0,
                        addr: parseInt(addr.value),
                        event: events.value.map(event => ({
                            code: parseInt(event.code),
                            source: parseInt(event.source),
                            priority: parseInt(event.priority),
                            prg_num: parseInt(event.showItem),
                            prg_time: parseInt(event.showDuration),
                            output: parseInt(event.outputPin),
                            level: parseInt(event.outlevel)
                        }))
                    },
                },
            };
            console.log(JSON.stringify(eventPayload)); // 打印构造的 JSON 数据
            if (isLocal.value) {
                axios.post(`/communication`, eventPayload, {
                    headers: {
                        "content-type": "application/json"
                    }
                })
                    .then(response => {
                        console.log('Response data:', response.data);
                        showToast('设置成功');
                        jsonId.value++;
                    })
                    .catch(error => {
                        // 处理错误
                        console.error('Upload error:', error);
                        showToast('设置失败');
                        jsonId.value++;
                    });
            }
            else {
                MQTT_send(eventPayload);
            }
        };
        const eventfilldata = (msg) => {
            if (msg.LoRa_card) {
                const trigCfg = msg.LoRa_card.trig_cfg;
                // 回填阈值设置的数据
                addr.value = trigCfg.addr;
                value.value = [trigCfg.trig_spd_L, trigCfg.trig_spd_H];
                overSpeedValue.value = [trigCfg.lmt_spd_L, trigCfg.lmt_spd_H]; 4
                screencontrol.value = !!trigCfg.screen_ctrl_en;

                // 回填事件列表的数据
                events.value = trigCfg.event.map(event => {
                    let eventType;
                    let eventsource;
                    switch (event.source) {
                        case 0:
                            eventsource = '本台设备';
                            break;
                        case 254:
                            eventsource = '除本身外任意设备';
                            break;
                        case 255:
                            eventsource = '任意设备';
                            break;
                        default:
                            eventsource = '其他';
                    }
                    switch (event.code) {
                        case 0:
                            eventType = '默认显示';
                            break;
                        case 1:
                            eventType = '雷达触发(RS485 雷达)';
                            break;
                        case 2:
                            eventType = '雷达超速(RS485 雷达)';
                            break;

                        case 3:
                            eventType = '车牌触发(摄像头)';
                            break;

                        case 4:
                            eventType = '车牌超速(摄像头)';
                            break;

                        case 5:
                            eventType = '行人检测(相机)';
                            break;

                        case 0x51:
                            eventType = 'IN1下降沿';
                            break;

                        case 0x52:
                            eventType = 'IN2上升沿';
                            break;

                        case 0x53:
                            eventType = 'IN3下降沿';
                            break;

                        case 0x54:
                            eventType = 'IN4上升沿';
                            break;

                        case 0x55:
                            eventType = 'IN1低电平';
                            break;
                        case 0x56:
                            eventType = 'IN2高电平';
                            break;
                        case 0x57:
                            eventType = 'IN3低电平';
                            break;
                        case 0x58:
                            eventType = 'IN4高电平';
                            break;
                        default:
                            eventType = '其他';
                    }
                    return {
                        type: eventType,
                        code: event.code.toString(),
                        source: event.source.toString(),
                        sourcename: eventsource,
                        priority: event.priority.toString(),
                        showItem: event.prg_num.toString(),
                        // showItem: programnum,
                        showDuration: event.prg_time.toString(),
                        outputPin: event.output.toString(),
                        outlevel: event.level.toString(),
                    };
                });

            }
        };
        const typeaction = [
            { name: '默认显示', code: 0 },
            { name: '雷达触发(RS485 雷达)', code: 1 },
            { name: '雷达超速(RS485 雷达)', code: 2 },
            { name: '车牌触发(摄像头)', code: 3 },
            { name: '车牌超速(摄像头)', code: 4 },
            { name: '行人检测(相机)', code: 5 },
            { name: 'IN1下降沿', code: 0x51 },
            { name: 'IN2上升沿', code: 0x52 },
            { name: 'IN3下降沿', code: 0x53 },
            { name: 'IN4上升沿', code: 0x54 },
            { name: 'IN1低电平', code: 0x55 },
            { name: 'IN2高电平', code: 0x56 },
            { name: 'IN3低电平', code: 0x57 },
            { name: 'IN4高电平', code: 0x58 },
            { name: '其他', code: -1 },
        ];

        const levelactions = [
            { name: '高(0)', value: 0 },
            { name: '低(1)', value: 1 },
        ];

        const sourceaction = [
            { name: '本台设备', code: 0 },
            { name: '任意设备（不包含本设备）', code: 254 },
            { name: '任意设备', code: 255 },
            { name: '其他', code: 1 },
        ];
        const progremcolums = [
            { text: '节目0(0)', value: '0' },
            { text: '节目1(1)', value: '1' },
            { text: '节目2(2)', value: '2' },
            { text: '节目3(3)', value: '3' },
            { text: '节目4(4)', value: '4' },
            { text: '节目5(5)', value: '5' },
            { text: '节目6(6)', value: '6' },
            { text: '节目7(7)', value: '7' },
            { text: '节目8(8)', value: '8' },
            { text: '节目9(9)', value: '9' },
        ];
        const outpincolumns = [
            { text: '关闭(-1)', value: '-1' },
            { text: '引脚1(0)', value: '0' },
            { text: '引脚2(1)', value: '1' },

        ];
        const MQTT_send = (send_string) => {
            showToast('设置成功');
            console.log("MQTT 发送:" + JSON.stringify(send_string));
            if (/xazn/.test(navigator.userAgent) || /uni-app/.test(navigator.userAgent)) {
                uni.postMessage({
                    data: {
                        str: JSON.stringify(send_string)
                    }
                });
            } else {
                window.parent.postMessage({ str: JSON.stringify(send_string) }, "*");
            }
        };

        onMounted(async () => {
            await checkEnvironment();
            console.log(isLocal.value);

        }); return {
            value,
            overSpeedValue,
            screencontrol,
            addr,
            events,
            showItemPicker,
            showpinpicker,
            addEvent,
            removeEvent,
            onSelectlevel,
            onSelecttype,
            onSelectsource,
            onConfirmShowItem,
            onConfirmoutpin,
            onChange,
            uploadEventSettings,
            typeaction,
            levelactions,
            sourceaction,
            progremcolums,
            outpincolumns,
            checkEnvironment,
            onOverSpeedChange,
            onClose,
            eventfilldata,
            uploadthreshold,
            MQTT_send
        };
    },
};
</script>

<style scoped>
.home {
    padding: 20px;
    border-radius: 10px;
    border: 2px solid #0668fc;
    margin: 100px 10px 20px;
    flex: 1;
}

.title {
    text-align: center;
    font-size: 30px;
}

.slider-container {
    display: flex;
    align-items: center;
}

.title-control {
    text-align: left;
    font-size: 15px;
    margin: 0;
    white-space: nowrap;

}

.set-title {
    font-size: 15px;
    margin-right: 10px;
    white-space: nowrap;
}

.input-container {
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
}

.button-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
}

.switch-control {
    margin-left: auto;
}

.control {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 10px;
}

.event-item {
    margin-top: 20px;
    padding: 10px;
    border: 1px solid #e0e0e0;
    border-radius: 10px;
}

.delete-button {
    position: absolute;
    top: 50%;
    border-radius: 10px;
}
</style>
