<template>
  <div class="device-page p-2">
    <!-- 头部信息栏 -->
    <div class="header-bar">
      <div>设备名称：{{ deviceDetail.deviceName }}，IMEI:{{ deviceDetail.deviceImei }}</div>
      <div>设备型号：{{ deviceDetail.typeName }}</div>
      <div class="device-status">
        设备状态：
        <span :class="{ online: deviceDetail.onlineStatus === 1, offline: deviceDetail?.onlineStatus === 0 }">
          {{ deviceDetail.onlineStatus === 1 ? '在线' : '离线' }}
        </span>
      </div>
      <div>电量：{{ Status.staPowerPercent ? Status.staPowerPercent : deviceDetail.staPowerPercent || 0 }}%</div>
      <div>续航：{{ Status.powerTime }}</div>
    </div>

    <div class="leftContent fleft">
      <div class="row card mainLight padding">
        <div class="title">主光模式</div>
        <div class="lightFlex">
          <div class="lightItem" :class="{ active: item.checked }" v-for="(item, index) in dic.main" @click="sendMode(item, index, 'main')">
            <div class="imgContent">
              <div v-show="!item.checked" class="img" :style="{ backgroundImage: `url(${item.icon})` }"></div>
              <div v-show="item.checked" class="img" :style="{ backgroundImage: `url(${item.iconAc})` }"></div>
              <div class="imgTxt">{{ item.text }}</div>
            </div>

            <el-switch v-model="item.checked" size="large" active-text="开" inactive-text="关" inline-prompt />
          </div>
        </div>
      </div>
      <div class="row fuLight">
        <div class="fleft card light padding">
          <div class="title">辅光模式</div>
          <div class="lightFlex">
            <div class="lightItem" :class="{ active: item.checked }" v-for="(item, index) in dic.fu" @click="sendMode(item, index, 'fu')">
              <div class="imgContent">
                <div v-show="!item.checked" class="img" :style="{ backgroundImage: `url(${item.icon})` }"></div>
                <div v-show="item.checked" class="img" :style="{ backgroundImage: `url(${item.iconAc})` }"></div>

                <div class="imgTxt">{{ item.text }}</div>
              </div>

              <el-switch v-model="item.checked" size="large" active-text="开" inactive-text="关" inline-prompt />
            </div>
          </div>
        </div>
        <div class="fleft card sos padding">
          <div class="title"></div>
          <div class="lightFlex" style="justify-content: space-around">
            <div class="lightItem" :class="{ active: item.checked }" v-for="(item, index) in dic.sos" @click="sendMode(item, index, 'sos')">
              <div class="imgContent">
                <div v-show="!item.checked" class="img" :style="{ backgroundImage: `url(${item.icon})` }"></div>
                <div v-show="item.checked" class="img" :style="{ backgroundImage: `url(${item.iconAc})` }"></div>

                <div class="imgTxt">{{ item.text }}</div>
              </div>

              <el-switch v-model="item.checked" size="large" active-text="开" inactive-text="关" inline-prompt />
            </div>
          </div>
        </div>
        <div class="clear"></div>
      </div>
      <div class="row card usr padding">
        <div class="title">人员信息登记</div>
        <div class="form-grid">
          <div class="form-item">
            <span class="form-label">单位:</span>
            <el-input v-if="deviceDetail" placeholder="请输入单位" v-model="deviceDetail.personnelInfo.unitName" />
          </div>
          <div class="form-item">
            <span class="form-label">职位:</span>
            <el-input v-if="deviceDetail" placeholder="请输入职位" v-model="deviceDetail.personnelInfo.position" />
          </div>
          <div class="form-item">
            <span class="form-label">姓名:</span>
            <el-input v-if="deviceDetail" placeholder="请输入姓名" v-model="deviceDetail.personnelInfo.name" />
          </div>
          <div class="form-item">
            <span class="form-label">ID:</span>
            <el-input v-if="deviceDetail" placeholder="请输入ID" v-model="deviceDetail.personnelInfo.code" />
          </div>
        </div>
        <el-button type="primary" class="register-btn fright" @click="sendUsr">登记</el-button>
      </div>
    </div>
    <div class="rightContent fleft">
      <div class="liangdu">
        <div class="leftsett">
          <div class="rmkLiangdu">灯光亮度</div>
          <input type="number" class="txtLiangdu" max="100" min="1" v-model="formData.ins_brightness" />
          <div>%</div>
        </div>

        <el-button type="primary" class="register-btn fright" @click="setBrightness">保存</el-button>
      </div>
      <div class="location padding">
        <div class="title">位置信息</div>
        <div class="mylocation">
          <div class="icoRemark"><img src="@/assets/images/lonlat.png" />经纬度</div>
          <div class="lonlat">
            <div>{{ deviceDetail.longitude }}</div>
            <div>{{ deviceDetail.latitude }}</div>
          </div>
          <div class="icoRemark"><img src="@/assets/images/location.png" />地址</div>
          <div class="addressLink">
            <div class="addrss">{{ currStatu.address ? currStatu.address : deviceDetail.address }}</div>
            <div class="link">查看</div>
          </div>
        </div>
        <div class="title">高度信息</div>
        <div class="height mylocation">
          <div class="icoRemark"><img src="@/assets/images/haiba.png" />海拔高度</div>
          <div class="haiba">{{currStatu.sta_Height}}</div>
          <div class="icoRemark"><img src="@/assets/images/haibaRelative.png" />相对高度</div>
          <div class="haiba">{{currStatu.sta_reHeight}}</div>
        </div>
      </div>
      <div class="msg padding" >
        <div class="title">发送信息</div>
        <div class="form-grid">
          <textarea class="textarea" maxlength="16" v-model="formData.sendMsg"></textarea>
        </div>
        <el-button type="primary" class="register-btn fright" @click="sendMsg" :loading="Status.msgLoading">发送</el-button>
      </div>
    </div>
    <div class="clear"></div>
    <!-- 提示框 -->
    <el-dialog :width="300" :draggable="true" v-model="Status.confirm.Visible" :title="Status.confirm.title" width="500" center>
      <span>
        {{ Status.confirm.text }}
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="Status.confirm.OkCallback">{{ Status.confirm.OkTxt || '确定' }} </el-button>
          <el-button v-show="Status.confirm.showCancel" @click="Status.confirm.cancelCallback">{{ Status.confirm.cancelTxt || '取消' }}</el-button>
        </div>
      </template>
    </el-dialog>

    <TextToHex ref="textToHex" :txts="formData.textLines" :fontSize="16" />
  </div>
