import { Control_API } from "../api";
import mount from "../components/mount";
import moment from "moment";

let positions = []; // 飞机走过的点, 会一直累计, 每n秒减半一次, 防止爆内存
setInterval(() => {
  if (positions.length > 1000) {
    positions = positions.filter((x, index) => index % 2 === 0);
  }
}, 60000);
window.positions = () => {
  console.log(positions);
};
const defaultPos = {
  latitude: 0, // 纬度
  longitude: 0, // 经度
};

const uavRealTimeData = {
  attitude: {
    roll: 0, // 飞机的俯仰值：向前为正，向后为负。单位为度。
    pitch: 0, // 飞机的横滚值：正向为正，反向为负。单位为度。
    yaw: 0, // 飞机的偏航值，其中0对应于正北航向。顺时针偏航会增加偏航值。
  },
  parachute: 1, // 降落伞状态 0正常，1未启用，2控制器不在线，3伞包未连接，4降落伞故障
  parachuteState: 1, // 1降落伞进入警戒，2降落伞退出警戒，3降落伞开伞
  accelerator: 0, // 飞机油门通道值
  locationCoordinate3D: {
    // 地理位置信息
    altitude: 0, // 相对高度，如果需要获取绝对高度 请查看Gps类
    latitude: defaultPos.latitude, // 纬度
    longitude: defaultPos.longitude, // 经度
  },
  gps: {
    absoluteAlt: 0, // 绝对高度，以米为单位
    relativeAlt: 0, // 相对高度，以米为单位
    satelliteCount: 0, // 搜星数，卫星数越大，GPS信号越强
    fixType: "", // GPS的锁定类型
    levelDivisor: 0, // 水平因子
    verticalDivisor: 0, // 垂直因子
    type: 15, // 19 RTK，15 GPS,0 默认（固件未更新）
    isMainSensor: false, // true主传感器，false备用传感器
  },
  rtk: {
    absoluteAlt: 0, // 绝对高度，以米为单位
    relativeAlt: 0, // 相对高度，以米为单位
    satelliteCount: 0, // 搜星数，卫星数越大，GPS信号越强
    fixType: "", // GPS的锁定类型
    levelDivisor: 0, // 水平因子
    verticalDivisor: 0, // 垂直因子
    type: 19, // 19 RTK，15 GPS,0 默认（固件未更新）
    isMainSensor: false, // true主传感器，false备用传感器
  },
  flyDistance: 0, // 当前飞行里程
  distanceToHome: 0, // 距离home的位置
  flyTime: 0, // 获取飞行时长，只记录飞机起飞到飞机降落的时间单位(毫秒),下次飞机起飞清零
  groundSpeed: 0, // hud地速，单位m/s, 飞行速度
  velocityZ: 0, // 使用NED（北-东-下）坐标系，飞机在z方向上的当前速度，以米/秒为单位, 爬升率
  rcChannelState: 0, // 0摇杆处于中位，-99摇杆未连接，-98为外场摇杆权限，1与-1俯仰，2与-2横滚，3与-3油门，4与-4偏航（大于0表示该通道处于高位，小于0表示该通道处于低位）
  obstacle: null /* {
    // 避障信息（#272）
    minDistance: 100, // 壁障最小距离单位（cm）
    maxDistance: 2000, // 壁障最大距离单位（cm）
    distances: [
      // distances[36],360度避障距离，每隔10度一个距离
      3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000,
      3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000,
      3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000, 3000,
    ],
    enable: true, // true触发避障，false未触发
    obsDistance: 100, // 避障使能距离单位（m）
    type: 0, // 感器类型
  } */,
  healthData: {
    // 健康管理模块预警信息（#275）
    AVI: {
      //航电健康预警信息
      code: "0x1510000",
      description: "",
      title: "航电系统数据待接收",
      warningLevel: "NOTICE",
    },
    BAT: {
      //电池健康预警信息
      code: "0x1610000",
      description: "",
      title: "电池系统数据待接收",
      warningLevel: "NOTICE",
    },
    OBS: {
      //避障健康预警信息
      code: "0x1810000",
      description: "",
      title: "避障系统数据待接收",
      warningLevel: "NOTICE",
    },
    GPS: {
      //GPS健康预警信息
      code: "0x1310000",
      description: "",
      title: "GPS数据待接收",
      warningLevel: "NOTICE",
    },
    SPE: {
      //1.4G专网健康预警信息
      code: "0x1110000",
      description: "",
      title: "1.4信号数据待接收",
      warningLevel: "NOTICE",
    },
    RTK: {
      //RTK健康预警信息
      code: "0x1910001",
      description: "",
      title: "RTK数据待接收",
      warningLevel: "NOTICE",
    },
    NX: {
      //NX链路健康预警信息
      code: "0x2110000",
      description: "",
      title: "NX通信数据待接收",
      warningLevel: "NOTICE",
    },
    CHUTE: {
      //降落伞健康预警信息
      code: "0x1710000",
      description: "",
      title: "	降落伞系统数据待接收",
      warningLevel: "NOTICE",
    },
    VPN: {
      //5G VPN网健康预警信息
      code: "0x1210000",
      description: "",
      title: "1.4信号数据待接收",
      warningLevel: "NOTICE",
    },
  },
  batteryList: [
    // 无人机电池信息, 会有多个电池的情况
    /* {
      id: -1, // 电池id,0普通电池,52左智能电池，53右智能电池
      active: 0,  // 电池激活类型（鹰巢无人机，这个参数才生效）
      chargeRemaining: -1, // 电池中的剩余能量百分比
      current: 0, // 电池的实时电流消耗（A）。负值表示电池正在放电，正值表示正在充电
      cycleIndex: -1, // 充电循环次数
      fullChargeCapacity: -1, // 电池完全充电时存储在电池中的总电量 100%
      lowVoltWarnValue: -1, // 低电压报警阈值（V）
      temperature: -1, // 电池温度(℃)
      voltage: -1, // 返回当前电池电压（V）
      statusType: 3, // 电池状态 0无效值，1开机，2充电中，3关机
    }, */
  ],
  msg: {
    // 飞控应答消息
    code: 0,
    cmd: 0,
    text: "",
  },
  msgList: [], // 飞控应答消息记录
};

