<template>
  <div class="flight-control" v-if="airportVal" v-drag>
    <div class="title">
      <div>
        飞行控制：
        <!-- {"0":"空闲中","1":"现场调试","2":"远程调试","3":"固件升级中","4":"作业中","5":"待标定"} -->
        <i v-if="airportVal.mode_code == 0">空闲中 </i>
        <i v-else-if="airportVal.mode_code == 1">现场调试 </i>
        <i v-else-if="airportVal.mode_code == 2">远程调试 </i>
        <i v-else-if="airportVal.mode_code == 3">固件升级中 </i>
        <i v-else-if="airportVal.mode_code == 4">作业中 </i>
        <i v-else-if="airportVal.mode_code == 5">待标定 </i>
      </div>
      <div @click="emits('changeFlightControl')">
        <CloseOutlined />
      </div>
    </div>
    <div class="content">
      <div class="content-button">
        <a-button @click="takeOff">一键起飞</a-button>
        <a-button @click="emits('clickFlyTo')">指点飞行</a-button>
        <!-- <a-button>智能环绕</a-button> -->
        <a-button @click="returnVoyage">一键返航</a-button>
        <a-button @click="obtain" style="background-color: #1b71e8; border: none"
          >获取飞行器控制权</a-button
        >
        <a-button @click="enterDRC" style="background-color: #24d365; border: none"
          >进入飞行控制</a-button
        >
        <a-button @click="exitDRC" style="background-color: #e3150e; border: none"
          >退出飞行控制</a-button
        >
      </div>
      <div class="content-info">
        <div class="info-item">
          <!-- <img src="@/assets/images/flightoperation/flight_control.png" alt="" /> -->
          <div class="info-item-top" title="上升" @click="changeDRC('throttle', 'up')">
            <img src="@/assets/images/flightoperation/top.png" alt="" />
          </div>
          <div class="info-item-right" title="右旋转" @click="changeDRC('yaw', 'up')">
            <img src="@/assets/images/flightoperation/right.png" alt="" />
          </div>
          <div class="info-item-bottom" title="下降" @click="changeDRC('throttle', 'down')">
            <img src="@/assets/images/flightoperation/bottom.png" alt="" />
          </div>
          <div class="info-item-left" title="左旋转" @click="changeDRC('yaw', 'down')">
            <img src="@/assets/images/flightoperation/left.png" alt="" />
          </div>
        </div>
        <div class="info-item">
          <!-- <img src="@/assets/images/flightoperation/flight_control.png" alt="" /> -->
          <div class="info-item-top" title="前进" @click="changeDRC('pitch', 'up')">
            <img src="@/assets/images/flightoperation/top.png" alt="" />
          </div>
          <div class="info-item-right" title="右移" @click="changeDRC('roll', 'up')">
            <img src="@/assets/images/flightoperation/right.png" alt="" />
          </div>
          <div class="info-item-bottom" title="后退" @click="changeDRC('pitch', 'down')">
            <img src="@/assets/images/flightoperation/bottom.png" alt="" />
          </div>
          <div class="info-item-left" title="左移" @click="changeDRC('roll', 'down')">
            <img src="@/assets/images/flightoperation/left.png" alt="" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { onMounted, ref, watch, reactive, onUnmounted } from 'vue';
  import { getClient, createSeizeConnection, destroySeizeConnection } from '@/utils/mqtt';
  import { CloseOutlined } from '@ant-design/icons-vue';
  import { vDrag } from '@/utils/drag';
  import { drcDownTopicReize, eventsTopicSubscribeReize } from '@/utils/debugging/events';
  import {
    servicesTopic,
    services_replyTopic,
    drcDownTopic,
    eventsTopicSubscribe,
  } from '@/utils/debugging/remote';
  import { buildGUID } from '@/utils/uuid';
  import { useMessage } from '@/hooks/web/useMessage';
  import {
    getRedisUser,
    addOrUpdateRedisUser,
    getLockedClients,
  } from '@/api/workmanagement/airportMaintenance';
  import { useUserStore } from '@/store/modules/user';
  import { timestampToFormattedDate } from '@/utils/index';

  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const redisUser = ref({});
  const { createMessage } = useMessage();
  const emits = defineEmits(['changeFlightControl', 'clickTakeOff', 'clickFlyTo']);
  const monitorDRC = ref(false);
  // 是否飞行控制权抢夺
  const flightGrab = ref(false);
  // 是否进入飞行指令控制模式
  const modeEnter = ref(false);
  const airportVal: any = ref({
    mode_code: 0,
    wind_speed: 0,
    environment_temperature: 0,
    temperature: 0,
    rainfall: 0,
    network_state: {
      rate: 0,
    },
    drone_in_dock: 0,
    drone_charge_state: {
      capacity_percent: 0,
    },
  });

  //修改redis用户锁
  const changeRedisUser = (val: boolean) => {
    const querys = redisUser.value;
    querys.isLock = val;
    querys.connectTime = timestampToFormattedDate(new Date().getTime());
    addOrUpdateRedisUser(querys);
  };
  const isLocked = ref(false);
  // 判断有没有redis用户锁
  const lockedClient = () => {
    getLockedClients().then((res) => {
      if (res.length > 0) {
        res.forEach((item, index) => {
          if (item.userId != userInfo.id) {
            isLocked.value = true;
          }
        });
      }
    });
  };
  // 一键起飞
  const takeOff = () => {
    if (isLocked.value) {
      createMessage.success('当前有用户正在操作，请稍后再试');
      return;
    }
    emits('clickTakeOff');
    changeRedisUser(true);
  };

  // 获取
  const obtain = () => {
    // if (!getClient()) {
    //   createConnection();
    // }
    if (isLocked.value) {
      createMessage.success('当前有用户正在操作，请稍后再试');
      return;
    }
    changeRedisUser(true);
    // 飞行控制权抢夺
    servicesTopic({
      bid: buildGUID(),
      method: 'flight_authority_grab',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {},
    });
    // 负载控制权抢夺
    servicesTopic({
      bid: buildGUID(),
      method: 'payload_authority_grab',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        payload_index: '99-0-0',
      },
    });
    services_replyTopic();
  };
  // 一键返航
  const returnVoyage = () => {
    // 老的
    servicesTopic({
      bid: buildGUID(),
      method: 'return_home',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {},
    });
    // 新的servicesTopicReize
  };
  const seq = ref(1);
  const changeDRC = (type, value) => {
    if (!modeEnter.value) {
      createMessage.warning('请先进入指令飞行控制');
      return;
    }
    seq.value = seq.value + 1;
    let data = {
      roll: 1024,
      pitch: 1024,
      throttle: 1024,
      yaw: 1024,
      gimbal_pitch: 1024,
    };
    if (value == 'up') {
      data[type] = 1684;
    } else {
      data[type] = 364;
    }
    const querys = {
      seq: seq.value,
      method: 'stick_control',
      data: data,
      bid: buildGUID(),
      tid: buildGUID(),
      timestamp: new Date().getTime(),
    };
    drcDownTopicReize(querys);
  };
  const drcSeq = ref(1);
  const enterDRC = () => {
    if (!flightGrab.value) {
      createMessage.warning('请先获取飞行控制权');
      return;
    }
    createSeizeConnection();
    // 进入指令飞行控制模式
    const querys = {
      bid: buildGUID(),
      data: {
        hsi_frequency: 10,
        mqtt_broker: {
          address: 'ws://175.27.168.120:6010/mqtt',
          // client_id: 'mqtt_client_1581F8HGX254V00A0BUY',
          client_id: 'mqtt_client_1581F8HGX254V00A0BUYSeize',
          enable_tls: false,
          expire_time: 3600,
          password: '',
          username: 'sdhc',
        },
        osd_frequency: 5,
      },
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      method: 'drc_mode_enter',
    };
    servicesTopic(querys);
    drc_eart_beat();
  };
  let timer;
  const drc_eart_beat = () => {
    monitorDRC.value = true;
    // 每隔五秒发送drc心跳包
    timer = window.setInterval(() => {
      drcSeq.value = drcSeq.value + 1;
      const drcQuerys = {
        bid: buildGUID(),
        tid: buildGUID(),
        timestamp: new Date().getTime(),
        method: 'heart_beat',
        data: {
          timestamp: new Date().getTime(),
        },
        seq: drcSeq.value,
      };
      drcDownTopic(drcQuerys);
    }, 5000);
    // 订阅drc链路状态通知
    eventsTopicSubscribe();
  };
  const exitDRC = () => {
    const querys = {
      bid: buildGUID(),
      data: {},
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      method: 'drc_mode_exit',
    };
    servicesTopic(querys);
  };
  onMounted(() => {
    // 获取mqtt客户端信息
    getRedisUser(userInfo.id).then((res) => {
      if (res) {
        redisUser.value = res;
      }
    });
    lockedClient();
    // // 接收消息
    getClient().on('message', (topic, message) => {
      const rs = JSON.parse(message);
      if (rs.data.mode_code || rs.data.mode_code == 0) {
        airportVal.value = rs.data;
      }
      if (rs.method == 'flight_authority_grab') {
        if (rs.data.result == 0) {
          flightGrab.value = true;
          createMessage.success('飞行控制权抢夺成功');
        } else {
          flightGrab.value = false;
          createMessage.error('飞行控制权抢夺失败，状态码' + rs.data.result);
        }
      }
      if (rs.method == 'drc_mode_enter') {
        if (rs.data.result == 0) {
          modeEnter.value = true;
          createMessage.success('进入指令飞行控制模式成功');
        } else {
          modeEnter.value = false;
          createMessage.error('进入指令飞行控制模式失败，状态码' + rs.data.result);
        }
      }
      if (rs.method == 'drc_mode_exit') {
        if (rs.data.result == 0) {
          modeEnter.value = false;
          createMessage.success('退出指令飞行控制模式成功');
        } else {
          createMessage.error('退出指令飞行控制模式失败，状态码' + rs.data.result);
        }
      }
      // 一键返航
      if (rs.method === 'return_home') {
        if (rs.data.result == 0) {
          createMessage.success('一键返航成功');
          monitorDRC.value = false;
        } else {
          createMessage.error('一键返航失败，状态码' + rs.data.result);
        }
      }
      if (rs.method === 'takeoff_to_point') {
        if (rs.data.result == 0) {
          createMessage.success('一键起飞成功');
        } else {
          createMessage.error('一键起飞失败，状态码' + rs.data.result);
        }
      }
      if (rs.method === 'drc_status_notify' && monitorDRC.value) {
        if (rs.data.result == 0) {
          if (rs.data.drc_state == 0) {
            drc_eart_beat();
          }
        } else {
          createMessage.error('DRC连接失败，状态码' + rs.data.result);
        }
      }
      // 指点飞行
      if (rs.method == 'fly_to_point') {
        if (rs.data.result == 0) {
          createMessage.success('指点飞行成功');
        } else {
          createMessage.error('指点飞行失败，状态码' + rs.data.result);
        }
      }
    });
  });
  onUnmounted(() => {
    window.clearInterval(timer);
    destroySeizeConnection();
    changeRedisUser(false);
    monitorDRC.value = false;
  });