</template>
<script setup name="DeviceControl" lang="ts">
const route = useRoute();
import TextToHex from './TextToHex.vue';
import { useMqtt } from '@/utils/mqtt';
import api from '@/api/controlCenter/controlPanel/670';
import { object } from 'vue-types';
import request from '@/utils/request';
import { status } from 'nprogress';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { connected, connect, subscribe, onConnect, onError, onMessage, disconnect, publish } = useMqtt();
const mapApiKey = import.meta.env.VITE_AMAP_WebApi_KEY;
const textToHex = ref(null);

const deviceDetail = ref<any>({
  'deviceId': null,
  'deviceName': null,
  'deviceImei': null,
  'deviceMac': null,
  'communicationMode': null,
  'devicePic': null,
  'typeName': null,
  'bluetoothName': null,
  'deviceStatus': null,
  'personnelInfo': {
    'id': null,
    'deviceId': null,
    'name': null,
    'position': null,
    'unitName': null,
    'code': null
  },
  'onlineStatus': null,
  'longitude': null,
  'latitude': null,
  'address': null,
  'staDetectGrade': null,
  'staLightGrade': null,
  'staSOSGrade': null,
  'staPowerTime': null,
  'staPowerPercent': null,
  'staDetectResult': null,
  'sendMsg': null,
  'sta_ShakeBit': null
});

const Status = reactive<any>({
  powerTime: null,
  confirm: {
    //弹出框的配置
    Visible: false,
    title: '',
    text: '',
    cancelCallback: null,
    OkCallback: null,
    showCancel: true,
    OkTxt: '',
    cancelTxt: '',
    msgLoading:false
  }
});

const getList = () => {
  api
    .deviceRealTimeStatus(route.params.deviceId)
    .then((res) => {
      if (res && res.code == 200) {
        let keys = Object.keys(res.data);
        keys.forEach((key) => {
          deviceDetail.value[key] = res.data[key];
        });

        if (!deviceDetail.value.personnelInfo) {
          deviceDetail.value.personnelInfo = {
            'id': null,
            'deviceId': null,
            'name': null,
            'position': null,
            'unitName': null,
            'code': null
          };
        }
      }
    })
    .catch((ex) => {
      console.error('出现异常', ex);
    });
};

