<template>
  <div class="gateway-setting">
    <!-- 固定标题栏 -->
    <van-nav-bar title="事件列表" left-arrow @click-left="onClickLeft" fixed placeholder />

    <!-- 添加下拉刷新组件 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 标题栏 -->
      <!-- <van-nav-bar title="事件列表" left-arrow @click-left="onClickLeft" /> -->

      <!-- 在设备地址输入前添加无线设置 -->
      <van-cell-group inset>
        <van-cell title="模组概况">
          <!-- <template #right-icon>
            <van-button size="small" type="primary" @click="uploadLoRaConfig">上传配置</van-button>
          </template> -->
          <template #label>
            <div class="module-info">
              <div class="info-row">
                <span class="info-label">固件版本</span>
                <span class="info-value" ref="firmwareVersionEl"></span>
              </div>
              <div class="info-row">
                <span class="info-label">MAC地址</span>
                <span class="info-value" ref="macAddressEl"></span>
              </div>
              <div class="info-title">网络参数</div>
              <div class="info-row">
                <span class="info-label">网络ID</span>
                <van-field v-model="networkId" type="text" input-align="right" placeholder="请输入网络ID" maxlength="6"
                  :formatter="value => value.replace(/[^0-9]/g, '')" />
              </div>
              <div class="info-row">
                <span class="info-label">无线频段</span>
                <van-field v-model="freqBand" is-link readonly input-align="right" placeholder="请选择频段"
                  @click="showFreqBandPopup" />
              </div>
              <div class="info-row">
                <span class="info-label">信道</span>
                <van-field v-model="channel" is-link readonly input-align="right" placeholder="请选择信道"
                  @click="showChannelPopup" />
              </div>
              <div class="info-row">
                <span class="info-label">速率(SF)</span>
                <van-field v-model="speedRate" is-link readonly input-align="right" placeholder="请选择速率"
                  @click="showSpeedRatePopup" />
              </div>
              <div class="info-row">
                <span class="info-label">功率</span>
                <van-field v-model="power" is-link readonly input-align="right" placeholder="请选择功率"
                  @click="showPowerPopup" />
              </div>
              <div class="upload-button-container">
                <van-button type="primary" size="small" block @click="uploadLoRaConfig">上传配置</van-button>
              </div>
            </div>
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 设备地址输入 -->
      <van-cell-group inset>
        <van-field 
          v-model="deviceAddress" 
          label="设备地址" 
          placeholder="请输入设备地址" 
          input-align="right"
        />
        <van-cell center title="事件开关">
          <template #right-icon>
            <van-switch v-model="eventEnabled" size="24" />
          </template>
        </van-cell>
      </van-cell-group>

      <!-- 事件列表 -->
      <div class="event-list">
        <van-cell-group inset>
          <van-cell v-for="event in events" :key="event.id" :title="getEventTitle(event)" :label="getEventLabel(event)">
            <template #right-icon>
              <van-button size="small" type="primary" @click="editEvent(event)">编辑</van-button>
              <van-button size="small" type="danger" @click="showDeleteConfirm(event)"
                style="margin-left: 8px;">删除</van-button>
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 添加事件按钮，只有在事件开关打开时显示 -->
      <div class="add-button" v-if="eventEnabled">
        <van-button type="primary" block icon="plus" @click="showAddEventDialog">添加事件</van-button>
      </div>

      <!-- 添加/编辑事件弹出层 -->
      <van-popup v-model:show="dialogVisible" position="bottom" :style="{ height: '80%' }">
        <div class="popup-content">
          <van-nav-bar :title="isEdit ? '编辑事件' : '添加事件'" left-text="取消" right-text="确认"
            @click-left="dialogVisible = false" @click-right="saveEvent" />

          <div class="popup-body">
            <!-- 基础设置 -->
            <van-cell-group inset title="基础设置">
              <van-field v-model="currentEvent.type" is-link readonly label="事件类型" placeholder="请选择事件类型"
                input-align="right" @click="showTypePopup" />
              <!-- 当选择"其他"时显示的输入框 -->
              <van-field
                v-if="currentEvent.type === '其他'"
                v-model="customEventType"
                label="时间码"
                placeholder="请输入时间码"
                input-align="right"
                type="number"
              />
              
              <van-field v-model="currentEvent.source" is-link readonly label="事件来源" placeholder="请选择事件来源"
                input-align="right" @click="showSourcePopup" />
              <!-- 当选择"其他"时显示的输入框 -->
              <van-field
                v-if="currentEvent.source === '其他'"
                v-model="customEventSource"
                label="来源"
                placeholder="请输入来源"
                input-align="right"
                type="number"
              />
              
              <van-field v-model="currentEvent.priority" is-link readonly label="优先级" placeholder="请选择优先级"
                input-align="right" @click="showPriorityPopup" />
            </van-cell-group>

            <!-- 输出设置 -->
            <van-cell-group inset title="输出设置">
              <van-cell title="添加输出" is-link @click="showOutputPopup">
                <template #right-icon>
                  <van-icon name="plus" />
                </template>
              </van-cell>

              <!-- 已添加的输出列表 -->
              <template v-if="currentEvent.outputs && currentEvent.outputs.length > 0">
                <van-cell v-for="(output, index) in currentEvent.outputs" :key="index"
                  :title="getOutputTypeName(output.type)">
                  <template #label>
                    <!-- 显卡输出设置 -->
                    <div class="output-settings" v-if="output.type === '显卡输出'">
                      <van-field v-model="output.programNumber" label="节目编号" type="digit" input-align="right" />
                      <van-field v-model="output.duration" label="节目时长(秒)" type="digit" input-align="right" />
                    </div>

                    <!-- 声卡输出设置 -->
                    <div class="output-settings" v-if="output.type === '声卡输出'">
                      <van-field v-model="output.audioNumber" label="音频编号" type="digit" input-align="right" />
                    </div>

                    <!-- 路锥输出设置 -->
                    <div class="output-settings" v-if="output.type === '路锥输出'">
                      <van-field v-model="output.lightMode" is-link readonly label="灯光模式" input-align="right"
                        placeholder="请选择灯光模式" @click="showLightModePopup(index)" />
                    </div>

                    <!-- 引脚输出设置 -->
                    <div class="output-settings" v-if="output.type === '引脚模式'">
                      <van-cell title="选择引脚" :border="false">
                        <template #label>
                          <van-checkbox-group v-model="output.pins" direction="horizontal" class="pin-checkbox-group">
                            <van-checkbox name="0" shape="square">引脚0</van-checkbox>
                            <van-checkbox name="1" shape="square">引脚1</van-checkbox>
                            <van-checkbox name="2" shape="square">引脚2</van-checkbox>
                            <van-checkbox name="3" shape="square">引脚3</van-checkbox>
                          </van-checkbox-group>
                          <p style="text-align: center;">默认低电平，勾选后为高点平</p>

                        </template>
                      </van-cell>
                    </div>

                    <!-- 在输出设置部分添加自定义输入框 -->
                    <template v-if="output.type === '其他'">
                      <div class="output-settings">
                        <van-field
                          v-model="output.customTarget"
                          label="目标板卡号"
                          type="number"
                          input-align="right"
                          placeholder="请输入目标板卡号"
                        />
                        <div class="custom-data-inputs">
                          <van-field
                            v-model="output.customData1"
                            label="数据1"
                            type="number"
                            input-align="right"
                            placeholder="请输入数据1"
                          />
                          <van-field
                            v-model="output.customData2"
                            label="数据2"
                            type="number"
                            input-align="right"
                            placeholder="请输入数据2"
                          />
                          <van-field
                            v-model="output.customData3"
                            label="数据3"
                            type="number"
                            input-align="right"
                            placeholder="请输入数据3"
                          />
                        </div>
                      </div>
                    </template>
                  </template>
                  <template #right-icon>
                    <van-button size="small" type="danger" @click="removeOutput(index)">删除</van-button>
                  </template>
                </van-cell>
              </template>
            </van-cell-group>
          </div>
        </div>
      </van-popup>

      <!-- 选择器弹出层 -->
      <van-popup v-model:show="typePickerVisible" position="bottom">
        <van-picker :columns="eventTypes" @confirm="onTypeConfirm" @cancel="typePickerVisible = false" show-toolbar />
      </van-popup>

      <van-popup v-model:show="sourcePickerVisible" position="bottom">
        <van-picker :columns="timeSourceTypes" @confirm="onSourceConfirm" @cancel="sourcePickerVisible = false"
          show-toolbar />
      </van-popup>

      <van-popup v-model:show="priorityPickerVisible" position="bottom">
        <van-picker :columns="priorityLevels" @confirm="onPriorityConfirm" @cancel="priorityPickerVisible = false"
          show-toolbar />
      </van-popup>

      <!-- 输出类型选择弹出层 -->
      <van-popup v-model:show="outputPickerVisible" position="bottom">
        <van-picker :columns="outputTypes" @confirm="onOutputConfirm" @cancel="outputPickerVisible = false"
          show-toolbar />
      </van-popup>

      <!-- 添加灯光模式选择弹出层 -->
      <van-popup v-model:show="lightModePickerVisible" position="bottom">
        <van-picker :columns="lightModes" @confirm="onLightModeConfirm" @cancel="lightModePickerVisible = false"
          show-toolbar />
      </van-popup>

      <!-- 添加选择器弹出层 -->
      <van-popup v-model:show="freqBandPickerVisible" position="bottom">
        <van-picker :columns="freqBandOptions" @confirm="onFreqBandConfirm" @cancel="freqBandPickerVisible = false"
          show-toolbar />
      </van-popup>

      <van-popup v-model:show="channelPickerVisible" position="bottom">
        <van-picker :columns="channelOptions" @confirm="onChannelConfirm" @cancel="channelPickerVisible = false"
          show-toolbar />
      </van-popup>

      <van-popup v-model:show="speedRatePickerVisible" position="bottom">
        <van-picker :columns="speedRateOptions" @confirm="onSpeedRateConfirm" @cancel="speedRatePickerVisible = false"
          show-toolbar />
      </van-popup>

      <van-popup v-model:show="powerPickerVisible" position="bottom">
        <van-picker :columns="powerOptions" @confirm="onPowerConfirm" @cancel="powerPickerVisible = false"
          show-toolbar />
      </van-popup>
    </van-pull-refresh>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, watch } from 'vue';
