<template>
  <VueDragResize
    :w="width"
    :h="height"
    :x="left"
    :y="top"
    :isActive="true"
    :parentLimitation="true"
    :isResizable="false"
  >
    <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-button">
          <a-button @click="obtain">
            <template #icon v-if="grabBtn"><CheckOutlined /></template>
            获取相机控制权
          </a-button>
          <a-button @click="singleShot">单拍</a-button>
        </div>
        <div class="direction-controller">
          <img
            class="controller-bg"
            src="@/assets/images/flightoperation/direction_controller.png"
            alt=""
          />
          <div
            class="direction-controller-top"
            title="俯视"
            @mousedown="changeDrc('pitch_speed', 'up', '俯视')"
            @mouseup="changeDrc('pitch_speed', 'up', '')"
          >
            <img
              src="@/assets/images/flightoperation/p-top-active.png"
              alt=""
              v-if="selectName == '俯视'"
            />
            <img src="@/assets/images/flightoperation/p-top.png" alt="" v-else />
          </div>
          <div
            class="direction-controller-right"
            title="右移"
            @mousedown="changeDrc('yaw_speed', 'up', '右移')"
            @mouseup="changeDrc('yaw_speed', 'up', '')"
          >
            <img
              src="@/assets/images/flightoperation/p-right-active.png"
              alt=""
              v-if="selectName == '右移'"
            />
            <img src="@/assets/images/flightoperation/p-right.png" alt="" v-else />
          </div>
          <div
            class="direction-controller-bottom"
            title="仰视"
            @mousedown="changeDrc('pitch_speed', 'down', '仰视')"
            @mouseup="changeDrc('pitch_speed', 'down', '')"
          >
            <img
              src="@/assets/images/flightoperation/p-bottom-active.png"
              alt=""
              v-if="selectName == '仰视'"
            />
            <img src="@/assets/images/flightoperation/p-bottom.png" alt="" v-else />
          </div>
          <div
            class="direction-controller-left"
            title="左移"
            @mousedown="changeDrc('yaw_speed', 'down', '左移')"
            @mouseup="changeDrc('yaw_speed', 'down', '')"
          >
            <img
              src="@/assets/images/flightoperation/p-left-active.png"
              alt=""
              v-if="selectName == '左移'"
            />
            <img src="@/assets/images/flightoperation/p-left.png" alt="" v-else />
          </div>
        </div>
        <div class="zoom">
          <a-slider
            v-model:value="zoomVale"
            :max="maxval"
            :min="2"
            :marks="marks"
            @change="cameraZoom"
          />
        </div>
      </div>
    </div>
  </VueDragResize>