</script>
<style lang="less" scoped>
  .flight-control {
    position: absolute;
    bottom: 100px;
    left: 700px;
    width: 360px;
    height: 350px;
    padding: 10px 20px;
    margin: 10px 0 0 10px;
    background: #0d0e15;
    box-shadow:
      0px 10px 30px 0px rgba(0, 0, 6, 0.15),
      inset 0px 0px 36px 0px rgba(58, 87, 232, 0.73);
    border-radius: 6px;
    backdrop-filter: blur(3px);
    color: #fff;
    .title {
      width: 100%;
      padding: 10px 0;
      box-shadow: 0px 10px 30px 0px rgba(0, 0, 6, 0.15);
      border-bottom: 1px solid #4e5778;
      display: flex;
      align-items: center;
      justify-content: space-between;
      i {
        color: #f2762d;
        font-style: normal;
      }
      div {
        color: #fff;
        cursor: pointer;
      }
    }
    .content-item {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #4e5778;
      padding: 10px 0;
    }
    .content-button {
      margin-top: 10px;
      button {
        background: none;
        margin: 10px 0 0 10px;
        color: #fff;
      }
    }
    .content-info {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .info-item {
        position: relative;
        width: 48%;
        height: 116px;
        margin: 24px 0 20px 20px;
        img {
          width: 36px;
        }
        .info-item-top {
          width: 40px;
          height: 40px;
          position: absolute;
          top: 8px;
          left: 20px;
          cursor: pointer;
          img {
            width: 62px;
          }
        }
        .info-item-right {
          width: 40px;
          height: 40px;
          position: absolute;
          top: 30px;
          right: 33px;
          cursor: pointer;
        }
        .info-item-bottom {
          width: 40px;
          height: 40px;
          position: absolute;
          bottom: 0px;
          left: 21px;
          cursor: pointer;
          img {
            width: 62px;
          }
        }
        .info-item-left {
          width: 40px;
          height: 40px;
          position: absolute;
          top: 30px;
          left: 0px;
          cursor: pointer;
        }
      }
    }
  }
</style>