// import { showConfirmDialog, showToast } from 'vant';
import { useRouter } from 'vue-router';
import axios from 'axios';
// import { connectMQTT, client } from "../../components/MQTT/mqttclient";

export default {
  name: 'GatewaySetting',
  setup() {
    const router = useRouter();
    const deviceAddress = ref('');
    const eventEnabled = ref(false);
    const events = ref([]);
    const dialogVisible = ref(false);
    const isEdit = ref(false);

    // 选择器相关
    const typePickerVisible = ref(false);
    const sourcePickerVisible = ref(false);
    const priorityPickerVisible = ref(false);
    const outputPickerVisible = ref(false);

    // 添加无线设置相关的响应式变量
    const networkId = ref('');
    const freqBand = ref('');
    const channel = ref('');
    const speedRate = ref('');
    const power = ref('');

    // 添加选择器显示状态
    const freqBandPickerVisible = ref(false);
    const channelPickerVisible = ref(false);
    const speedRatePickerVisible = ref(false);
    const powerPickerVisible = ref(false);

    // 添加选项数据
    const freqBandOptions = [
      { text: '433MHz(430MHz-446MHz)', value: 0 },
      { text: '470MHz(454MHz-469MHz)', value: 1 },
      { text: '480MHz(470MHz-486MHz)', value: 2 },
      { text: '500MHz(494MHz-509MHz)', value: 3 }
    ];

    const channelOptions = Array.from({ length: 32 }, (_, i) => ({
      text: `信道${i + 1}`,
      value: i
    }));

    const speedRateOptions = [
      { text: '62.5kbps', value: 0 },
      { text: '37.5kbps', value: 1 },
      { text: '21.8kbps', value: 2 },
      { text: '12.5kbps', value: 3 },
      { text: '7.0kbps', value: 4 },
      { text: '3.9kbps', value: 5 },
      { text: '2.1kbps', value: 6 }
    ];

    const powerOptions = [
      { text: '22dbm', value: 0 },
      { text: '20dbm', value: 1 },
      { text: '17dbm', value: 2 },
      { text: '14dbm', value: 3 },
      { text: '11dbm', value: 4 },
      { text: '8dbm', value: 5 },
      { text: '5dbm', value: 6 },
      { text: '2dbm', value: 7 }
    ];

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

    const timeSourceTypes = [
      { text: '本台设备', value: 0x00 },
      { text: '任意设备(除本身外任意设备)', value: 0xfe },
      { text: '任意设备', value: 0xff },
      { text: '其他', value: 'other' }
    ];

    const priorityLevels = [
      { text: '0', value: 0 },
      { text: '1', value: 1 },
      { text: '2', value: 2 },
      { text: '3', value: 3 },
      { text: '4', value: 4 },
      { text: '5', value: 5 },
      { text: '6', value: 6 },
      { text: '7', value: 7 },
      { text: '8', value: 8 },
      { text: '9', value: 9 },
      { text: '10', value: 10 },
    ];

    const outputTypes = [
      { text: '显卡输出', value: 'display' },
      { text: '声卡输出', value: 'audio' },
      { text: '路锥输出', value: 'serial' },
      { text: '引脚模式', value: 'io' },
      { text: '其他', value: 'other' }
    ];

    const currentEvent = reactive({
      type: '',
      source: '',
      priority: '',
      outputs: []
    });

    // 添加灯光模式相关的状态和函数
    const lightModePickerVisible = ref(false);
    const currentEditingOutputIndex = ref(-1);
    const lightModes = [
      { text: '常亮', value: '0' },
      { text: '闪烁', value: '1' },
      { text: '呼吸', value: '2' }
    ];

    // 添加 ref 引用
    const firmwareVersionEl = ref(null);
    const macAddressEl = ref(null);

    // 添加 WebSocket 相关变量
    const ws = ref(null);

    // 在 setup 函数中添加新的响应式变量
    const customEventType = ref('');
    const customEventSource = ref('');

    const onClickLeft = () => {
      router.back();
    };

    const showTypePopup = () => {
      typePickerVisible.value = true;
    };

    const showSourcePopup = () => {
      sourcePickerVisible.value = true;
    };

    const showPriorityPopup = () => {
      priorityPickerVisible.value = true;
    };

    const showOutputPopup = () => {
      outputPickerVisible.value = true;
    };

    const onTypeConfirm = (value) => {
      currentEvent.type = value.selectedOptions[0].text;
      typePickerVisible.value = false;
    };

    const onSourceConfirm = (value) => {
      currentEvent.source = value.selectedOptions[0].text;
      sourcePickerVisible.value = false;
    };

    const onPriorityConfirm = (value) => {
      currentEvent.priority = value.selectedOptions[0].text;
      priorityPickerVisible.value = false;
    };

    const onOutputConfirm = (value) => {
      const outputType = value.selectedOptions[0].text;
      const output = {
        type: outputType,
        ...(outputType === '显卡输出' ? {
          programNumber: '1',
          duration: '10'
        } : {}),
        ...(outputType === '声卡输出' ? {
          audioNumber: '1'
        } : {}),
        ...(outputType === '路锥输出' ? {
          lightMode: '常亮'
        } : {}),
        ...(outputType === '引脚模式' ? {
          pins: []
        } : {}),
        ...(outputType === '其他' ? {
          customTarget: '0',
          customData1: '0',
          customData2: '0',
          customData3: '0'
        } : {})
      };
      currentEvent.outputs.push(output);
      outputPickerVisible.value = false;
    };

    const showAddEventDialog = () => {
      isEdit.value = false;
      Object.assign(currentEvent, {
        type: '',
        source: '',
        priority: '',
        outputs: []
      });
      dialogVisible.value = true;
    };

    const removeOutput = (index) => {
      currentEvent.outputs.splice(index, 1);
    };

    const saveEvent = () => {
      // 检查必填字段
      if (!currentEvent.type || !currentEvent.source || !currentEvent.priority || currentEvent.outputs.length  === 0) {
        showToast('请填写所有必填字段并至少添加一个输出');
        return;
      }

      // 检查自定义输入
      if (currentEvent.type === '其他' && !customEventType.value) {
        showToast('请填写自定义事件类型');
        return;
      }
      if (currentEvent.source === '其他' && !customEventSource.value) {
        showToast('请填写自定义事件来源');
        return;
      }

      const outputs = currentEvent.outputs.map(output => {
        let target = 0;
        let data = [0, 0, 0];

        switch (output.type) {
          case '显卡输出':
            target = 102;
            data = [
              parseInt(output.programNumber) || 0,
              parseInt(output.duration) || 10,
              0
            ];
            break;
          case '声卡输出':
            target = 103;
            data = [
              parseInt(output.audioNumber) || 0,
              0,
              0
            ];
            break;
          case '路锥输出':
            target = 106;
            data = [
              lightModes.find(mode => mode.text === output.lightMode)?.value || 0,
              0,
              0
            ];
            break;
          case '引脚模式':
            target = 1;
            const pinValue = output.pins.reduce((acc, pin) => acc | (1 << parseInt(pin)), 0);
            data = [pinValue, 0, 0];
            break;
          case '其他':
            target = parseInt(output.customTarget) || 0;
            data = [
              parseInt(output.customData1) || 0,
              parseInt(output.customData2) || 0,
              parseInt(output.customData3) || 0
            ];
            break;
        }

        return { target, data };
      });

      const eventConfig = {
        board_id: 1,
        JSON_id: jsonId.value,
        gateway: {
          trig_cfg: {
            event_group: [{
              index: events.value.length,
              // 根据是否为"其他"选择使用自定义值还是预设值
              event_id: currentEvent.type === '其他' 
                ? parseInt(customEventType.value)
                : parseInt(eventTypes.find(type => type.text === currentEvent.type)?.value || '0'),
              source: currentEvent.source === '其他'
                ? parseInt(customEventSource.value)
                : timeSourceTypes.find(source => source.text === currentEvent.source)?.value || 0,
              priority: parseInt(currentEvent.priority),
              output: outputs
            }]
          }
        }
      };

      console.log('Saving event config:', eventConfig);

      // 发送配置
      if (isLocal.value) {
        axios.post('/communication', eventConfig, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Save response:', response.data);
            showToast('保存成功');
            jsonId.value++;

            // 更新本地事件列表
            if (isEdit.value) {
              const index = events.value.findIndex(e => e.id === currentEvent.id);
              if (index !== -1) {
                events.value[index] = {
                  ...currentEvent,
                  index: eventConfig.gateway.trig_cfg.event_group[0].index
                };
              }
            } else {
              events.value.push({
                id: Date.now(),
                ...currentEvent,
                index: eventConfig.gateway.trig_cfg.event_group[0].index
              });
            }
            dialogVisible.value = false;
          })
          .catch(error => {
            console.error('Save error:', error);
            showToast('保存失败');
            jsonId.value++;
          });
      } else {
        MQTT_send(eventConfig);
        if (isEdit.value) {
          const index = events.value.findIndex(e => e.id === currentEvent.id);
          if (index !== -1) {
            events.value[index] = {
              ...currentEvent,
              index: eventConfig.gateway.trig_cfg.event_group[0].index
            };
          }
        } else {
          events.value.push({
            id: Date.now(),
            ...currentEvent,
            index: eventConfig.gateway.trig_cfg.event_group[0].index
          });
        }
        dialogVisible.value = false;
      }
    };

    const editEvent = (event) => {
      isEdit.value = true;
      Object.assign(currentEvent, event);
      dialogVisible.value = true;
    };

    const showDeleteConfirm = (event) => {
      showConfirmDialog({
        title: '确认删除',
        message: '是否确认删除该事件？',
      }).then(() => {
        deleteEvent(event);
      });
    };

    const deleteEvent = (event) => {
      // 构建删除事件的配置
      const deleteConfig = {
        "JSON_id": jsonId.value,
        "board_id": 1,
        "gateway": {
          "trig_cfg": {
            "event_en": eventEnabled.value ? 1 : 0,
            "addr": parseInt(deviceAddress.value) || 0,
            "operate": 3,
            "event_group": [
              {
                "index": event.index
              }
            ]
          }
        }
      };

      console.log('Deleting event:', deleteConfig);

      // 发送删除配置
      if (isLocal.value) {
        axios.post('/communication', deleteConfig, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Delete response:', response.data);
            showToast('删除成功');
            jsonId.value++;

            // 更新本地事件列表
            const index = events.value.findIndex(e => e.id === event.id);
            if (index !== -1) {
              events.value.splice(index, 1);
            }
          })
          .catch(error => {
            console.error('Delete error:', error);
            showToast('删除失败');
            jsonId.value++;
          });
      } else {
        MQTT_send(deleteConfig);
        // 更新本地事件列表
        const index = events.value.findIndex(e => e.id === event.id);
        if (index !== -1) {
          events.value.splice(index, 1);
        }
      }
    };

    const getEventTitle = (event) => {
      return `${event.type} - ${event.priority}优先级`;
    };

    const getEventLabel = (event) => {
      return `来源: ${event.source} | 输出: ${event.outputs.map(o => o.type).join(', ')}`;
    };

    const getOutputTypeName = (type) => {
      return type;
    };

    const showLightModePopup = (index) => {
      currentEditingOutputIndex.value = index;
      lightModePickerVisible.value = true;
    };

    const onLightModeConfirm = (value) => {
      if (currentEditingOutputIndex.value !== -1) {
        currentEvent.outputs[currentEditingOutputIndex.value].lightMode = value.selectedOptions[0].text;
      }
      lightModePickerVisible.value = false;
      currentEditingOutputIndex.value = -1;
    };

    // 添加方法
    const showFreqBandPopup = () => freqBandPickerVisible.value = true;
    const showChannelPopup = () => channelPickerVisible.value = true;
    const showSpeedRatePopup = () => speedRatePickerVisible.value = true;
    const showPowerPopup = () => powerPickerVisible.value = true;

    const onFreqBandConfirm = (value) => {
      freqBand.value = value.selectedOptions[0].text;
      freqBandPickerVisible.value = false;
    };

    const onChannelConfirm = (value) => {
      channel.value = value.selectedOptions[0].text;
      channelPickerVisible.value = false;
    };

    const onSpeedRateConfirm = (value) => {
      speedRate.value = value.selectedOptions[0].text;
      speedRatePickerVisible.value = false;
    };

    const onPowerConfirm = (value) => {
      power.value = value.selectedOptions[0].text;
      powerPickerVisible.value = false;
    };

    // 添加下拉刷新相关的变量
    const refreshing = ref(false);
    const isLocal = ref(true); // 用于判断是否为本地模式
    const jsonId = ref(1);
    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 MQTT_send = (send_string) => {
      showToast('设置成功');
      jsonId.value++;
      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) }, "*");
      }
    };
    // 获取配置信息
    const getLoRaConfig = () => {
      const configData = {
        "board_id": 1,
        "JSON_id": jsonId.value,
        "gateway": {
          "get_LoRa_cfg": 1,
          "get_cfg": 1,
        },
      };

      console.log('Sending config request:', configData);

      if (isLocal.value) {
        axios.post('/communication', configData, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Response data:', response.data);
            // 更新界面数据
            updateConfigData(response.data);
            showToast('获取成功');
            jsonId.value++;
          })
          .catch(error => {
            console.error('Get config error:', error);
            showToast('获取失败');
            jsonId.value++;
          });
      } else {
        MQTT_send(configData);
      }
    };

    // 更新配置数据到界面
    const updateConfigData = (data) => {
      // 更新 LoRa 配置
      if (data && data.gateway && data.gateway.LoRa_cfg) {
        const config = data.gateway.LoRa_cfg;

        // 更新固件版本
        if (firmwareVersionEl.value) {
          firmwareVersionEl.value.textContent = config.versions;
        }

        // 更新MAC地址
        if (macAddressEl.value) {
          const macAddress = config.mac_addr.map(num => num.toString(16).padStart(2, '0').toUpperCase()).join(' ');
          macAddressEl.value.textContent = macAddress;
        }

        // 更新网络ID
        networkId.value = config.mesh_id.map(num => num.toString(16).padStart(2, '0').toUpperCase()).join('');

        // 更新频段
        freqBand.value = getFreqBandText(config.fre_band);

        // 更新信道
        channel.value = `信道${(config.channel + 1)}`;

        // 更新速率
        speedRate.value = getSpeedRateText(config.SF);

        // 更新功率
        power.value = getPowerText(config.power);
      }

      // 更新事件配置
      if (data && data.gateway && data.gateway.trig_cfg) {
        const trigConfig = data.gateway.trig_cfg;

        // 更新事件开关状态
        eventEnabled.value = trigConfig.event_en === 1;

        // 更新设备地址
        deviceAddress.value = trigConfig.addr.toString();

        // 更新事件列表
        events.value = trigConfig.event_group.map(event => {
          // 转换输出配置
          const outputs = event.output.map(output => {
            let type = '';
            let config = {};

            // 根据目标类型设置输出配置
            switch (output.target) {
              case 102: // 显卡输出
                type = '显卡输出';
                config = {
                  programNumber: output.data[0].toString(),
                  duration: output.data[1].toString()
                };
                break;
              case 103: // 声卡输出
                type = '声卡输出';
                config = {
                  audioNumber: output.data[0].toString()
                };
                break;
              case 106: // 路锥输出
                type = '路锥输出';
                config = {
                  lightMode: lightModes.find(mode => mode.value === output.data[0].toString())?.text || '常亮'
                };
                break;
              case 1: // 引脚输出
                type = '引脚模式';
                const pinValue = output.data[0];
                config = {
                  pins: Array.from({ length: 4 }, (_, i) => ((pinValue >> i) & 1) === 1 ? i.toString() : null)
                    .filter(pin => pin !== null)
                };
                break;
            }

            return {
              type,
              ...config
            };
          });

          return {
            id: Date.now() + event.index, // 生成唯一ID
            index: event.index,
            type: eventTypes.find(type => parseInt(type.value) === event.event_id)?.text || '其他',
            source: timeSourceTypes.find(source => source.value === event.source)?.text || '本台设备',
            priority: event.priority.toString(),
            outputs
          };
        });
      }
    };

    // 辅助函数：获取频段文本
    const getFreqBandText = (value) => {
      const band = freqBandOptions.find(option => option.value === value);
      return band ? band.text : '';
    };

    // 辅助函数：获取速率文本
    const getSpeedRateText = (value) => {
      const rate = speedRateOptions.find(option => option.value === value);
      return rate ? rate.text : '';
    };

    // 辅助函数：获取功率文本
    const getPowerText = (value) => {
      const pow = powerOptions.find(option => option.value === value);
      return pow ? pow.text : '';
    };

    // 下拉刷新处理函数
    const onRefresh = () => {
      getLoRaConfig();
      setTimeout(() => {
        refreshing.value = false;
      }, 1000);
    };

    // 在 setup 函数中添加以下方法
    const sendDeviceAddressConfig = () => {
      const configData = {
        "board_id": 1,
        "JSON_id": jsonId.value,
        "gateway": {
          "device_addr": deviceAddress.value
        }
      };

      console.log('Sending device address config:', configData);

      if (isLocal.value) {
        axios.post('/communication', configData, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Device address config response:', response.data);
            showToast('设备设置成功');
            jsonId.value++;
          })
          .catch(error => {
            console.error('Device address config error:', error);
            showToast('设备设置失败');
            jsonId.value++;
          });
      } else {
        MQTT_send(configData);
      }
    };

    const sendEventSwitchConfig = () => {
      const configData = {
        "board_id": 1,
        "JSON_id": jsonId.value,
        "gateway": {
          "event_enable": eventEnabled.value ? 1 : 0
        }
      };

      console.log('Sending event switch config:', configData);

      if (isLocal.value) {
        axios.post('/communication', configData, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Event switch config response:', response.data);
            showToast('事件开关打开成功');
            jsonId.value++;
          })
          .catch(error => {
            console.error('Event switch config error:', error);
            showToast('事件开关打开失败');
            jsonId.value++;
          });
      } else {
        MQTT_send(configData);
      }
    };

    // 监听设备地址的变化
    let deviceAddressTimeout;
    watch(deviceAddress, (newValue, oldValue) => {
      if (newValue && newValue !== oldValue) {
        // 使用 setTimeout 来确保输入完成后再发送
        if (deviceAddressTimeout) {
          clearTimeout(deviceAddressTimeout);
        }
        deviceAddressTimeout = setTimeout(() => {
          sendDeviceAddressConfig();
        }, 1000); // 1秒后发送
      }
    });

    // 监听事件开关的变化
    watch(eventEnabled, () => {
      sendEventSwitchConfig();
    });

    // 组件挂载时初始化连接
    onMounted(() => {
      checkEnvironment();
      getLoRaConfig();
    });

    // 组件卸载前断开连接
    onBeforeUnmount(() => {

    });

    // 在 setup 中添加上传配置方法
    const uploadLoRaConfig = () => {
      // 检查必填字段是否为空
      if (!networkId.value || !freqBand.value || !channel.value || !speedRate.value || !power.value || !customEventType.value || !customEventSource.value) {
        showToast('请填写所有必填字段');
        return;
      }

      // 将十进制字符串转换为十六进制数组
      const meshId = networkId.value.match(/.{2}/g)?.map(hex => parseInt(hex, 10)) || [0, 0, 0];

      // 获取各个选项的值
      const freqBandValue = freqBandOptions.find(option => option.text === freqBand.value)?.value || 0;
      const channelValue = parseInt(channel.value.replace('信道', '')) - 1;
      const speedRateValue = speedRateOptions.find(option => option.text === speedRate.value)?.value || 0;
      const powerValue = powerOptions.find(option => option.text === power.value)?.value || 0;

      const configData = {
        "board_id": 1,
        "JSON_id": jsonId.value,
        "gateway": {
          "LoRa_cfg": {
            "mesh_id": meshId,
            "fre_band": freqBandValue,
            "channel": channelValue,
            "SF": speedRateValue,
            "power": powerValue,
            "mode": 0
          }
        }
      };

      console.log('Uploading config:', configData);

      if (isLocal.value) {
        axios.post('/communication', configData, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Upload response:', response.data);
            showToast('上传成功');
            jsonId.value++;
          })
          .catch(error => {
            console.error('Upload error:', error);
            showToast('上传失败');
            jsonId.value++;
          });
      } else {
        MQTT_send(configData);
      }
    };

    return {
      deviceAddress,
      eventEnabled,
      events,
      dialogVisible,
      isEdit,
      currentEvent,
      typePickerVisible,
      sourcePickerVisible,
      priorityPickerVisible,
      outputPickerVisible,
      eventTypes,
      timeSourceTypes,
      priorityLevels,
      outputTypes,
      onClickLeft,
      showTypePopup,
      showSourcePopup,
      showPriorityPopup,
      showOutputPopup,
      onTypeConfirm,
      onSourceConfirm,
      onPriorityConfirm,
      onOutputConfirm,
      showAddEventDialog,
      removeOutput,
      saveEvent,
      editEvent,
      showDeleteConfirm,
      getEventTitle,
      getEventLabel,
      getOutputTypeName,
      lightModePickerVisible,
      lightModes,
      showLightModePopup,
      onLightModeConfirm,
      networkId,
      freqBand,
      channel,
      speedRate,
      power,
      freqBandPickerVisible,
      channelPickerVisible,
      speedRatePickerVisible,
      powerPickerVisible,
      freqBandOptions,
      channelOptions,
      speedRateOptions,
      powerOptions,
      showFreqBandPopup,
      showChannelPopup,
      showSpeedRatePopup,
      showPowerPopup,
      onFreqBandConfirm,
      onChannelConfirm,
      onSpeedRateConfirm,
      onPowerConfirm,
      refreshing,
      onRefresh,
      checkEnvironment,
      uploadLoRaConfig,
      firmwareVersionEl,
      macAddressEl,
      ws,
      sendDeviceAddressConfig,
      sendEventSwitchConfig,
      customEventType,
      customEventSource,
    };
  }
};
</script>