</template>
<script setup lang="ts">
  import { onMounted, ref, watch, createVNode, 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 { buildGUID } from '@/utils/uuid';
  import { servicesTopic, services_replyTopic, errorName } 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';
  import { airPortStore } from '@/store/modules/airport';
  import VueDragResize from 'vue-drag-resize/src';

  const width = ref(400);
  const height = ref(440);
  const left = ref(300);
  const top = ref(100);
  const airPortStoreVal = airPortStore();
  const airPort = airPortStoreVal.getAirport;
  const uav = airPortStoreVal.getUAV;

  const selectName = ref('');
  const userStore = useUserStore();
  const userInfo = userStore.getUserInfo;
  const redisUser = ref({});
  const { createMessage } = useMessage();
  const emits = defineEmits(['changeLoadControl']);
  const props = defineProps({
    msgData: Object,
    cameraType: String,
  });
  const uavStatus = ref();
  const monitorDRC = ref(false);
  // 是否飞行控制权抢夺
  const flightGrab = 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,
    },
  });
  const zoomVale = ref(2);
  const maxval = ref(20);
  const marks = ref<Record<number, any>>({
    2: {
      style: {
        color: '#f50',
      },
      label: createVNode('strong', {}, '2'),
    },
    10: {
      style: {
        color: '#f50',
      },
      label: createVNode('strong', {}, '10'),
    },
    20: {
      style: {
        color: '#f50',
      },
      label: createVNode('strong', {}, '20'),
    },
  });
  watch(
    () => props.cameraType,
    (val) => {
      console.log('props.cameraType', val);
      cameraZoom();
    },
  );
  const bid = buildGUID();
  // 变焦
  const cameraZoom = () => {
    if (!flightGrab.value) {
      createMessage.warning('请先获取相机控制权');
      zoomVale.value = 2;
      return;
    }
    if (props.cameraType == 'wide') {
      createMessage.warning('广角相机不支持变焦，请先调整相机模式');
      return;
    }
    const querys = {
      bid: buildGUID(),
      method: 'camera_focal_length_set',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: {
        payload_index: uav.camera_index,
        camera_type: props.cameraType,
        zoom_factor: zoomVale.value,
      },
    };
    console.log('querys', querys);
    servicesTopicReize(querys);
  };
  //修改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 grabBtn = ref(false);
  const obtain = () => {
    // if (!getClient()) {
    //   createConnection();
    // }
    if (isLocked.value) {
      createMessage.warning('当前有用户正在操作，请稍后再试');
      return;
    }
    if (uavStatus.value == 0) {
      createMessage.warning('飞行器未开机');
      return;
    }
    if (grabBtn.value) {
      createMessage.warning('已经获取了飞行器控制权');
      return;
    }
    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();
    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: uav.camera_index,
      },
    });
    services_replyTopicReize();
  };
  let timer;
  const longPressTimer = ref();
  const longPressInterval = ref();
  const longPressDuration = ref(1000); // 长按时间阈值，单位为毫秒
  // 控制方向
  const changeDrc = (type, val, name) => {
    selectName.value = name;
    if (name !== '') {
      if (!flightGrab.value) {
        createMessage.warning('请先获取相机控制权');
        return;
      }
      let isLongPress = false;
      longPressTimer.value = setTimeout(() => {
        console.log('长按事件触发！');
        isLongPress = true;
        longPressInterval.value = setInterval(() => {
          let querys = getDRCFlightQuery(type, val);
          servicesTopicReize(querys);
          createMessage.info(name + '指令已发送');
        }, 1000);
      }, longPressDuration.value);
      if (isLongPress) {
        isLongPress = false;
        return;
      }
      // 画面拖动控制
      let querys = getDRCFlightQuery(type, val);
      servicesTopicReize(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, val) => {
    let data = {
      payload_index: uav.camera_index,
      locked: true,
      pitch_speed: 0,
      yaw_speed: 0,
    };
    if (val == 'up') {
      data[type] = 8;
    } else {
      data[type] = -8;
    }
    const querys = {
      bid: buildGUID(),
      method: 'camera_screen_drag',
      tid: buildGUID(),
      timestamp: new Date().getTime(),
      data: data,
    };
    console.log(querys);
    return 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.data.sub_device) {
        uavStatus.value = rs.data.sub_device.device_online_status;
      }
      if (rs.method == 'camera_photo_take') {
        if (rs.data.result == 0) {
          createMessage.success('拍照成功');
        } else {
          flightGrab.value = false;
          createMessage.error('拍照失败，' + errorName(rs.data.result));
        }
      }
      if (rs.method == 'flight_authority_grab' && rs.bid == bid) {
        if (rs.data.result == 0) {
          flightGrab.value = true;
          grabBtn.value = true;
          createMessage.success('相机控制权获取成功');
        } else {
          flightGrab.value = false;
          grabBtn.value = false;
          createMessage.error('相机控制权获取失败，' + errorName(rs.data.result));
        }
      }
    });
  });
  onUnmounted(() => {
    window.clearInterval(timer);
    destroySeizeConnection();
    changeRedisUser(false);
    monitorDRC.value = false;
  });
</script>
<style lang="less" scoped>
  .remote-debugging {
    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;
      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;
      .controller-bg {
        margin-left: 60px;
        width: 200px;
      }
      .direction-controller-top {
        position: absolute;
        top: 43px;
        left: 120px;
        cursor: pointer;
        img {
          width: 80px;
        }
      }
      .direction-controller-right {
        position: absolute;
        top: 60px;
        right: 127px;
        cursor: pointer;
        img {
          width: 38px;
        }
      }
      .direction-controller-bottom {
        position: absolute;
        bottom: 44px;
        left: 120px;
        cursor: pointer;
        img {
          width: 80px;
        }
      }
      .direction-controller-left {
        position: absolute;
        top: 60px;
        left: 103px;
        cursor: pointer;
        img {
          width: 38px;
        }
      }
    }
    .zoom {
      margin-top: 40px;
      ::v-deep .ant-slider-rail {
        background: #435382;
      }
    }
  }
</style>