var dic = reactive<any>({
  mainClose: 6,
  fuClose: 5,

  main: [
    {
      text: '强光',
      icon: 'strong-light.png',
      iconAc: 'strong-light_HL.png',
      value: 1,
      key: 'ins_LightGrade',
      checked: false
    },
    // {
    //   text: '超强光',
    //   icon: 'superStrong.png',
    //   iconAc: 'superStrong_HL.png',
    //   value: 7,
    //   key: 'ins_LightGrade',
    //   checked: false
    // },
    {
      text: '工作光',
      icon: 'work.png',
      iconAc: 'work_HL.png',
      value: 2,
      key: 'ins_LightGrade',
      checked: false
    },
    {
      text: '节能光',
      icon: 'jieN.png',
      iconAc: 'jieN_HL.png',
      value: 3,
      key: 'ins_LightGrade',
      checked: false
    },
    {
      text: '爆闪',
      icon: 'strobe-light.png',
      iconAc: 'strobe-light_HL.png',
      value: 4,
      key: 'ins_LightGrade',
      checked: false
    },
    {
      text: 'SOS',
      icon: 'sos.png',
      iconAc: 'sos_HL.png',
      value: 5,
      key: 'ins_LightGrade',
      checked: false
    }
    // ,
    // {
    //   text: '关闭',
    //   icon: 'close.png',
    //   iconAc: 'close_HL.png',
    //   value: '6',
    //   key: 'ins_LightGrade',
    //   checked: false
    // }
  ],
  fu: [
    {
      text: '泛光',
      icon: 'weak-light.png',
      iconAc: 'weak-light_HL.png',
      value: 2,
      key: 'ins_Side_Light',
      checked: false
    },
    {
      text: '泛光爆闪',
      icon: 'weak-light.png',
      iconAc: 'weak-light_HL.png',
      value: 3,
      key: 'ins_Side_Light',
      checked: false
    },
    {
      text: '警示灯',
      icon: 'hb.png',
      iconAc: 'hbAc.png',
      value: 1,
      key: 'ins_Side_Light',
      checked: false
    },
    {
      text: '警示灯/泛光',
      icon: 'hb.png',
      iconAc: 'hbAc.png',
      value: 4,
      key: 'ins_Side_Light',
      checked: false
    } //,
    // {
    //   text: '关闭',
    //     icon: 'close.png',
    //   iconAc: 'close_HL.png',
    //   value: '5',
    //   key: 'ins_Side_Light'
    // }
  ],
  sos: [
    {
      text: '激光模式',
      icon: 'laser-light.png',
      iconAc: 'laser-light_HL.png',
      value: 1,
      closeVal: 0,
      key: 'ins_laser',
      checked: false
    },
    {
      text: '声光报警',
      icon: 'hb.png',
      iconAc: 'hbAc.png',
      value: 1,
      closeVal: 0,
      key: 'ins_ShakeBit',
      checked: false
    }
  ]
});

var formData = reactive<any>({
  ins_brightness: null,
  textLines: ['湖北星汉文化', '有限', '公司', '胡红军'],
  sendMsg: '湖北星汉文化有限公司'
});

var currStatu = reactive<any>({
  'sta_LightGrade': null, // 主灯档位：null=未设置，1=强光，2=工作光，3=节能光，4=爆闪，5=SOS，6=关闭
  'sta_Side_Light': null, // 副灯档位：1=两侧红蓝警示，2=泛光长亮，3=泛光爆闪，4=红蓝警示与泛光同步开启，5=关闭所有
  'sta_PowerTime': null, // 剩余工作时间，单位分钟，范围0-5999
  'sta_PowerPercent': null, // 剩余电量百分比，范围0-100
  'sta_ShakeBit': null, // 报警状态：0=未报警，1=正在报警
  'sta_4gSinal': null, // 4G信号强度，范围0-32，数值越大信号越强
  'sta_imei': null, // IMEI卡号
  'sta_longitude': null, // 经度
  'sta_latitude': null, // 纬度
  'sta_system': null, // 设备现状：0=关机，1=仅充电，2=开机未充电，3=开机且充电
  'sta_laser': null, // 激光：0=关闭，1=开启
  'sta_address': null, // 蓝牙MAC地址，String类型，冒号可有可无
  'sta_brightness': null, // 亮度，范围1-100
  'sta_SOSGrade': null, // SOS档位：0=关闭，1=单色爆闪模式，2=红蓝模式
  'sta_Heat': null, // 温度，单位摄氏度
  'sta_Height': null, // 海拔，单位米
  'sta_reHeight':null,//相对海拔
  address: '',
  sta_BreakNews:null
});

function getImageUrl(fileName) {
  let img = new URL(`/src/assets/images/${fileName}`, import.meta.url);

  return img.href;
}

function dicImgHandle() {
  let keys = Object.keys(dic);
  keys.forEach((key) => {
    if (dic[key] instanceof Array) {
      dic[key].forEach((el) => {
        el.icon = getImageUrl(el.icon);
        el.iconAc = getImageUrl(el.iconAc);
      });
    }
  });
}
function sendMode(item, index, type) {
  let flag = !dic[type][index].checked;
  let json = {};
  if (type == 'sos') {
    dic.sos[index].checked = flag;
    if (flag) {
      json[item.key] = 1;
    } else {
      json[item.key] = 0;
    }
  } else {
    dic[type].forEach((el, i) => {
      if (i == index) {
        el.checked = flag;
      } else {
        el.checked = false;
      }
    });

    if (flag) {
      json[item.key] = item.value;
    } else {
      json[item.key] = dic[type + 'Close'];
    }
  }

  sendCmd(json);
}