const state = {
  openTest: false, // 开启测试
  uav: null, // 选择中的无人机信息
  uavRealTimeData,
  airlineEntity: null, // 航线实例
  uavModelEntity: null, // 飞机模型实例
  smuTime: false, // 模拟上报定时器
  airlineData: null, // 当前选择的航线数据
  airlineId: "", // 当前选择的航线id(任务中带的航线)
  flyMode: "auto", // 飞行模式, auto: 自动, manual: 手动,
  showVideo: false, // 显示视频
  mountList: [
    /* {
      gimbalName: "MMC_Gimbal_Z40",
      mountId: 12,
    }, */
  ], // 挂载列表
  selectMount: null, // 选中的挂载
  showPlayer: false, //显示播放器
  showPanel: false, //显示数据面板
  // 任务列表
  taskList: [
    /* {
      name: "任务",
      id: 1,
      children: [],
      airway: {
        name: "航线名称1",
        id: 1,
        content:
          '{"filename":"肇庆航线20240318","line":{"baseSpeed":3},"content":[{"uuid":"1nmI-Fo18IagbcVJsia7Q","latitude":23.178153411812204,"longitude":112.57807281336807,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"9pTbBPlF8iIwbUNqusyHK","latitude":23.17783116525969,"longitude":112.57797543441967,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"s91IhN22wuaeyG-UQs0XR","latitude":23.17786413506686,"longitude":112.57824336604547,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]},{"uuid":"xS_JIl3wxQrhMPdpcjcSn","latitude":23.17820934975604,"longitude":112.5781357731637,"alt":100,"yawAngle":0,"pitchAngle":0,"speed":3,"actions":[]}],"baseSpeed":3,"gimbalYaw":0,"gimbalPitch":0,"alt":100}',
      },
    }, */
  ],
};

const mutations = {
  /**
   * 单纯的给state赋值
   * @param {*} param0
   * @param {*} data {key: '', value}
   */
  setState(state, data) {
    try {
      state[data.key] = data.value;
    } catch (e) {
      console.log("setDate err", e);
    }
  },
};

