<template>
  <VueDragResize
    :w="width"
    :h="height"
    :x="left"
    :y="top"
    :isActive="true"
    :parentLimitation="true"
    :isResizable="false"
  >
    <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="flyTo">指点飞行</a-button>
          <!-- <a-button>智能环绕</a-button> -->
          <a-button @click="returnVoyage">一键返航</a-button>
          <a-button @click="obtain" style="background-color: #1b71e8; border: none">
            <template #icon v-if="flightGrab">
              <CheckOutlined />
            </template>
            获取飞行器控制权
          </a-button>
          <a-button @click="enterDRC" style="background-color: #24d365; border: none">
            <template #icon v-if="modeEnter">
              <CheckOutlined />
            </template>
            进入飞行控制
          </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="上升"
              @mousedown="changeDRC('throttle', 'up', '上升')"
              @mouseup="changeDRC('throttle', 'up', '')"
            >
              <img
                src="@/assets/images/flightoperation/top-active.png"
                alt=""
                v-if="selectName == '上升'"
              />
              <img src="@/assets/images/flightoperation/top.png" alt="" v-else />
            </div>
            <div
              class="info-item-right"
              title="右旋转"
              @mousedown="changeDRC('yaw', 'up', '右旋转')"
              @mouseup="changeDRC('yaw', 'up', '')"
            >
              <img
                src="@/assets/images/flightoperation/right-active.png"
                alt=""
                v-if="selectName == '右旋转'"
              />
              <img src="@/assets/images/flightoperation/right.png" alt="" v-else />
            </div>
            <div
              class="info-item-bottom"
              title="下降"
              @mousedown="changeDRC('throttle', 'down', '下降')"
              @mouseup="changeDRC('throttle', 'down', '')"
            >
              <img
                src="@/assets/images/flightoperation/bottom-active.png"
                alt=""
                v-if="selectName == '下降'"
              />
              <img src="@/assets/images/flightoperation/bottom.png" alt="" v-else />
            </div>
            <div
              class="info-item-left"
              title="左旋转"
              @mousedown="changeDRC('yaw', 'down', '左旋转')"
              @mouseup="changeDRC('yaw', 'down', '')"
            >
              <img
                src="@/assets/images/flightoperation/left-active.png"
                alt=""
                v-if="selectName == '左旋转'"
              />
              <img src="@/assets/images/flightoperation/left.png" alt="" v-else />
            </div>
          </div>
          <div class="info-item">
            <!-- <img src="@/assets/images/flightoperation/flight_control.png" alt="" /> -->
            <div
              class="info-item-top"
              title="前进"
              @mousedown="changeDRC('pitch', 'up', '前进')"
              @mouseup="changeDRC('pitch', 'up', '')"
            >
              <img
                src="@/assets/images/flightoperation/top-active.png"
                alt=""
                v-if="selectName == '前进'"
              />
              <img src="@/assets/images/flightoperation/top.png" alt="" v-else />
            </div>
            <div
              class="info-item-right"
              title="右移"
              @mousedown="changeDRC('roll', 'up', '右移')"
              @mouseup="changeDRC('roll', 'up', '')"
            >
              <img
                src="@/assets/images/flightoperation/right-active.png"
                alt=""
                v-if="selectName == '右移'"
              />
              <img src="@/assets/images/flightoperation/right.png" alt="" v-else />
            </div>
            <div
              class="info-item-bottom"
              title="后退"
              @mousedown="changeDRC('pitch', 'down', '后退')"
              @mouseup="changeDRC('pitch', 'down', '')"
            >
              <img
                src="@/assets/images/flightoperation/bottom-active.png"
                alt=""
                v-if="selectName == '后退'"
              />
              <img src="@/assets/images/flightoperation/bottom.png" alt="" v-else />
            </div>
            <div
              class="info-item-left"
              title="左移"
              @mousedown="changeDRC('roll', 'down', '左移')"
              @mouseup="changeDRC('roll', 'down', '')"
            >
              <img
                src="@/assets/images/flightoperation/left-active.png"
                alt=""
                v-if="selectName == '左移'"
              />
              <img src="@/assets/images/flightoperation/left.png" alt="" v-else />
            </div>
          </div>
        </div>
      </div>
    </div>
  </VueDragResize>
