<template>
  <div class="page-container">
    <Header :title="currentTitle"></Header>
    <van-pull-refresh v-model="loading" success-text="刷新成功" @refresh="onRefresh" class="fresh">
      <div class="home">
        <van-cell-group inset>
          <p class="title">LoRa模组信息</p>
          <van-divider :style="{ color: 'black' }" />
          <van-field label="固件版本:" v-model="versions" readonly />
          <van-field label="MAC地址:" v-model="mac_addr" readonly />
          <van-field label="无线频率:" v-model="radio_band" readonly />
          <van-field label="设备功率:" v-model="selectedpower" readonly />
          <van-field label="模式:" v-model="mode" readonly />
        </van-cell-group>
      </div>
      <div class="home">
        <van-cell-group inset>
          <p class="title">LoRa网络参数</p>

          <!-- 网络id -->
          <van-field v-model="value" label="网络ID" placeholder="请输入网络ID" @input="validateValue" />

          <!-- 选择信道 -->
          <van-field v-model="channelValue" is-link readonly label="信道" placeholder="选择信道"
            @click="showchannelPicker = true" />
          <van-popup v-model:show="showchannelPicker" round position="bottom">
            <van-picker :columns="channelcolumns" @cancel="showchannelPicker = false" @confirm="onConfirmchannel" />
          </van-popup>

          <!-- 速率 -->
          <van-cell is-link title="速率" @click="showspeed = true">
            {{ selectedspeed }}
          </van-cell>
          <van-action-sheet v-model:show="showspeed" :actions="speedactions" @select="onSelectspeed" />

          <van-button round type="success" size="large" @click="uploadEventSettings">设置</van-button>
        </van-cell-group>
      </div>
      <EventSettings ref="eventSettingsRef">
      </EventSettings>
    </van-pull-refresh>
    <Footer></Footer>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import Header from "../../components/Header.vue";
import Footer from "../../components/Footer.vue";
import EventSettings from "../event/event.vue"
import '@vant/touch-emulator';
import axios from 'axios';
// import { showToast } from 'vant';