function setBrightness() {
  let json = { ins_brightness: formData.ins_brightness };
  sendCmd(json);
}

function sendCmd(json, isBuffer) {
  if (isBuffer) {
    let buffer = new ArrayBuffer(json.length);

    let view = new DataView(buffer);
    for (let i = 0; i < json.length; i++) {
      const el = json[i];
      view.setUint8(i, el);
    }

    json = buffer;
  } else if (json instanceof Object) {
    json = JSON.stringify(json);
  }

  return publish('B/' + deviceDetail.value.deviceImei, json, { qos: 0, retained: false });
}

function handleDeviceMessage(payload) {
  console.log('payload=', payload);

  if (!(payload instanceof object)) {
    payload = JSON.parse(payload);
  }

  let keys = Object.keys(payload);

  for (let i = 0; i < keys.length; i++) {
    let key = keys[i];
    currStatu[key] = payload[key];
  }

  //修改主灯模式
  let index = null;
  dic.main.find((v, i) => {
    if (v.value == currStatu.sta_LightGrade) {
      index = i;
      return true;
    }
  });
  for (let i = 0; i < dic.main.length; i++) {
    if (i == index) {
      dic.main[i].checked = true;
      continue;
    }
    dic.main[i].checked = false;
  }

  dic.fu.find((v, i) => {
    if (v.value == currStatu.sta_Side_Light) {
      index = i;
      return true;
    }
  });
  for (let i = 0; i < dic.fu.length; i++) {
    if (i == index) {
      dic.fu[i].checked = true;
      continue;
    }
    dic.fu[i].checked = false;
  }

  dic.sos[0] = currStatu.sta_laser;
  dic.sos[1] = currStatu.sta_ShakeBit;
}

watch(()=>currStatu.sta_BreakNews,(newVal,oldVal)=>{
  if(!newVal){
    return;
  }

  if(newVal=='I get it'){
    confirm("用户已确认收到消息");
  }

  currStatu.sta_BreakNews=null;
});

