<template>
  <div class="remote-debugging" v-if="airportVal" v-drag>
    <div class="title">
      <span> 云台相机控制 </span>
      <div @click="emits('changeLoadControl')">
        <CloseOutlined />
      </div>
    </div>
    <div class="content">
      <!-- <div class="content-item">
        <span>相机控制权</span>
        <a-button @click="obtain">获取</a-button>
      </div> -->
      <!-- <div class="content-item">
        <span>切换相机模式</span>
        <a-button>抢夺负载控制</a-button>
      </div> -->
      <!-- <div class="content-item">
        <span>拍照</span>
        <a-button @click="singleShot">单拍</a-button>
      </div> -->
      <div class="content-button">
        <a-button @click="obtain">获取相机控制权</a-button>
        <a-button @click="singleShot">单拍</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="direction-controller">
        <img src="@/assets/images/flightoperation/direction_controller.png" alt="" />
        <div class="direction-controller-top" title="前进" @click="changeDrc('pitch', 'top')"></div>
        <div
          class="direction-controller-right"
          title="右移"
          @click="changeDrc('roll', 'right')"
        ></div>
        <div
          class="direction-controller-bottom"
          title="后退"
          @click="changeDrc('pitch', 'bottom')"
        ></div>
        <div
          class="direction-controller-left"
          title="左移"
          @click="changeDrc('roll', 'left')"
        ></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 { buildGUID } from '@/utils/uuid';
  import { servicesTopic, services_replyTopic } from '@/utils/debugging/remote';
  import {
    drcDownTopicReize,
    eventsTopicSubscribeReize,
    servicesTopicReize,
    services_replyTopicReize,
  } from '@/utils/debugging/events';
  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(['changeLoadControl']);
  const props = defineProps({
    msgData: Object,
  });
  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,
    },
  });
  watch(
    () => props.msgData,
    (val) => {
      if (val.topic == 'thing/product/8UUXN5400A079H/events_reply') {
        console.log(val);
      }
    },
  );
  //修改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) => {
      console.log(res);
      if (res.length > 0) {
        res.forEach((item, index) => {
          if (item.userId != userInfo.id) {
            isLocked.value = 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();
    createSeizeConnection();
  };
  // 单拍
  const singleShot = () => {
    if (!flightGrab.value) {
      createMessage.warning('请先获取相机控制权');
      return;
    }
    // 开始拍照
    servicesTopicReize({
      bid: buildGUID(),
      method: 'camera_photo_take',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        payload_index: '99-0-0',
      },
    });
    services_replyTopicReize();
  };
  const drcSeq = ref(1);
  const enterDRC = () => {
    if (!flightGrab.value) {
      createMessage.warning('请先获取相机控制权');
      return;
    }
    createSeizeConnection();
    // 进入指令飞行控制模式
    const querys = {
      bid: buildGUID(),
      data: {
        hsi_frequency: 10,
        mqtt_broker: {
          address: 'http://175.27.168.120:6010',
          client_id: 'mqtt_client_1581F8HGX254V00A0BUY',
          enable_tls: false,
          expire_time: 3600,
          password: '',
          username: 'sdhc',
        },
        osd_frequency: 5,
      },
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      method: 'drc_mode_enter',
    };
    console.log(querys);
    servicesTopic(querys);
    drc_eart_beat();
  };
  let timer;
  const drc_eart_beat = () => {
    monitorDRC.value = true;
    // 每隔五秒发送drc心跳包
    drcSeq.value = drcSeq.value + 1;
    timer = window.setInterval(() => {
      const drcQuerys = {
        bid: buildGUID(),
        tid: buildGUID(),
        timestamp: new Date().getTime(),
        method: 'heart_beat',
        data: {
          timestamp: new Date().getTime(),
        },
        seq: drcSeq.value,
      };
      drcDownTopicReize(drcQuerys);
    }, 5000);
    // 订阅drc链路状态通知
    eventsTopicSubscribeReize();
  };
  const exitDRC = () => {
    const querys = {
      bid: buildGUID(),
      data: {},
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      method: 'drc_mode_exit',
    };
    servicesTopic(querys);
  };
  const seq = ref(1);
  // 控制方向
  const changeDrc = (type, val) => {
    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 (val == 'up') {
      data[type] = 1684;
    } else {
      data[type] = 364;
    }
    const querys = {
      seq: seq.value,
      method: 'stick_control',
      data: data,
    };
    drcDownTopicReize(querys);
  };
  onMounted(() => {
    // 获取mqtt客户端信息
    getRedisUser(userInfo.id).then((res) => {
      console.log(res);
      if (res) {
        redisUser.value = res;
      }
    });
    lockedClient();
    // // 接收消息
    getClient().on('message', (topic, message) => {
      const rs = JSON.parse(message);
      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 === '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);
        }
      }
    });
  });
  onUnmounted(() => {
    window.clearInterval(timer);
    destroySeizeConnection();
    changeRedisUser(false);
    monitorDRC.value = false;
  });
</script>
<style lang="less" scoped>
  .remote-debugging {
    position: absolute;
    bottom: 100px;
    left: 300px;
    width: 360px;
    height: 420px;
    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;
      div {
        cursor: pointer;
      }
    }
    .content-title {
      font-size: 14px;
      padding: 10px 0;
      span {
        font-size: 12px;
      }
    }
    .content-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10px 0;
      span {
        display: block;
        width: 50%;
        text-align: right;
      }
      button {
        text-align: center;
        background: none;
        font-size: 12px;
        box-shadow: 0px 10px 30px 0px rgba(0, 0, 6, 0.15);
        border-radius: 2px;
        border: 1px solid #3b4154;
        color: #fff;
      }
    }
    .content-button {
      margin-bottom: 10px;
      button {
        background: none;
        margin: 10px 0 0 10px;
        color: #fff;
      }
    }
    .direction-controller {
      position: relative;
      margin-top: 20px;
      img {
        margin-left: 60px;
        width: 200px;
      }
      .direction-controller-top {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 20px;
        left: 130px;
        cursor: pointer;
      }
      .direction-controller-right {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 70px;
        right: 80px;
        cursor: pointer;
      }
      .direction-controller-bottom {
        width: 50px;
        height: 50px;
        position: absolute;
        bottom: 20px;
        right: 130px;
        cursor: pointer;
      }
      .direction-controller-left {
        width: 50px;
        height: 50px;
        position: absolute;
        top: 80px;
        left: 80px;
        cursor: pointer;
      }
    }
  }
</style>