export default {
  methods: {
    eventfilldata(data) {
      // 处理数据的逻辑
    }
  },
  components: {
    Header,
    Footer,
    EventSettings
  },

  setup() {
    const jsonId = ref(1); // 初始 JSON ID
    const currentTitle = ref('预警设置');
    const loading = ref(false);
    const show = ref(false);
    const selectedspeed = ref('');
    const selectedpower = ref('');
    const channelValue = ref('');
    const mode = ref('');
    const showchannelPicker = ref(false);
    const showspeed = ref(false);
    const versions = ref('');
    const mac_addr = ref('');
    const radio_band = ref('');
    const value = ref('');
    const eventSettingsRef = ref(null); // 添加这一行
    const maxRetries = 3;
    let errorCount = 0;
    // let client;
    const isLocal = ref(true); // 定义 isLocal 变量并初始化为 false
    // 定义检查环境函数
    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 validateValue = (event) => {
      let inputValue = event.target.value;
      if (inputValue > 255) {
        value.value = '255';
      } else {
        value.value = inputValue;
      }
    };
    const channelcolumns = [
      { 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' },
      { text: '11', value: '11' },
      { text: '12', value: '12' },
      { text: '13', value: '13' },
      { text: '14', value: '14' },
      { text: '15', value: '15' },
      { text: '16', value: '16' },
      { text: '17', value: '17' },
      { text: '18', value: '18' },
      { text: '19', value: '19' },
      { text: '20', value: '20' },
      { text: '21', value: '21' },
      { text: '22', value: '22' },
      { text: '23', value: '23' },
      { text: '24', value: '24' },
      { text: '25', value: '25' },
      { text: '26', value: '26' },
      { text: '27', value: '27' },
      { text: '28', value: '28' },
      { text: '29', value: '29' },
      { text: '30', value: '30' },
      { text: '31', value: '31' },
    ];
    const speedactions = [
      { name: '62.5kbps', value: '0' },
      { name: '37.5kbps', value: '1' },
      { name: '21.8kbps', value: '2' },
      { name: '12.5kbps', value: '3' },
      { name: '7.0kbps', value: '4' },
      { name: '3.9kbps', value: '5' },
      { name: '2.1kbps', value: '6' },
    ];

    const onSelectspeed = (item) => {
      selectedspeed.value = item.name;
      showspeed.value = false;
      showToast(item.name);
    };

    const onConfirmchannel = ({ selectedOptions }) => {
      showchannelPicker.value = false;
      channelValue.value = selectedOptions[0].text;
    };

    const onRefresh = () => {
      loading.value = true;
      const requestData = {
        board_id: 105,
        JSON_id: jsonId.value,
        LoRa_card: {
          get_LoRa_cfg: 1,
          get_cfg: 1,
        }
      };

      let timeoutHandler;
      const timeoutDuration = 5000; // 超时时间为5秒

      if (isLocal.value) {
        console.log('axios发送');
        console.log('Send Data:', requestData);

        axios.post(`/communication`, requestData, {
          headers: {
            "content-type": "application/json"
          },
          timeout: timeoutDuration // 设置axios的超时
        })
          .then(response => {
            clearTimeout(timeoutHandler); // 清除超时处理器
            parseAndFillData(response.data);
            eventSettingsRef.value.eventfilldata(response.data);
            console.log('Received message:', JSON.stringify(response.data));
            jsonId.value++;
            loading.value = false;
          })
          .catch(error => {
            clearTimeout(timeoutHandler); // 清除超时处理器
            if (error.code === 'ECONNABORTED') {
              console.error('Request timeout:', error);
              showToast('刷新超时');
            } else {
              console.error('Upload error:', error);
              showToast('刷新失败');
            }
            jsonId.value++;
            loading.value = false;
          });

        // 手动设置超时处理器，防止axios超时机制失败
        timeoutHandler = setTimeout(() => {
          loading.value = false;
          showToast('请求超时');
        }, timeoutDuration);

      } else {
        // 添加超时机制
        const sendMQTTWithTimeout = new Promise((resolve, reject) => {
          MQTT_send(requestData); // 发送请求
          resolve('MQTT消息已发送');
        });

        const timeout = new Promise((_, reject) =>
          setTimeout(() => reject(new Error('MQTT发送超时')), timeoutDuration)
        );

        Promise.race([sendMQTTWithTimeout, timeout])
          .then(result => {
            console.log(result); // 成功发送MQTT消息
            showToast('刷新请求已发送');
          })
          .catch(error => {
            console.error(error.message); // 超时或发送错误
            showToast('MQTT发送超时');
          })
          .finally(() => {
            loading.value = false; // 无论超时还是成功，最后都关闭loading状态
          });
      }
    };

    const powerMap = {
      0: '22dbm',
      1: '20dbm',
      2: '17dbm',
      3: '14dbm',
      4: '11dbm',
      5: '8dbm',
      6: '5dbm',
      7: '2dbm'
    };
    const modeMap = {
      1: '主机',
      0: '从机',
    }
    const radio_bandMap = {
      0: '62.5kbps',
      1: '37.5kbps',
      2: '21.8kbps',
      3: '12.5kbps',
      4: '7.0kbps',
      5: '3.9kbps',
      6: '2.1kbps',
    };
    const parseAndFillData = (msg) => {
      // const LoRa_cfg = msg?.LoRa_card?.LoRa_cfg || {}; // 如果LoRa_cfg缺失则使用空对象
      // versions.value = LoRa_cfg.versions || ''; // 版本号如果缺失则设置为空字符串
      // mac_addr.value = Array.isArray(LoRa_cfg.mac_addr) ? LoRa_cfg.mac_addr.join(':') : ''; // 防止mac_addr不是数组
      // value.value = LoRa_cfg.mesh_id ? LoRa_cfg.mesh_id.slice(-1)[0].toString() : ''; // 防止mesh_id不存在
      // radio_band.value = radio_bandMap[LoRa_cfg.fre_band] || ''; // 如果频率带宽缺失则设为空
      // // channelValue.value = channelcolumns.find(channel => channel.value === LoRa_cfg.channel.toString())?.text;
      // channelValue.value = LoRa_cfg.channel ? LoRa_cfg.channel.toString() : ''; // 防止channel缺失
      // selectedspeed.value = LoRa_cfg.SF ? speedactions.find(action => action.value === LoRa_cfg.SF.toString())?.name : ''; // 防止SF缺失
      // selectedpower.value = powerMap[LoRa_cfg.power] || ''; // 防止power缺失
      // mode.value = modeMap[LoRa_cfg.mode] || ''; // 防止mode缺失
      const LoRa_cfg = msg.LoRa_card.LoRa_cfg;
      versions.value = LoRa_cfg.versions;
      mac_addr.value = LoRa_cfg.mac_addr.join(':');
      value.value = LoRa_cfg.mesh_id ? LoRa_cfg.mesh_id.slice(-1)[0].toString() : '';
      radio_band.value = radio_bandMap[LoRa_cfg.fre_band] || '';
      // channelValue.value = channelcolumns.find(channel => channel.value === LoRa_cfg.channel.toString())?.text; 
      channelValue.value = LoRa_cfg.channel.toString();
      selectedspeed.value = speedactions.find(action => action.value === LoRa_cfg.SF.toString())?.name;
      selectedpower.value = powerMap[LoRa_cfg.power] || '';
      mode.value = modeMap[LoRa_cfg.mode] || '';
      loading.value = false;
      showToast('配置已更新');
    };


    const uploadEventSettings = () => {
      if (!value.value || !channelValue.value || !selectedspeed.value) {
        showToast('请重新输入所有必填项');
        return;
      }

      const data = {
        JSON_id: jsonId.value,
        board_id: 105,
        LoRa_card: {
          LoRa_cfg: {
            mesh_id: [0, 0].concat(value.value.split(',').map(Number)),
            channel: Number(channelValue.value),
            SF: Number(speedactions.find(action => action.name === selectedspeed.value)?.value),
          }
        }
      };
      if (isLocal.value) {
        console.log('axios发送');
        // 在本地环境使用 Axios 发送请求
        console.log('Send Data:', data);
        axios.post(`/communication`, data, {
          headers: {
            "content-type": "application/json"
          },
        })

          .then(response => {
            console.log('Received message:', response.data);
            showToast('上传成功');
            jsonId.value++;
          })
          .catch(error => {
            // 处理错误
            console.error('Upload error:', error);
            showToast('上传失败');
            jsonId.value++;

          });
      } else {
        MQTT_send(data);
        showToast('设置已上传');
        jsonId.value++;
      }
    }
    const MQTT_send = (send_string) => {
      console.log(" 向父页面发送消息:", JSON.stringify(send_string));
      // 使用 postMessage 发送数据给父页面 
      window.parent.postMessage(
        {
          data: send_string
        },
        '*' // 目标 origin，生产环境应替换为具体的父页面域名 
      );
    };

    const MQTT_recv = (string) => {
      console.log("MQTT 接收的json:" + JSON.stringify(string));
      loading.value = false;

      const msg = JSON.parse(string);
      console.log('Received message:', msg);

      try {
        parseAndFillData(msg);
        eventSettingsRef.value.eventfilldata(msg);

      } catch (error) {
        console.error('Error in parseAndFillData:', error);
        console.error('Error in eventfilldata:', error);
        errorCount++;
        if (errorCount >= maxRetries) {
          showToast("设备异常，请检查系统");
          return;
        }
      }
      errorCount = 0; // Reset error count if successful
      showToast("刷新成功");
    };

    onMounted(async () => {
      await checkEnvironment();
      console.log(isLocal.value);
      // window.MQTT_recv = MQTT_recv;
      window.addEventListener('message', function (event) {
        // console.log("message",JSON.stringify(message))
        // 仅校验消息结构（非必须但建议）
        console.log("接受的原始数据", JSON.stringify(event.data))
        if (event.data) {
          MQTT_recv(JSON.stringify(event.data));  // 保持与原 MQTT_recv 兼容 
        }
      });
      onRefresh();
    });
    onBeforeUnmount(() => {

    });
    return {
      currentTitle,
      jsonId,
      loading,
      onRefresh,
      show,
      onConfirmchannel,
      channelValue,
      channelcolumns,
      showchannelPicker,
      speedactions,
      onSelectspeed,
      showspeed,
      selectedspeed,
      selectedpower,
      versions,
      mac_addr,
      radio_band,
      value,
      uploadEventSettings,
      parseAndFillData,
      checkEnvironment,
      mode,
      validateValue,
      modeMap,
      radio_bandMap,
      eventSettingsRef,
      MQTT_send,
      MQTT_recv
    };
  }
};
</script>

<style scoped>
.page-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  position: relative;
  margin-bottom: 100px;
}




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

.home {
  padding: 20px;
  border-radius: 10px;
  border: 2px solid #0668fc;
  margin: 50px 10px 10px;
  flex: 1;
}

.page-container {
  margin-top: 50px;
}

.fresh {
  margin-top: 20px;
}

::v-deep .van-field__control {
  text-align: right !important;
}
</style>
