<template>
  <div class="cone-control">
    <van-nav-bar title="路锥控制" left-arrow @click-left="onClickLeft" fixed />

    <!-- 添加下拉刷新组件 -->
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <!-- 为模组概况添加边框 -->
      <div class="module-container">
        <div class="module-header">
          <van-icon name="setting-o" size="18" />
          <span>模组概况</span>
        </div>
        <van-cell-group inset>
          <van-cell title="模组概况">
            <template #label>
              <div class="module-info">
                <div class="info-row">
                  <span class="info-label">固件版本</span>
                  <span class="info-value" ref="firmwareVersionEl">{{ firmwareVersion }}</span>
                </div>
                <div class="info-row">
                  <span class="info-label">MAC地址</span>
                  <span class="info-value" ref="macAddressEl">{{ macAddress }}</span>
                </div>
                <div class="info-title">网络参数</div>

                <div class="info-row">
                  <span class="info-label">网络ID</span>
                  <van-field v-model="networkId" readonly input-align="right" />
                </div>
                <div class="info-row">
                  <span class="info-label">无线频段</span>
                  <van-field v-model="freqBand" readonly input-align="right" />
                </div>
                <div class="info-row">
                  <span class="info-label">信道</span>
                  <van-field v-model="channel" readonly input-align="right" />
                </div>
                <div class="info-row">
                  <span class="info-label">速率(SF)</span>
                  <van-field v-model="speedRate" readonly input-align="right" />
                </div>
                <div class="info-row">
                  <span class="info-label">功率</span>
                  <van-field v-model="power" readonly input-align="right" />
                </div>
                <div class="mode-container">
                  <div class="info-row mode-row">
                    <span class="info-label">网络通道</span>
                    <van-field v-model="currentMode" is-link readonly input-align="right" placeholder="请选择网络通道"
                      @click="showModePopup" class="mode-field" />
                  </div>
                </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>
      </div>

      <!-- 状态和控制面板 -->
      <div class="status-container">
        <div class="module-header">
          <van-icon name="info-o" size="18" />
          <span>状态与控制</span>
        </div>
        <van-cell-group inset>

          <!-- 报警状态（只读） -->
          <van-cell title="报警状态">
            <template #value>
              <span :style="{ color: alarmStatus === '正常' ? '#07c160' : '#ee0a24' }">{{ alarmStatus }}</span>
            </template>
            <template #right-icon>
              <van-button v-if="alarmStatus !== '正常'" size="small" type="danger"
                @click="sendCommand('clearAlarm')">清除报警</van-button>
            </template>
          </van-cell>

          <!-- 灯光状态选择 -->
          <van-cell title="灯光状态" :value="lightStatus" is-link @click="showLightStatusPicker" />

          <!-- 布防开关 -->
          <van-cell center title="布防开关">
            <template #right-icon>
              <van-switch v-model="defenseEnabled" size="24" @change="onDefenseChange" />
            </template>
          </van-cell>
        </van-cell-group>
      </div>

      <!-- 灯光状态选择器 -->
      <van-popup v-model:show="lightStatusPickerVisible" position="bottom">
        <van-picker :columns="lightStatusOptions" @confirm="onLightStatusConfirm"
          @cancel="lightStatusPickerVisible = false" show-toolbar />
      </van-popup>

      <!-- 添加模式选择器 -->
      <van-popup v-model:show="modePickerVisible" position="bottom">
        <van-picker :columns="modeOptions" @confirm="onModeConfirm" @cancel="modePickerVisible = false" show-toolbar />
      </van-popup>
    </van-pull-refresh>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, computed } from 'vue';
import { useRouter } from 'vue-router';
// import { showToast } from 'vant';
import axios from 'axios';