//坐标变化了
watch(
  () => currStatu.sta_longitude,
  (newVal, oldVal) => {
    if(!newVal){
      return;
    }
    //GPS坐标转高德
    let lonLatConvert = () => {
      return new Promise((resolve,reject)=>{
         let url ='https://restapi.amap.com/v3/assistant/coordinate/convert?locations=' +
        currStatu.sta_longitude +
        ',' +
        currStatu.sta_latitude +
        '&coordsys=gps&output=json&key='+mapApiKey;

      request({
        url: url,
        method: 'get'
      }).then((res) => {
        if (res.statusCode == 200) {
          if (res.data.status == '1' && res.data.infocode == '10000') {
            console.log('坐标转换接口成功', res);
            let lonLat = res.data.locations.split(',');
            deviceDetail.value.longitude = lonLat[0];
            deviceDetail.value.latitude = lonLat[1];
            resolve({lon:lonLat[0],lat:lonLat[1],flag:true});
            return;
          }
        } else {
          deviceDetail.value.longitude = currStatu.sta_longitude;
          deviceDetail.value.latitude = currStatu.sta_latitude;
           resolve({lon:currStatu.sta_longitude,lat:currStatu.sta_latitude,flag:false});
          return;
        }

        reject(false);
      }).catch(ex=>{

      });
      });
     
    };

    //坐标点逆地理，解析出地址
    let regeo=(param)=>{
        let url="https://restapi.amap.com/v3/geocode/regeo?key="+mapApiKey+"&location="+param.lon+","+param.lat;
         request({
        url: url,
        method: 'get'
      }).then((res) => {
          if(!res){
              return;
          }
          if(res.info=="OK" && res.infocode=="10000" && res.status=="1"){
            currStatu.address= res.regeocode.formatted_address;
          }

      }).catch(ex=>{

      });
    }


    lonLatConvert().then(res=>{
      regeo(res);
    }).catch(ex=>{

    });
  }
);
function sendMsg() {
  
  formData.sendMsg.padStart(16, ' ');

  formData.textLines = [formData.sendMsg.slice(0, 8), formData.sendMsg.slice(8, 16)];
  //握手
  let holdHand = (hexs, time) => {
    return new Promise((resolve, reject) => {
      sendCmd(hexs)
        .then((res) => {
          setTimeout(() => {
            resolve(true);
          }, time);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  //画图
  let drawText = () => {
    return new Promise((resolve, reject) => {
      textToHex.value
        .drawAndGetPixels()
        .then((allPixels) => {
          if (!allPixels) {
            reject('文本初始化失败');
            return;
          }
          console.log('画图成功');
          resolve(allPixels);
        })
        .catch((compEx) => {
          reject(compEx);
           Status.msgLoading=false;
        });
    });
  };
  //发送3个分包的数据
  let task = (allPixels) => {
    try {
      let combinedData = [];
      for (let i = 0; i < 2; i++) {
        let linePixels = (allPixels[i] || []).flat(Infinity).map((item) => item.replace('0x', ''));

        for (var j = linePixels.length; j < 256; j++) {
          linePixels.push('00');
        }

        combinedData.push(['0' + (i + 1), '01'].concat(linePixels.slice(0, 128)));
        combinedData.push(['0' + (i + 1), '02'].concat(linePixels.slice(128, 256)));
      }

      let curr = 1;
      let len = combinedData.length;

      console.log('包数量', len);
      //分包发送
      let sendPacket = () => {
        if (combinedData.length === curr - 1) {
          holdHand('transmit complete', 200).then((res) => {
            debugger;
          });
   Status.msgLoading=false;
          return;
        }

        let array = combinedData[curr - 1];

        let json = {
          ins_msg: array.join('')
        };

        sendCmd(json)
          .then((res) => {
            curr++;
            console.log('发送成功', curr);
            setTimeout(sendPacket, 500);
          })
          .catch((err) => {
            if (err.code == '10007') {
              setTimeout(sendPacket, 500);
            } else {
              debugger;
              console.error('err:', err);
            }
               Status.msgLoading=false;
          });
      };

      setTimeout(sendPacket, 0);
      // 5. 发送成功处理
    } catch (ex) {
      console.error('出现错误', ex);
    }
  };
  Status.msgLoading=true;
  setTimeout(() => {
    Promise.allSettled([holdHand('word transmit start', 2200), drawText()]).then((results) => {
      console.log('PromiseAll=', results);
      if (results[0].status == 'rejected') {
        console.error('出现错误', results[0].reason);
        return;
      }
      if (results[1].status == 'rejected') {
        console.log('任务1失败了', results[1].reason);
        return;
      }
      console.log('开始发送数据包');
      task(results[1].value);
    });
  }, 0);
}
function sendUsr() {
  formData.textLines = [
    deviceDetail.value.personnelInfo.unitName,
    deviceDetail.value.personnelInfo.position,
    deviceDetail.value.personnelInfo.name,
    deviceDetail.value.personnelInfo.code
  ];
  console.log('data=', formData.textLines);

  let sendServer = () => {
    let data = {
      code: deviceDetail.value.personnelInfo.code,
      name: deviceDetail.value.personnelInfo.name,
      position: deviceDetail.value.personnelInfo.position,
      unitName: deviceDetail.value.personnelInfo.unitName,
      deviceId: route.params.deviceId,
      deviceImei: deviceDetail.value.deviceImei
    };
    return api.SendUser(data);
  };
  //握手
  let holdHand = (hexs, time) => {
    return new Promise((resolve, reject) => {
      sendCmd(hexs)
        .then((res) => {
          setTimeout(() => {
            resolve(true);
          }, time);
        })
        .catch((err) => {
          reject(err);
        });
    });
  };
  //画图
  let drawText = () => {
    return new Promise((resolve, reject) => {
      textToHex.value
        .drawAndGetPixels()
        .then((allPixels) => {
          if (!allPixels) {
            reject('文本初始化失败');
            return;
          }
          console.log('画图成功');
          resolve(allPixels);
        })
        .catch((compEx) => {
          reject(compEx);
        });
    });
  };

  let toByteValue = (value) => {
    if (typeof value === 'number') {
      return value;
    }
    if (typeof value === 'string') {
      if (value.startsWith('0x') || value.startsWith('0X')) {
        return parseInt(value, 16);
      }
      return parseInt(`0x${value}`, 16);
    }
    return 0;
  };
  //发送3个分包的数据
  let task = (allPixels) => {
    try {
      let combinedData = [];
      for (let i = 0; i < 4; i++) {
        let linePixels = (allPixels[i] || []).flat(Infinity).map((item) => (typeof item === 'string' ? toByteValue(item) : item));

        for (var j = linePixels.length; j < 256; j++) {
          linePixels.push(0x00);
        }
        linePixels = [0xfa, 0x06, 0x03, i + 1].concat(linePixels);

        linePixels.push(0xff);

        combinedData.push(linePixels);
      }

      let curr = 1;
      let len = combinedData.length;

      //分包发送
      let sendPacket = () => {
        if (combinedData.length === curr - 1) {
          holdHand('transmit complete', 200).then((res) => {});
          sendServer();
          return;
        }

        let array = combinedData[curr - 1];

        console.log('array=', array);
        sendCmd(array, true)
          .then((res) => {
            curr++;
            console.log('发送成功', curr);

            setTimeout(sendPacket, 250);
          })
          .catch((err) => {
            console.error('发送失败', err);
            if (err.code == '10007') {
              setTimeout(sendPacket, 250);
            } else {
              console.log('err:', err);
            }
          });
      };

      setTimeout(sendPacket, 0);
      // 5. 发送成功处理
    } catch (ex) {
      console.error('发送失败', ex);
    }
  };

  setTimeout(() => {
    Promise.allSettled([holdHand('word transmit start', 2200), drawText()]).then((results) => {
      if (results[0].status == 'rejected') {
        setTimeout(() => {}, 500);
        return;
      }
      if (results[1].status == 'rejected') {
        return;
      }

      task(results[1].value);
    });
  }, 0);
}

onUnmounted(() => {
  disconnect();
});
onMounted(() => {
  getList();
  dicImgHandle();
  onConnect(async () => {
    const deviceImei = deviceDetail.value.deviceImei;
    if (!deviceImei) {
      return;
    }
    try {
      await subscribe(`A/${deviceImei}`, { qos: 1 });
      console.log('订阅成功');
    } catch (err) {
      console.error('订阅失败（onConnect内）:', err);
    }
  });
  // 2. 注册消息接收回调（核心：处理设备发送的消息）
  onMessage((msg) => {
    console.log('收到新消息:', {
      主题: msg.topic,
      内容: msg.payload,
      时间: msg.time,
      QoS: msg.qos
    });
    // 在这里处理消息（根据实际业务逻辑）
    handleDeviceMessage(msg.payload);
  });
  onError((err) => {
    console.error('MQTT连接失败原因:', err.message); // 关键：打印连接失败的具体原因
  });
  connect();
});

window.confirm = function (msg, OK, cancel, title) {
  let Cfg = {
    Visible: true,
    title: title ? title : '提示',
    text: msg ? msg : '此操作不可逆，您确定这样做吗？',
    OkCallback: () => {
      Status.confirm.Visible = false;
      if (OK) {
        OK();
      }
    },
    showCancel: true,
    cancelCallback: () => {
      Status.confirm.Visible = false;
      if (cancel) {
        cancel();
      }
    },
    OkTxt: '',
    cancelTxt: ''
  };

  Status.confirm = Cfg;
};

window.ShowConfirm = function (option: any) {
  let Cfg = {
    Visible: true,
    title: option.title ? option.title : '提示',
    text: option.text ? option.text : '此操作不可逆，您确定这样做吗？',
    OkCallback: () => {
      Status.confirm.Visible = false;
      if (option.OkCallback) {
        option.OkCallback();
      }
    },
    showCancel: true,
    cancelCallback: () => {
      Status.confirm.Visible = false;
      if (option.cancelCallback) {
        option.cancelCallback();
      }
    },
    OkTxt: '',
    cancelTxt: ''
  };

  Status.confirm = Cfg;
};

window.hideConfirm = function () {
  let Cfg = {
    Visible: false,
    title: '提示',
    text: '',
    cancelCallback: null,
    OkCallback: null,
    showCancel: false,
    OkTxt: '',
    cancelTxt: ''
  };

  Status.confirm = Cfg;
};
</script>
<style lang="scss" scoped>
.p-2 {
  background: #f7f8fc;
  min-height: calc(100vh - 84px);
  height: calc(100vh - 84px);
  box-sizing: border-box;
  padding: 15px;
}
.device-page {
  .header-bar {
    border-radius: 8px;
    background: linear-gradient(135deg, #3400e7, #009bff);
    color: white;
    padding: 20px;
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;

    .device-status {
      .online {
        color: #00ff00;
      }

      .offline {
        color: rgb(224, 52, 52);
      }
    }
  }

  .content-wrapper {
    .content-row {
      margin-bottom: 10px;
    }

    .content-card {
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 34, 96, 0.1);
      background: white;
      padding: 0px 20px 50px;
      border: 1px solid #ebeef5;
      height: 289px;
      position: relative;
    }

    .content-card_gps {
      border-radius: 8px;
      box-shadow: 0 2px 12px rgba(0, 34, 96, 0.1);
      background: white;
      padding: 0px 20px 50px;
      border: 1px solid #ebeef5;
      height: 100%;
    }

    .section-title {
      font-size: 16px;
      font-weight: 600;
      margin-bottom: 20px;
      color: #303133;
    }

    .light-mode {
      display: flex;

      justify-content: space-between;
    }

    .lacatin_gps {
      height: 70px;
      border-radius: 4px;
      background: rgba(247, 248, 252, 1);
      display: inline-block;
      width: 400px;
      padding: 10px;
    }

    .brightness-alarm {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 10px;

      .brightness-control {
        display: flex;
        align-items: center;
        gap: 10px;
        border-radius: 39px;
        box-shadow: 0px 0px 6px 0px rgba(0, 34, 96, 0.1);
        background: rgba(255, 255, 255, 1);
        width: 70%;
        height: 54px;
        padding: 10px 20px;

        .brightness-label {
          font-size: 14px;
          color: #606266;
          min-width: 70px;
        }

        .brightness-value {
          font-size: 14px;
          color: #409eff;
          font-weight: 500;
        }

        .save-btn {
          padding: 6px 20px;
          border-radius: 29px;
          background: rgba(2, 124, 251, 1);
          border: none;
        }

        .inputTFT {
          width: 130px;
          height: 40px;
        }
      }

      .alarm-btn {
        background-color: rgba(224, 52, 52, 1);
        border-color: rgba(224, 52, 52, 1);
        padding: 8px 20px;
        border-radius: 27px;
      }
    }

    .location-info {
      .location-item {
        display: flex;
        align-items: center;
        margin-bottom: 15px;
        font-size: 14px;
        color: #606266;

        .location-icon {
          margin-right: 8px;
          font-weight: bold;
          color: #409eff;
        }

        .view-btn {
          margin: 0 8px;
          padding: 0;
          font-size: 13px;
        }
      }
    }

    .form-grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 15px;
      margin-bottom: 15px;
      text-align: right;

      .form-item {
        display: flex;
        align-items: center;

        .form-label {
          min-width: 35px;
          font-size: 14px;
          color: #606266;
          margin-right: 10px;
        }

        .el-input {
          flex: 1;
        }
      }

      .register-btn {
        grid-column: 1 / 3;
        justify-self: start;
        padding: 6px 20px;
        position: absolute;
        right: 19px;
        bottom: 30px;
        border-radius: 29px;
        background: rgba(2, 124, 251, 1);
        border: none;
      }
    }

    .message-content {
      // display: flex;
      // flex-direction: column;
      // gap: 10px;

      .el-textarea {
        border: 1px solid rgba(29, 111, 255, 1);
        border-radius: 4px;
        background: rgba(247, 248, 252, 1);
        border-radius: 6px;
        padding: 10px;
      }

      .el-textarea__inner {
        background: rgba(247, 248, 252, 1);
      }

      .send-btn {
        align-self: flex-end;
        padding: 10px 20px;
        border-radius: 29px;
        background: rgba(2, 124, 251, 1);
        border: none;
        margin: 20px 0px 30px 0;
      }
    }

    .upload-area {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100px;
      border: 1px dashed #dcdfe6;
      border-radius: 6px;
      cursor: pointer;
    }

    .video-input {
      display: flex;
      gap: 10px;
      align-items: center;

      .el-input {
        flex: 1;
      }

      .save-video-btn {
        padding: 6px 12px;
      }
    }
  }

  // 响应式调整
  @media (max-width: 768px) {
    .header-bar {
      flex-direction: column;
      align-items: flex-start;
      gap: 16px;
    }

    .form-grid {
      grid-template-columns: 1fr;
    }

    .form-grid .register-btn {
      grid-column: 1;
    }

    .light-mode .mode-group {
      gap: 10px;
    }

    .light-mode .mode-item {
      width: 60px;
    }

    .light-mode .mode-icon {
      width: 30px;
      height: 30px;
    }
  }
}

.displayNone {
  display: none !important;
}

.fleft {
  float: left !important;
}
.fright {
  float: right !important;
}

.clear {
  clear: both !important;
}

.leftContent {
  width: calc(70% - 15px);
  margin-right: 15px;
  height: calc(100% - 80px);
}

.leftContent .row {
  width: 100%;
  height: calc(calc(100% - 30px) / 3);
  margin-bottom: 15px;
}
.leftContent .row:last-child {
  margin-bottom: 0px !important;
}
.leftContent .fuLight .light {
  width: calc(65% - 15px);
  margin-right: 15px;
}
.leftContent .fuLight .sos {
  width: 35%;
}
.card {
  height: 100%;
  border-radius: 4px;
  box-shadow: 0px 0px 6px 0px #0022604a;
  background: #ffffff;
}

.rightContent {
  width: 30%;
  height: calc(100% - 80px);
  display: flex;
  flex-direction: column;
}

.rightContent .liangdu {
  width: 100%;
  height: 55px;
  margin-bottom: 15px;
  flex-shrink: 0; /* 防止被压缩 */

  border-radius: 39px;
  box-shadow: 0px 0px 6px 0px #0022604a;
  background: #ffffff;

  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: space-around;
  align-items: center;
}

.rightContent .leftsett {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: center;
  width: calc(100% - 80px);
  box-sizing: border-box;
  padding-left: 15px;
}

.rightContent .location {
  flex: 1; /* 自动填充剩余空间 */
  width: 100%;
  border-radius: 4px;
  box-shadow: 0px 0px 6px 0px #0022604a;
  background: #ffffff;
}

.rightContent .msg {
  height: calc(calc(100% - 30px) / 3);
  flex-shrink: 0; /* 防止被压缩 */
  border-radius: 4px;
  box-shadow: 0px 0px 6px 0px #0022604a;
  background: rgba(255, 255, 255, 1);
  margin-top: 15px;
}

.title {
  color: #38404f;

  font-family: 'Microsoft YaHei';
  font-style: Bold;
  font-size: 14px;
  font-weight: 700;

  letter-spacing: 0px;
  text-align: left;
  width: 100%;
  height: 30px;
  line-height: 30px;
}

.padding {
  padding: 12px;
  box-sizing: border-box;
}

.usr .form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
  width: 100%;
  height: calc(100% - 90px);
  margin-bottom: 15px;
  text-align: right;
  position: relative;

  .form-item {
    display: flex;
    align-items: center;

    .form-label {
      min-width: 35px;
      font-size: 14px;
      color: #606266;
      margin-right: 10px;
    }

    .el-input {
      flex: 1;
    }
  }
}
.msg .form-grid {
  width: 100%;
  height: calc(100% - 90px);
  margin-bottom: 15px;
  .textarea {
    width: 100%;
    height: 100%;
    resize: none;
    padding: 5px;
    box-sizing: border-box;
    border: 1px solid #bdc6d7;
    border-radius: 4px;
    background: #f7f8fc;
  }
  .textarea:focus,
  .textarea:focus-visible {
    border: 1px solid #1d6fff !important;
    outline: none !important;
  }
}

.register-btn {
  width: 70px;
  padding: 0px 20px;

  border-radius: 29px;
  background: #027cfb;
  border: none;
}
.lightFlex {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  height: calc(100% - 50px);
}

.lightItem {
  width: 100px;
  box-sizing: border-box;

  display: flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  position: relative;
  cursor: pointer;
}

.lightItem .imgContent {
  width: 100%;
  height: 130px;
  height: calc(100% - 30px);
  border: 1px solid #027cfb33;
  border-radius: 4px;
  position: relative;
}

.lightItem .imgContent img,
.lightItem .imgContent .img {
  width: 100px;
  height: 100px;
  object-fit: none;
  object-position: center;
  background-repeat: no-repeat;
  background-position-x: center;
  background-position-y: 15px;
  background-size: inherit;
}

.lightItem .imgContent .imgTxt {
  height: 30px;
  line-height: 25px;
  color: #38404f;
  text-align: center;
  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;
  letter-spacing: 0px;
  position: absolute;
  bottom: 0px;
  left: 0px;
  z-index: 1;
  width: 100%;
}
// 贴一层透明膜,让switch点不上
.lightItem::before {
  content: '';
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0px;
  left: 0px;
  z-index: 1;
  background-color: #00000000;
}

.lightItem.active .imgContent {
  border: 1px solid #027cfb;
  background: #027cfb0f;
}
.rightContent .liangdu .rmkLiangdu {
  color: #38404f;

  font-family: 'Microsoft YaHei';
  font-style: Bold;
  font-size: 14px;
  font-weight: 700;

  letter-spacing: 0px;
  text-align: left;
  height: 30px;
  line-height: 30px;
}
.rightContent .liangdu .txtLiangdu {
  box-sizing: border-box;
  border: 1px solid #d2d2d3;
  border-radius: 8px;
  height: 38px;
  line-height: 38px;
  text-align: left;
  text-indent: 5px;
  color: #38404f;

  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;
  margin-left: 5px;
  letter-spacing: 0px;
  margin-right: 5px;
  width: 70px;
}

.TextToHex {
  position: fixed;
  z-index: 0;
  top: -999999rpx;
  left: -999999rpx;
  visibility: hidden;
}
.mylocation {
  width: 100%;
  height: calc(calc(100% - 60px) / 2);
}
.mylocation .icoRemark img {
  width: auto;
  height: 15px;
  margin-right: 5px;
}
.mylocation .icoRemark {
  height: 30px;
  width: 100%;

  color: #38404f99;

  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;

  letter-spacing: 0px;
  text-align: left;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  align-items: center;
  justify-content: flex-start;
}
.mylocation .lonlat {
  color: #38404f;

  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;
  line-height: 30px;
  letter-spacing: 0px;
  text-align: left;
  width: 100%;
  height: 30px;
}

.mylocation .addressLink {
  width: 100%;
  height: calc(100% - 100px);
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: flex-start;
  align-items: center;
}
.mylocation .addrss {
  width: calc(100% - 60px);
  height: 100%;
  border-radius: 4px;
  background: rgba(247, 248, 252, 1);
  color: #38404f;

  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;
  line-height: 18px;
  letter-spacing: 0px;
  text-align: left;
}
.mylocation .link {
  width: 60px;
  height: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-content: center;
  justify-content: center;
  align-items: center;

  color: #027cfb;

  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;

  letter-spacing: 0px;
}

.mylocation .haiba {
  width: 100%;
  color: #38404f;

  font-family: 'Microsoft YaHei';
  font-style: Regular;
  font-size: 14px;
  font-weight: 400;
  height: 30px;
  line-height: 30px;
  letter-spacing: 0px;
  text-align: left;
}
</style>