</template>
<script setup lang="ts">
  import { onMounted, ref, watch, reactive, onUnmounted } from 'vue';
  import {
    getClient,
    createSeizeConnection,
    destroySeizeConnection,
    connection,
  } from '@/utils/mqtt';
  import { CloseOutlined, CheckOutlined } from '@ant-design/icons-vue';
  import { vDrag } from '@/utils/drag';
  import { drcDownTopicReize, eventsTopicSubscribeReize } from '@/utils/debugging/events';
  import {
    servicesTopic,
    services_replyTopic,
    drcDownTopic,
    eventsTopicSubscribe,
    drcUpTopic,
    errorName,
  } 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';
  import VueDragResize from 'vue-drag-resize/src';
  import { airPortStore } from '@/store/modules/airport';
  import { EventBus } from '@/utils/eventBus';

  const uavStatus = ref();
  const airPortStoreVal = airPortStore();
  const uav = airPortStoreVal.getUAV;
  const isTakeOff = ref(false);
  const width = ref(380);
  const height = ref(390);
  const left = ref(700);
  const top = ref(100);
  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,
  });
  const selectName = ref('');
  const bid = buildGUID();
  //修改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.warning('当前有用户正在操作，请稍后再试');
      return;
    }
    if (isTakeOff.value) {
      createMessage.warning('请勿重复操作');
      return;
    }
    emits('clickTakeOff');
    changeRedisUser(true);
  };
  // 指点飞行
  const flyTo = () => {
    if (uavStatus.value == 0) {
      createMessage.warning('飞行器未开机');
      return;
    }
    emits('clickFlyTo');
  };
  // 获取
  const obtain = () => {
    // if (!getClient()) {
    //   createConnection();
    // }
    if (isLocked.value) {
      createMessage.warning('当前有用户正在操作，请稍后再试');
      return;
    }
    if (uavStatus.value == 0) {
      createMessage.warning('飞行器未开机');
      return;
    }
    if (flightGrab.value) {
      createMessage.warning('已经获取了飞行器控制权');
      return;
    }
    createMessage.info('正在获取飞行器控制权，请稍候');
    changeRedisUser(true);
    // 飞行控制权抢夺
    servicesTopic({
      bid: bid,
      method: 'flight_authority_grab',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {},
    });
    // 负载控制权抢夺
    servicesTopic({
      bid: bid,
      method: 'payload_authority_grab',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        payload_index: uav.camera_index,
      },
    });
    services_replyTopic();
  };
  // 一键返航
  const returnBtn = ref(false);
  const returnVoyage = () => {
    if (uavStatus.value == 0) {
      createMessage.warning('飞行器未开机');
      return;
    }
    if (returnBtn.value) {
      createMessage.warning('正在返航或已返航，请勿重复操作');
      return;
    }
    returnBtn.value = true;
    servicesTopic({
      bid: buildGUID(),
      method: 'return_home',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {},
    });
  };
  const seq = ref(1);
  const longPressTimer = ref();
  const longPressInterval = ref();
  const longPressDuration = ref(1000); // 长按时间阈值，单位为毫秒
  const changeDRC = (type, value, name) => {
    selectName.value = name;
    if (name !== '') {
      console.log('鼠标按下');
      if (!flightGrab.value) {
        createMessage.warning('请先获取飞行器控制权');
        return;
      }
      if (!modeEnter.value) {
        createMessage.warning('请先进入指令飞行控制');
        return;
      }
      let isLongPress = false;
      longPressTimer.value = setTimeout(() => {
        console.log('长按事件触发！');
        isLongPress = true;
        longPressInterval.value = setInterval(() => {
          seq.value = seq.value + 1;
          let querys = getDRCFlightQuery(type, value, seq);
          drcDownTopicReize(querys);
          createMessage.info(name + '指令已发送');
        }, 1000);
      }, longPressDuration.value);
      if (isLongPress) {
        isLongPress = false;
        return;
      }
      seq.value = seq.value + 1;
      let querys = getDRCFlightQuery(type, value, seq);
      drcDownTopicReize(querys);
      createMessage.info(name + '指令已发送');
    } else {
      if (longPressTimer.value) {
        clearTimeout(longPressTimer.value);
        longPressTimer.value = null;
        console.log('清除延时器');
      }
      if (longPressInterval.value) {
        clearTimeout(longPressInterval.value);
        longPressInterval.value = null;
        console.log('清除定时器');
      }
      console.log('鼠标松开');
    }
  };
  const getDRCFlightQuery = (type, value, seq) => {
    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(),
    };
    console.log(querys);
    return querys;
  };
  const drcSeq = ref(1);
  let drc_mode_enter_timer;
  const drc_mode_enter_val = ref(1);
  const enterDRC = () => {
    if (uavStatus.value == 0) {
      createMessage.warning('飞行器未开机');
      return;
    }
    if (!flightGrab.value) {
      createMessage.warning('请先获取飞行控制权');
      return;
    }
    createSeizeConnection();
    createMessage.info('正在进入飞行控制，请稍后');
    // 进入指令飞行控制模式
    const { protocol, host, port, endpoint } = connection;
    const connectUrl = `${protocol}://${host}:${port}${endpoint}`;
    const querys = {
      bid: bid,
      data: {
        hsi_frequency: 10,
        mqtt_broker: {
          address: connectUrl,
          // client_id: 'mqtt_client_1581F8HGX254V00A0BUY',
          client_id: 'mqtt_client_1581F8HGX254V00A0BUYSeize',
          // client_id: 'mqttx_' + Math.random().toString(16).substring(2, 8),
          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();
    drcUpTopic();
    drc_mode_enter_timer = window.setInterval(() => {
      if (drc_mode_enter_val.value > 30) {
        window.clearInterval(drc_mode_enter_timer);
        drc_mode_enter_timer = null;
        drc_mode_enter_val.value = 0;
        createMessage.error('进入指令飞行控制模式失败，无响应');
        return;
      }
      drc_mode_enter_val.value++;
    }, 1000);
  };
  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 = () => {
    if (uavStatus.value == 0) {
      createMessage.warning('飞行器未开机');
      return;
    }
    createMessage.info('正在退出飞行控制，请稍后');
    const querys = {
      bid: bid,
      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.mode_code = rs.data.mode_code;
      }
      if (rs.data.sub_device) {
        uavStatus.value = rs.data.sub_device.device_online_status;
      }
      if (rs.method == 'flight_authority_grab' && rs.bid == bid) {
        if (rs.data.result == 0) {
          flightGrab.value = true;
          createMessage.success('飞行控制权抢夺成功');
        } else {
          flightGrab.value = false;
          createMessage.error('飞行控制权抢夺失败，' + errorName(rs.data.result));
        }
      }
      if (rs.method == 'drc_mode_enter' && rs.bid == bid) {
        if (rs.data.result == 0) {
          modeEnter.value = true;
          createMessage.success('进入指令飞行控制模式成功');
        } else {
          modeEnter.value = false;
          createMessage.error('进入指令飞行控制模式失败，' + errorName(rs.data.result));
        }
      }
      if (rs.method == 'drc_mode_exit' && rs.bid == bid) {
        if (rs.data.result == 0) {
          modeEnter.value = false;
          createMessage.success('退出指令飞行控制模式成功');
          changeRedisUser(false);
          window.clearInterval(drc_mode_enter_timer);
        } else {
          createMessage.error('退出指令飞行控制模式失败，' + errorName(rs.data.result));
          window.clearInterval(drc_mode_enter_timer);
        }
      }
      // 一键返航
      if (rs.method === 'return_home') {
        if (rs.data.result == 0) {
          createMessage.success('一键返航成功');
          monitorDRC.value = false;
          returnBtn.value = true;
        } else {
          createMessage.error('一键返航失败，' + errorName(rs.data.result));
          returnBtn.value = false;
        }
      }
      if (rs.method === 'takeoff_to_point') {
        if (rs.data.result == 0) {
          createMessage.success('一键起飞成功');
          isTakeOff.value = true;
          EventBus.emit('closeTranslation', null);
        } else {
          createMessage.error('一键起飞失败，' + errorName(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 {
          drc_eart_beat();
          createMessage.error('DRC连接失败，' + errorName(rs.data.result));
        }
      }
      // 指点飞行
      if (rs.method == 'fly_to_point') {
        if (rs.data.result == 0) {
          createMessage.success('指点飞行成功');
          EventBus.emit('closeTranslation', null);
        } else {
          createMessage.error('指点飞行失败，' + errorName(rs.data.result));
        }
      }
    });
  });
  onUnmounted(() => {
    window.clearInterval(timer);
    window.clearInterval(drc_mode_enter_timer);
    destroySeizeConnection();
    changeRedisUser(false);
    monitorDRC.value = false;
  });
</script>
<style lang="less" scoped>
  .flight-control {
    width: 96%;
    height: 98%;
    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 {
          position: absolute;
          top: 8px;
          left: 20px;
          cursor: pointer;

          img {
            width: 62px;
          }
        }

        .info-item-right {
          position: absolute;
          top: 30px;
          right: 36px;
          cursor: pointer;
        }

        .info-item-bottom {
          position: absolute;
          bottom: 0px;
          left: 21px;
          cursor: pointer;

          img {
            width: 62px;
          }
        }

        .info-item-left {
          position: absolute;
          top: 30px;
          left: -2px;
          cursor: pointer;
        }
      }
    }
  }
</style>