export default {
  name: 'ConeControl',
  setup() {
    const router = useRouter();
    const networkId = ref('');
    const freqBand = ref('');
    const channel = ref('');
    const speedRate = ref('');
    const power = ref('');
    const firmwareVersionEl = ref(null);
    const macAddressEl = ref(null);
    const jsonId = ref(1);
    const isLocal = ref(true);
    const freqBandPickerVisible = ref(false);
    const channelPickerVisible = ref(false);
    const speedRatePickerVisible = ref(false);
    const powerPickerVisible = ref(false);
    const alarmStatus = ref('报警');
    const lightStatus = ref('白灯亮');
    const defenseEnabled = ref(false);
    const lightStatusPickerVisible = ref(false);
    const refreshing = ref(false);
    const firmwareVersion = ref('');
    const macAddress = ref('');
    const modePickerVisible = ref(false);
    const currentMode = ref('');

    // 选项数据
    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 lightStatusOptions = [
      { text: '白光亮(高)', value: 0 },
      { text: '白光亮(中)', value: 1 },
      { text: '白光亮(低)', value: 2 },
      { text: '红蓝快闪', value: 3 },
      { text: '红蓝慢闪', value: 4 },
      { text: '投射灯亮', value: 5 },
      { text: '关闭', value: 6 }
    ];

    const modeOptions = [
      { text: '通道一', value: 0, networkId: '6A6A00' },
      { text: '通道二', value: 1, networkId: '6A6A01' },
      { text: '通道三', value: 2, networkId: '6A6A02' },
      { text: '通道四', value: 3, networkId: '6A6A03' }
    ];

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

    const showFreqBandPopup = () => {
      freqBandPickerVisible.value = true;
    };

    const showChannelPopup = () => {
      channelPickerVisible.value = true;
    };

    const showSpeedRatePopup = () => {
      speedRatePickerVisible.value = true;
    };

    const showPowerPopup = () => {
      powerPickerVisible.value = true;
    };

    const showLightStatusPicker = () => {
      lightStatusPickerVisible.value = true;
    };

    const showModePopup = () => {
      modePickerVisible.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 onLightStatusConfirm = (value) => {
      lightStatus.value = value.selectedOptions[0].text;
      lightStatusPickerVisible.value = false;
      sendLightStatusCommand(value.selectedOptions[0].value);
    };

    const sendLightStatusCommand = (value) => {
      const lightStatusCommand = {
        board_id: 106,
        JSON_id: 1,
        cones_card: {
          traffic_cone: {
            lamplight: value
          }
        },
        error_code: 0
      };
      if (isLocal.value) {
        axios.post('/communication', lightStatusCommand, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Light status response:', response.data);
          })
          .catch(error => {
            console.error('Light status error:', error);
          });
      } else {
        MQTT_send(lightStatusCommand);
      }
    };

    const onDefenseChange = (value) => {
      const defenseCommand = {
        board_id: 106,
        JSON_id: 1,
        cones_card: {
          traffic_cone: {
            mode: value ? 1 : 0
          }
        },
        error_code: 0
      };
      if (isLocal.value) {
        axios.post('/communication', defenseCommand, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Defense mode response:', response.data);
          })
          .catch(error => {
            console.error('Defense mode error:', error);
          });
      } else {
        MQTT_send(defenseCommand);
      }
    };

    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 uploadLoRaConfig = () => {
      // 检查必填字段是否为空
      if (!networkId.value || !freqBand.value || !channel.value || !speedRate.value || !power.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);
      }
    };

    const sendCommand = (command) => {
      if (command === 'clearAlarm') {
        const clearAlarmCommand = {
          board_id: 106,
          JSON_id: 1,
          cones_card: {
            traffic_cone: {
              alarm: 0
            }
          },
          error_code: 0
        };
        if (isLocal.value) {
          axios.post('/communication', clearAlarmCommand, {
            headers: {
              "content-type": "application/json"
            }
          })
            .then(response => {
              console.log('Clear alarm response:', response.data);
              alarmStatus.value = '正常';
            })
            .catch(error => {
              console.error('Clear alarm error:', error);
            });
        } else {
          MQTT_send(clearAlarmCommand);
        }
      }
    };

    const onModeConfirm = (value) => {
      currentMode.value = value.selectedOptions[0].text;
      networkId.value = value.selectedOptions[0].networkId;
      modePickerVisible.value = false;

      // 发送配置更新命令
      const configData = {
        board_id: 106,
        JSON_id: 1,
        cones_card: {
          LoRa_cfg: {
            mesh_id: [
              parseInt(networkId.value.slice(0, 2), 16),
              parseInt(networkId.value.slice(2, 4), 16),
              parseInt(networkId.value.slice(4, 6), 16)
            ],
            fre_band: freqBandOptions.find(option => option.text === freqBand.value)?.value || 0,
            channel: channel.value ? (parseInt(channel.value.match(/\d+/)?.[0] || '1') - 1) : 0,
            SF: speedRateOptions.find(option => option.text === speedRate.value)?.value || 0,
            power: powerOptions.find(option => option.text === power.value)?.value || 0,
            mode: value.selectedOptions[0].value
          }
        },
        error_code: 0
      };

      if (isLocal.value) {
        axios.post('/communication', configData, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {
            console.log('Mode update response:', response.data);
          })
          .catch(error => {
            console.error('Mode update error:', error);
          });
      } else {
        MQTT_send(configData);
      }
    };

    const updateStateFromResponse = (data) => {
      // 检查数据结构
      if (!data || !data.cones_card) {
        console.error('Invalid response data structure');
        return;
      }

      // 更新 LoRa 配置相关状态
      if (data.cones_card.LoRa_cfg) {
        const loraConfig = data.cones_card.LoRa_cfg;
        firmwareVersion.value = loraConfig.versions;
        macAddress.value = loraConfig.mac_addr.join(':');
        networkId.value = loraConfig.mesh_id.map(num => num.toString(16).padStart(2, '0').toUpperCase()).join('');
        freqBand.value = freqBandOptions.find(option => option.value === loraConfig.fre_band)?.text || '';
        channel.value = `信道${loraConfig.channel + 1}`;
        speedRate.value = speedRateOptions.find(option => option.value === loraConfig.SF)?.text || '';
        power.value = powerOptions.find(option => option.value === loraConfig.power)?.text || '';

        // 更新当前模式
        const mode = modeOptions.find(option => option.networkId === networkId.value);
        if (mode) {
          currentMode.value = mode.text;
        }
      }

      // 更新路锥状态
      if (data.cones_card.traffic_cone) {
        const trafficCone = data.cones_card.traffic_cone;
        // 更新报警状态
        alarmStatus.value = trafficCone.alarm === 1 ? '报警' : '正常';

        // 更新灯光状态
        const lightOption = lightStatusOptions.find(option => option.value === trafficCone.lamplight);
        if (lightOption) {
          lightStatus.value = lightOption.text;
        }

        // 更新布防状态
        defenseEnabled.value = trafficCone.mode === 1;
      }
    };

    const onRefresh = () => {
      const refreshCommand = {
        board_id: 106,
        JSON_id: 1,
        cones_card: {
          get_traffic_cone: 1,
          get_LoRa_cfg: 1
        },
        error_code: 0
      };
      if (isLocal.value) {
        axios.post('/communication', refreshCommand, {
          headers: {
            "content-type": "application/json"
          }
        })
          .then(response => {               
            console.log('Refresh response:', response.data);
            // 直接传递整个响应数据
            updateStateFromResponse(response.data);
            refreshing.value = false;
          })
          .catch(error => {
            console.error('Refresh error:', error);
            refreshing.value = false;
          });
      } else {
        MQTT_send(refreshCommand);
        refreshing.value = false;
      }
    };

    onMounted(() => {
      checkEnvironment();
      onRefresh();
    });

    return {
      networkId,
      freqBand,
      channel,
      speedRate,
      power,
      firmwareVersionEl,
      macAddressEl,
      onClickLeft,
      showFreqBandPopup,
      showChannelPopup,
      showSpeedRatePopup,
      showPowerPopup,
      uploadLoRaConfig,
      sendCommand,
      freqBandPickerVisible,
      channelPickerVisible,
      speedRatePickerVisible,
      powerPickerVisible,
      onFreqBandConfirm,
      onChannelConfirm,
      onSpeedRateConfirm,
      onPowerConfirm,
      freqBandOptions,
      channelOptions,
      speedRateOptions,
      powerOptions,
      alarmStatus,
      lightStatus,
      defenseEnabled,
      lightStatusPickerVisible,
      lightStatusOptions,
      showLightStatusPicker,
      onLightStatusConfirm,
      onDefenseChange,
      refreshing,
      onRefresh,
      firmwareVersion,
      macAddress,
      modePickerVisible,
      currentMode,
      modeOptions,
      showModePopup,
      onModeConfirm,
    };
  }
};
</script>