<style scoped>
.gateway-setting {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

/* 确保标题栏在最上层 */
:deep(.van-nav-bar) {
  z-index: 999;
}

/* 添加这个样式来设置 van-cell-group 之间的间距 */
.gateway-setting :deep(.van-cell-group) {
  margin-bottom: 12px;
}

.event-list {
  margin-top: 12px;
}

.add-button {
  margin: 16px;
}

.popup-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.popup-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
}

:deep(.van-cell-group__title) {
  padding: 20px 16px 12px;
}

.output-settings {
  margin-top: 12px;
  margin-bottom: 12px;
}

.output-settings :deep(.van-field) {
  padding: 12px 0;
}

.pin-checkbox-group {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-top: 12px;
  margin-bottom: 8px;
}

.pin-checkbox-group :deep(.van-checkbox) {
  margin: 0;
  padding: 10px;
}

.output-settings :deep(.van-cell) {
  padding: 12px 0;
}

.output-settings :deep(.van-field__label) {
  width: 6em;
}

.module-info {
  padding: 8px 0;
}

.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
  justify-content: space-between;
}

.info-label {
  min-width: 80px;
  color: #646566;
  flex-shrink: 0;
}

.info-row :deep(.van-field) {
  flex: 1;
  padding: 0;
  background: transparent;
  margin-left: 8px;
}

.info-row :deep(.van-field__body) {
  min-height: unset;
}

.info-row :deep(.van-cell) {
  padding: 0;
}

.info-row :deep(.van-field__control) {
  min-height: unset;
  text-align: right;
}

.info-row :deep(.van-field__right-icon) {
  margin-left: 8px;
}

.info-value {
  text-align: right;
  flex: 1;
  margin-left: 8px;
}

.info-title {
  font-weight: bold;
  margin-bottom: 12px;
}

/* 添加下拉刷新相关样式 */
:deep(.van-pull-refresh) {
  min-height: 100vh;
  background-color: #f7f8fa;
}

.custom-data-inputs {
  margin-top: 8px;
}

.custom-data-inputs :deep(.van-field) {
  margin-bottom: 8px;
}
</style>