const actions = {
  /**
   * 销毁无人机相关对象
   * @param {} param0
   * @param {*} data
   */
  destroy({ commit, state, dispatch }, data) {
    window.$mmc.viewer.entities.remove(state.airlineEntity);
    window.$mmc.viewer.entities.remove(state.uavModelEntity);
    commit("setState", { key: "uav", value: null });
    commit("setState", { key: "airlineEntity", value: null });
    commit("setState", { key: "uavModelEntity", value: null });
    commit("setState", { key: "airlineData", value: null });
    commit("setState", { key: "flyMode", value: "auto" });
    commit("setState", { key: "mountList", value: [] });
    commit("setState", { key: "selectMount", value: null });
    commit("setState", { key: "showVideo", value: false });
    commit("setState", { key: "uavRealTimeData", value: uavRealTimeData });

    positions = [];
  },
  /**
   * 开始测试
   * @param {*} param0
   * @param {*} data.open 是否开启
   */
  // test({ commit, dispatch }, { open }) {
  //   commit("setState", { key: "openTest", value: open });
  //   dispatch("smuUavRealTimeData", { open });
  // },
  /**
   * 模拟无人机实时数据上报
   * @param {*} param0
   * @param {boolean} data.open 开关
   */
  smuUavRealTimeData({ commit, state, dispatch }, data) {
    // 目前只支持飞控中心链路
    if (data.open) {
      const time = setInterval(() => {
        if (!state.uav) {
          return;
        }
        const data = {
          locationCoordinate3D: {
            // 地理位置信息
            altitude: Math.random() * 10, // 相对高度，如果需要获取绝对高度 请查看Gps类
            latitude: 22.433 + Math.random() * 0.01, // 纬度
            longitude: 113.75 + Math.random() * 0.01, // 经度
          },
        };
        dispatch("updateByMQTT", {
          258: { data },
          259: {
            data: {
              gimbalName: "MMC_Gimbal_Z40Pro",
              mountId: 11,
              mountType: 1036,
              payload: [165, 9, 3, 0, 57],
              widgetHeight: 500,
              widgetWidth: 540,
            },
          },
        });
      }, 10000);
      commit("setState", { key: "smuTime", value: time });
    } else {
      clearInterval(state.smuTime);
    }
  },
  // 通过mqtt更新实时采集数据
  updateByMQTT({ commit, state, dispatch }, data) {
    if (state.uav.network == 2) {
      // console.log(data,'datadata');
      // mqtt链路
      const type258 = data[258]?.data || {};
      const type268 = data[268]?.data || {};
      const type257 = data[257]?.data || {};
      const type259 = data[259]?.data;
      const type2006 = data[2006]?.data;
      const type2017 = data[2017]?.data;
      const type272 = data[272]?.data; // 避障信息
      const type275 = data[275]?.data; // 健康管理
      const type270 = data[270]?.data; //飞控应答消息

      let msgList = state.uavRealTimeData.msgList || [];

      if (type270) {
        type270.timestamp = data[270].timestamp;
        let findMsg = msgList.find((item) => item.timestamp === type270.timestamp);
        if (!findMsg) {
          msgList.push({
            ...type270,
            time: moment(type270.timestamp).format("YYYY-MM-DD HH:mm:ss"),
          });
        }
      }

      // gps 需要判断使用哪个
      if (type258.rtk?.isMainSensor) {
        type258.gps = type258.rtk;
      }
      // 257返回单次电池信息, 实际飞机可能有多个电池, 但是每次只返回其中一个信息, 通过id判断来组成电池列表
      let batteryList = state.uavRealTimeData?.batteryList || [];
      if (type257?.id) {
        let findIndex = -1;
        batteryList.find((item, i) => {
          if (item.id === type257.id) {
            findIndex = i;
            return true;
          }
        });
        if (findIndex !== -1) {
          batteryList[findIndex] = type257;
        } else {
          batteryList.push(type257);
        }
      }
      commit("setState", {
        key: "uavRealTimeData",
        value: {
          ...state.uavRealTimeData,
          ...type258,
          ...type268,
          ...type2006,
          ...type2017,
          obstacle: type272 || state.uavRealTimeData.obstacle,
          healthData: type275 || state.uavRealTimeData.healthData,
          batteryList,
          msg: type270,
          msgList,
        },
      });

      if (type259) {
        // 通过返回的259类型,获取挂载列表
        const find = state.mountList.find(
          (item) => item.mountId === type259.mountId
        );
        if (!find) {
          state.mountList.push(type259);
          state.mountList.forEach((item) => {
            const find = mount.list.find((item1) => {
              return item1.name === item.gimbalName;
            });
            if (find) {
              item.icon = find.icon;
            }
          });
          commit("setState", { key: "mountList", value: [...state.mountList] });
        }
      }
    } else {
      const uavInfo = data?.deviceData?.data?.uavInfo;

      if (uavInfo) {
        // 地面站链路
        commit("setState", {
          key: "uavRealTimeData",
          value: {
            ...state.uavRealTimeData,
            attitude: {
              roll: uavInfo.roll, // 飞机的俯仰值：向前为正，向后为负。单位为度。
              pitch: uavInfo.pitch, // 飞机的横滚值：正向为正，反向为负。单位为度。
              yaw: uavInfo.yaw, // 飞机的偏航值，其中0对应于正北航向。顺时针偏航会增加偏航值。
            },
            accelerator: 0, // 飞机油门通道值, 地面站链路获取不到
            locationCoordinate3D: {
              // 地理位置信息
              altitude: uavInfo.height, // 相对高度，如果需要获取绝对高度 请查看Gps类
              latitude: uavInfo.latitude, // 纬度
              longitude: uavInfo.longitude, // 经度
            },
            gps: {
              absoluteAlt: uavInfo.altitude, // 绝对高度，以米为单位
              relativeAlt: uavInfo.height, // 相对高度，以米为单位
              satelliteCount: 0, // 搜星数，卫星数越大，GPS信号越强
            },
            flyDistance: uavInfo.flightDistance, // 当前飞行里程
            distanceToHome: uavInfo.distanceToHome, // 距离home的位置
            flyTime: uavInfo.flightTime * 1000, // 获取飞行时长，只记录飞机起飞到飞机降落的时间单位(毫秒),下次飞机起飞清零
            groundSpeed: uavInfo.groundSpeed, // hud地速，单位m/s, 飞行速度
            velocityZ: uavInfo.climbRate, // 使用NED（北-东-下）坐标系，飞机在z方向上的当前速度，以米/秒为单位, 爬升率
            voltage: uavInfo.voltage, // 返回当前电池电压（V）
            chargeRemaining: uavInfo.battaryRemain, // 电池中的剩余能量百分比
            flightSortie: uavInfo.flightSortie, // 本次架次
          },
        });
      }

      // 挂载列表
      const mountList =
        data?.deviceData?.data?.mountInfo?.map((item) => {
          const find = mount.list.find((item1) => {
            return item1.name === item.mountName;
          });
          if (find) {
            item.icon = find.icon;
          }
          return {
            gimbalName: item.mountName,
            mountId: item.mountType,
            icon: item.icon,
          };
        }) || [];
      commit("setState", { key: "mountList", value: mountList });
    }

    if (state.uavRealTimeData.locationCoordinate3D.longitude) {
      if (
        state.uavRealTimeData.locationCoordinate3D.longitude ===
          defaultPos.longitude &&
        state.uavRealTimeData.locationCoordinate3D.latitude ===
          defaultPos.latitude
      ) {
        // 默认坐标不记录
      } else {
        // const posData = UAVDataParser(state.uavRealTimeData);    // 这种写法在执行rollup混淆压缩后, posData对象会变成elementUI的对象,原因未知
        // 更新轨迹
        positions.push(UAVDataParser(state.uavRealTimeData).position);
      }

      if (state.uavRealTimeData.locationCoordinate3D.longitude !== defaultPos.longitude && !state.uavModelEntity) {
        dispatch("createUavModel");
        dispatch("createAirline");
        dispatch("flyToUavModel");
      }
    }
  },
  /**
   * 订阅无人机数据
   * @param {*} param0
   * @param {object} data
   */
  subscribe({ state, dispatch }) {
    if (state.uav.network === 1) {
      window.$mmc.$store.dispatch("MMCMQTT/subscribe", {
        topic: "PX4/RECEIVE/" + state.uav.deviceId,
        callback(ok) {
          ok && console.log("mqtt订阅主题", "PX4/RECEIVE/" + state.uav.deviceId);
        },
      });
    } else {
      // 由于ws连接到地面站是使用广播形式获取无人机数据的,所以在组件创建时先连接ws,后续选择无人机时,通过广播数据,筛选出选择的无人机信息出来
      try {
        const username =
          window.$mmc.$store.state.MMCFlightControlCenter.userInfo.userName;
        const token = window.$mmc.$store.state.MMCFlightControlCenter.token;
        window.$mmc.$store
          .dispatch("MMCGroundStation/init", {
            url: window.$mmc.$store.getters["MMCFlightControlCenter/wsUrl"],
            userInfo: {
              type: 100,
              systemCode: "mmc",
              state: 1,
              username,
              token,
              appId: "40003",
            },
            loginCallback() {
              // 订阅取数据不一定有用, ws的订阅需要后端做了处理才生效, 未处理则会收到所有无人机的数据, 负担非常大
              window.$mmc.$store.dispatch(
                "MMCGroundStation/subscribe",
                state.uav.deviceId
              );
            },
          })
          .then(() => {
            console.log("地面站连接成功");
          });
      } catch (e) {
        console.log("地面站连接失败", e);
      }
    }
  },
  /**
   * 取消订阅
   * @param {} param0
   */
  unsubscribe({ state, dispatch }) {
    if (state.uav.network === 1) {
      window.$mmc.$store.dispatch("MMCMQTT/unsubscribe", {
        topic: "PX4/RECEIVE/" + state.uav.deviceId,
        callback(ok) {
          ok &&
            console.log("mqtt取消订阅主题", "PX4/RECEIVE/" + state.uav.deviceId);
        },
      });
    } else {
      // 地面站取消订阅后需要关闭ws连接
      window.$mmc.$store.dispatch(
        "MMCGroundStation/unsubscribe",
        state.uav.deviceId
      );
      window.$mmc.$store.dispatch("MMCGroundStation/end");
    }

    dispatch("destroy");
  },
  /**
   * 断开ws连接
   * @param {*} param0
   */
  end({ state, dispatch }) {
    window.$mmc.$store.dispatch("MMCMQTT/end");
    window.$mmc.$store.dispatch("MMCGroundStation/end");
  },
  /**
   * 创建飞机模型
   * @param {*} param0
   * @param {*} data
   */
  createUavModel({ state, commit }, data) {
    if (!state.uavModelEntity) {
      // let ondelUrl = '';
      // ondelUrl = state.uav.modelVictor.replace(
      //   'https://mmc-crm.oss-cn-shenzhen.aliyuncs.com',
      //   'modelRequest'
      // );
      const entity = window.$mmc.viewer.entities.add({
        id: "model_" + state.uav.deviceId,
        orientation: new Cesium.CallbackProperty(() => {
          const posData = UAVDataParser(state.uavRealTimeData);
          return posData.orientation;
        }, false),
        position: new Cesium.CallbackProperty(() => {
          const posData = UAVDataParser(state.uavRealTimeData);
          return posData.position;
        }, false),
        model: {
          uri:
            state.uav.modelVictor ||
            "https://tmj.mmcuav.cn/cesium/model/1800_20220816_no_effect283g2color.gltf",
          minimumPixelSize: 100,
          maximumScale: 20000,
          scale: 1,
          color: Cesium.Color.fromCssColorString("#550088"), // 颜色
          // color: Cesium.Color.fromAlpha(Cesium.Color.BLACK, parseFloat(1.0)), //包含透明度的颜色
          colorBlendMode: Cesium.ColorBlendMode["MIX"],
        },
        label: {
          text: state.uav.name || "",
          font: "14pt monospace",
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, -20),
          eyeOffset: new Cesium.Cartesian3(0, 0, -10),
        },
      });
      commit("setState", { key: "uavModelEntity", value: entity });
    }
  },
  /**
   * 创建轨迹航线
   * @param {*} param0
   * @param {*} data
   */
  createAirline({ state, commit }, data) {
    if (!state.airlineEntity) {
      // 创建航线
      const airlineEntity = window.$mmc.viewer.entities.add({
        id: "airline_" + state.uav.deviceId,
        polyline: {
          positions: new Cesium.CallbackProperty((time, result) => {
            return positions;
          }, false),
          width: 5,
          show: true,
          material: Cesium.Color.fromCssColorString("#6DD400"),
        },
      });
      airlineEntity.show = true;

      commit("setState", { key: "airlineEntity", value: airlineEntity });
    }
  },
  /**
   * 镜头飞向飞机模型
   * @param {*} param0
   * @param {*} data
   */
  flyToUavModel({ state, commit }, data) {
    if (state.uavModelEntity) {
      window.$mmc.viewer.flyTo(state.uavModelEntity, {
        offset: new Cesium.HeadingPitchRange(
          0,
          -Cesium.Math.PI_OVER_TWO,
          10000
        ),
      });
    }
  },

  /**
   * 一键起飞
   * @param {function} data.callback  //完成回调
   */
  async takeOff({ state }, data) {
    console.log(state.airlineData, data);
    if (state.uav.network == 2) {
      try {
        // 生成架次號
        const getFlightSortic = await Control_API.getFlightSortic({
          taskId: state.airlineData.id,
          deviceHardId: state.uav.deviceId,
        });
        // 上传航线指令
        const waypointList = state.airlineData?.content;
        window.$mmc.$store.dispatch("MMCMQTT/publish", {
          topic: "PX4/OBTAIN/" + state.uav.deviceId,
          data: {
            type: window.$mmc.$store.state.MMCMQTT.orders.航线上传,
            data: {
              taskId: state.airlineData.id,
              flightSortiesID: getFlightSortic.data,
              waypointList: waypointList,
              autoFlightSpeed: state.airlineData.baseSpeed,
              finishedAction: "GO_HOME",
              headingMode: "AUTO",
              isExitMissionOnRCSignalLostEnabled: true,
              maxFlightSpeed: 12,
            },
          },
          callback() {},
        });

        // 告诉飞控开始任务,并且把架次号和 任务id传过去
        window.$mmc.$store.dispatch("MMCMQTT/publish", {
          topic: "PX4/OBTAIN/" + state.uav.deviceId,
          data: {
            type: window.$mmc.$store.state.MMCMQTT.orders.绑定任务id,
            data: {
              taskId: state.airlineData.id,
              flightSortiesID: getFlightSortic.data,
            },
          },
          callback() {},
        });

        // 更改任务状态

        // 起飞指令
        setTimeout(() => {
          window.$mmc.$store.dispatch("MMCMQTT/publish", {
            topic: "PX4/OBTAIN/" + state.uav.deviceId,
            data: {
              type: window.$mmc.$store.state.MMCMQTT.orders.航线一键起飞,
              data: {
                taskId: state.airlineData.id,
                seq: 0,
              },
            },
            callback() {
              data?.callback && data.callback(true, getFlightSortic.data);
            },
          });
        }, 3000);
      } catch (e) {
        console.log("一键起飞失败", e);
        data?.callback && data.callback(false);
      }
    } else {
      // 地面站链路
      window.$mmc.$store.dispatch("MMCGroundStation/order", {
        order: "航线上传",
        data: {
          cmdValue: state.airlineData?.id,
        },
        deviceHardId: state.uav.deviceId,
      });

      // 起飞指令
      setTimeout(() => {
        window.$mmc.$store.dispatch("MMCGroundStation/order", {
          order: "起飞",
          data: {},
          deviceHardId: state.uav.deviceId,
        });
        data?.callback && data.callback(true);
      }, 3000);
    }
  },
  /**
   * 任务结束
   * @param {function} data.callback  //完成回调
   */
  async takeEnd({ state }, data) {
    console.log(state.airlineData, data);
    if (state.uav.network == 2) {
      try {
        // 结束航线指令
        window.$mmc.$store.dispatch("MMCMQTT/publish", {
          topic: "PX4/OBTAIN/" + state.uav.deviceId,
          data: {
            type: 525,
            data: null,
          },
          callback() {
            data?.callback && data.callback(true);
          },
        });
      } catch (e) {
        console.log("任务结束失败", e);
        data?.callback && data.callback(false);
      }
    } else {
      try {
        // //地面站链路
        window.$mmc.$store.dispatch("MMCGroundStation/order", {
          order: "结束平台任务",
          data: {
            cmdFunction: 2280,
            taskId: state.airlineData.id,
          },
          deviceHardId: state.uav.deviceId,
        });
      } catch (e) {
        console.log("任务结束失败", e);
        data?.callback && data.callback(false);
      }

      // //起飞指令
      // setTimeout(() => {
      //   window.$mmc.$store.dispatch("MMCGroundStation/order", {
      //     order: "起飞",
      //     data: {},
      //     deviceHardId: state.uav.deviceId,
      //   });
      //   data?.callback && data.callback(true);
      // }, 3000);
    }
  },
  /**
   * 安全降落
   * @param {*} param0
   * @param {*} data
   */
  land({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.原地降落,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc.$store.dispatch("MMCGroundStation/order", {
        order: "降落",
        data: {},
        deviceHardId: state.uav.deviceId,
      });
      data?.callback && data.callback(true);
    }
  },
  /**
   * 暂停飞行
   * @param {*} param0
   * @param {*} data
   */
  pauseFly({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.暂停航线任务,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc.$store.dispatch("MMCGroundStation/order", {
        order: "悬停",
        data: {},
        deviceHardId: state.uav.deviceId,
      });
      data?.callback && data.callback(true);
    }
  },
  /**
   * 继续飞行
   * @param {*} param0
   * @param {*} data
   */
  continueFly({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.继续航线任务,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc.$store.dispatch("MMCGroundStation/order", {
        order: "航线模式",
        data: {},
        deviceHardId: state.uav.deviceId,
      });
      data?.callback && data.callback(true);
    }
  },
  /**
   * 返航
   * @param {*} param0
   * @param {*} data
   */
  returnFlight({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.返航,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc.$store.dispatch("MMCGroundStation/order", {
        order: "返航",
        data: {},
        deviceHardId: state.uav.deviceId,
      });
      data?.callback && data.callback(true);
    }
  },
  /**
   * 航线控制
   * @param {*} param0
   * @param {*} data
   */
  routeControl({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.航线控制,
          data: {
            latitude: data.latitude,
            longitude: data.longitude,
            speed: data.speed,
          },
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      data?.callback && data.callback(false);
      throw "地面站链路不支持指点移动";
    }
  },

  /**
   * 手动模式
   */
  modeManual({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "POSITION",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      data?.callback && data.callback(true);
    }
  },
  /**
   * 自动模式
   */
  modeAuto({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "AUTO_MISSION",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      data?.callback && data.callback(true);
    }
  },
  /**
   * 挂载控制
   */
  mounteControl({ state }, data) {
    console.log(
      {
        type: 514,
        data: data,
      },
      "xxx"
    );
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: 514,
          data: data,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    }
  },
  /**
   * 摇杆控制
   */
  modeLAND({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "LAND",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
    }
  },
  /**
   * 发送指令申请内场摇杆控制权限，抢占无人机外场摇杆控制权限
   * @param {*} param0
   * @param {*} data
   */
  changeYGPermissions({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: 534,
          data: {
            cmd: 31021, //内场请求摇杆控制权限
            param1: 1, //数值等于1的时候，地面站请求抢占外场权限
            param2: 0,
            param3: 0,
            param4: 0,
            param5: 0,
            param6: 0,
            param7: 0,
          },
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
    }
  },
  /**
   * 返航模式
   */
  modeAUTO_RTL({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "AUTO_RTL",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
    }
  },
  /**
   * 航线模式
   */
  modeAUTO_MISSION({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "AUTO_MISSION",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
    }
  },

  /**
   * GPS/定点模式
   */
  modePOSITION({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "POSITION",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
    }
  },

  /**
   * 录制视频
   * @param {Object} data
   * @param {string} data.playerFormat  //播放格式, qingliu或其它
   * @param {boolean} data.recordControl //录制开头
   * @param {number} data.videoID //视频通道ID(需保持唯一)
   * @param {string} data.name  //挂载名称（如果知道挂载名称，将传名称即可，通道号可以不用传）
   * @param {number} data.taskID //任务ID，可传可不传
   * @param {number} data.dbID //历史记录id
   */
  videoTranscribe({ state }, data) {
    if (state.uav.network == 2) {
      const streamData = {
        data: {
          data: {
            taskID: data.taskID,
            videoID: 1,
            name: data.name,
            dbID: data.dbID,
          },
        },
        type: 528,
      };
      if (data.playerFormat.toLocaleLowerCase() == "qingliu") {
        streamData.data.messageID = 1017;
        streamData.data.data.status = data.recordControl;
      } else {
        streamData.data.messageID = 1006;
        streamData.data.data.recordControl = data.recordControl;
      }
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: streamData,
        callback() {
          data?.callback && data.callback(true);
        },
      });
    }
  },

  /**
   * 查询录制视频状态
   */
  videoTranscribeStatus({ state }, data) {
    if (state.uav.network == 2) {
      const streamData = {
        data: {
          data: {},
        },
        type: 528,
      };
      // if (streamSelect == "QingLiu") {
      streamData.data.messageID = 1031;
      // } else {
      //   streamData.data.messageID = 1006;
      //   streamData.data.data.recordControl = this.record;
      // }
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: streamData,
        callback() {
          data?.callback && data.callback(true);
        },
      });
    }
  },

  /**
   * 拍照指令
   * @param {Object} data
   * @param {string} data.playerFormat  //播放格式, qingliu或其它
   * @param {number} data.videoID //视频通道ID(需保持唯一)
   * @param {string} data.name  //挂载名称（如果知道挂载名称，将传名称即可，通道号可以不用传）
   * @param {number} data.taskID //任务ID，可传可不传
   * @param {number} data.dbID //历史记录id
   */
  takePhotos({ state }, data) {
    if (state.uav.network == 2) {
      const streamData = {
        data: {
          data: {
            taskID: data.taskID,
            videoID: 1,
            name: data.name,
            dbID: data.dbID,
          },
        },
        type: 528,
      };
      if (data.playerFormat.toLocaleLowerCase() == "qingliu") {
        streamData.data.messageID = 1016;
      } else {
        streamData.data.messageID = 1007;
      }
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: streamData,
        callback() {
          data?.callback && data.callback(true);
        },
      });
    }
  },

  /**
   * 挂载指令
   * @param {*} param0
   * @param {*} data.buffer 指令数据
   * @param {*} data.mountId 挂载的id
   */
  mountDirective({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc.$store.state.MMCMQTT.orders.云台控制指令can包透传,
          data: {
            mountId: data.mountId,
            payload: data.buffer,
          },
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      const buff = data.buffer.join(",");
      window.$mmc.$store.dispatch("MMCGroundStation/publish", {
        type: 200,
        cmdFunction: null,
        data: {
          cmdControlType: 7000,
          cmdState: null,
          cmdValue: null,
          cmdBuffer: buff,
          cmdName: state.selectMount.gimbalName,
        },
        deviceHardId: state.uav.deviceId,
      });
    }
  },
  /**
   * 判断是否已接管
   * @param { Number } data.id 无人机id
   */
  async isTakeOver({ state }, data) {
    let res = await Control_API.uavDetail({ id: data?.id || state.uav.id });
    if (
      res.data.currentOperator !==
      window.$mmc.$store.state.MMCFlightControlCenter.userInfo.id
    ) {
      return false;
    }
    return true;
  },
};

export default {
  namespaced: true,
  name: "uav",
  state,
  mutations,
  actions,
};

/**
 * 生成飞机坐标与姿态信息
 * @param {number} data.longitude
 * @param {number} data.latitude
 * @param {number} data.height 海拔
 * @param {number} data.yaw
 * @param {number} data.pitch
 * @param {number} data.roll
 * @returns {} position
 * @returns {} orientation
 */
function UAVDataParser(data) {
  const position = Cesium.Cartesian3.fromDegrees(
    Number(data.locationCoordinate3D.longitude),
    Number(data.locationCoordinate3D.latitude),
    Number(data?.gps?.absoluteAlt || 100)
  );
  const hpr = new Cesium.HeadingPitchRoll(
    Cesium.Math.toRadians((data?.attitude?.yaw || 0) + 90),
    Cesium.Math.toRadians(data?.attitude?.pitch || 0),
    Cesium.Math.toRadians(data?.attitude?.roll || 0)
  );
  const orientation = Cesium.Transforms.headingPitchRollQuaternion(
    position,
    hpr
  );
  return {
    position,
    orientation,
  };
}