<style scoped>
.cone-control {
  padding-top: 46px;
  /* 为固定的导航栏留出空间 */
  background-color: #f7f8fa;
  min-height: 100vh;
}

.module-container {
  margin: 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
  overflow: hidden;
}

.module-header {
  padding: 16px;
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  border-bottom: 1px solid #f5f5f5;
  display: flex;
  align-items: center;
  gap: 8px;
}

.status-container {
  margin: 16px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.08);
  overflow: hidden;
}

.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;
}

.upload-button-container {
  margin-top: 16px;
  padding: 0 8px;
}

/* 添加过渡动画 */
.command-item {
  position: relative;
  overflow: hidden;
}

.command-item::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(25, 137, 250, 0.1);
  border-radius: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.command-item:active::after {
  opacity: 1;
}

/* 为清除报警按钮添加样式 */
:deep(.van-button--danger) {
  margin-left: 8px;
}

.mode-container {
  margin: 12px -16px;
  padding: 12px 16px;
  background-color: #f2f7ff;
  /* 浅蓝色背景 */
  border-left: 4px solid #1989fa;
  /* 左边添加蓝色边框 */
}

.mode-row {
  margin-bottom: 0;
  /* 覆盖原来的 margin */
}

.mode-field {
  font-weight: 500;
  /* 字体加粗 */
  color: #1989fa;
  /* 使用主题蓝色 */
}

.mode-field :deep(.van-field__value) {
  color: #1989fa;
}

.mode-field :deep(.van-field__placeholder) {
  color: #1989fa;
  opacity: 0.7;
}

/* 让其他网络参数稍微淡一点 */
.info-row:not(.mode-row) {
  opacity: 0.85;
}

.car-status {
  font-weight: bold;
}

.status-0 {
  color: #909399;
  /* 灰色 - 停止 */
}

.status-1 {
  color: #67C23A;
  /* 绿色 - 前进 */
}

.status-2 {
  color: #E6A23C;
  /* 橙色 - 后退 */
}

.status-3 {
  color: #409EFF;
  /* 蓝色 - 左转 */
}

.status-4 {
  color: #409EFF;
  /* 蓝色 - 右转 */
}
</style>