import { Control_API, TaskInfo } 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);
    console.log('飞行轨迹', positions);
  }
}, 60000);
if (!window.$mmc_stl) {
  window.$mmc_stl = {};
}
window.$mmc_stl.positions = () => {
  console.log(positions);
}
const defaultPos = {
  latitude: 0, // 纬度
  longitude: 0, // 经度
};

function initUavRealTimeData() {
  return {
    isFlying: false, // true 飞机处于飞行中，电动机解锁后，飞机就处于飞行中
    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: [], // 飞控应答消息记录
    signal: null, //基站信号值
    /* {  
    sqe14	1.4G基站信号质量，详见如下RSRP表	1.4G信号质量，详见如下RSRP-1.4G(dBm)
    sqe45	4/5G基站信号质量，详见如下RSRP表	5G信号质量，详见如下RSRP-45G(dBm)
    type45	公网信号值类型	5G信号类型，"4G"、"5G"
    signal14	1.4G基站信号信息	List<Map<String,String>>
    signal45	4/5G基站信号信息	List<Map<String,String>>
    up14Link	1.4G上行速率，单位字节/秒	Long
    down14Link	1.4G下行速率。单位字节/秒	Long
    up45Link	4/5G上行速率，单位字节/秒	Long
    down45Link	4/5G下行速率，单位字节/秒	Long
  } */
    flightMode: "UNKNOWN",
    uploadAirline: {
      //上传的航线
      finishedAction: "", //航点任务完成后，飞机将采取的行动
      headingMode: "", //飞机在航点之间移动时的航向模式
      isExitMissionOnRCSignalLostEnabled: Boolean, //飞机在航点之间移动时的航向模式
      maxFlightSpeed: 0, //航线飞行最大速度，px4无人机默认最大12m
      autoFlightSpeed: 0, //航线飞行速度默认5m
      waypointList: null,
    },
    airlineProgress: {
      action: "NON", //执行的动作，NON表示飞到航点位置
      actionIndex: 1, //航点动作执行索引
      isFinish: true, //true航线任务执行完成，false未完成
      isFinishAction: true, //航点执行完成，true执行完成，false为执行完成
      progress: 0, //航线任务执行进度
      totalWaypointCount: 0, //航线任务总进度
      waypointIndex: 1, //执行航点索引值，从1开始
    },
  };
}

const state = {
  openTest: false, // 开启测试
  uav: null, // 选择中的无人机信息
  uavRealTimeData: initUavRealTimeData(),
  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, // 选中的挂载,payload数据是固定的,不会实时更新,实时更新使用selectMountPayload
  showPlayer: false, //显示播放器
  showPanel: false, //显示数据面板
  isQingLiu: null, // 当前视频播放的是否为清流
  waitAirlineUpload: false, //是否正在等待航线上传
};

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_stl.viewer.entities.remove(state.airlineEntity);
    window.$mmc_stl.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: initUavRealTimeData(),
    });

    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; // 飞控应答消息
      const type260 = data[260]?.data; // 无人机提示信息
      const type261 = data[261]?.data; // 航线上传完成信息
      const type265 = data[265]?.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({
            grade: "AUTO",
            text: type270.text,
            time: moment(type270.timestamp).format("YYYY-MM-DD HH:mm:ss"),
            timestamp: type270.timestamp,
          });
        }
      }
      if (type260) {
        type260.timestamp = data[260].timestamp;
        let findMsg = msgList.find(
          (item) => item.timestamp === type260.timestamp
        );
        if (!findMsg) {
          msgList.push({
            grade:
              type260.grade <= 2
                ? "[危险]"
                : type260.grade == 3
                ? "[错误]"
                : type260.grade == 4
                ? "[警告]"
                : type260.grade == 5
                ? "[通知]"
                : type260.grade == 6
                ? "[正常]"
                : type260.grade == 7
                ? "[调试]"
                : "AUTO",
            text: type260.msg,
            time: moment(type260.timestamp).format("YYYY-MM-DD HH:mm:ss"),
            timestamp: type260.timestamp,
          });
        }
      }

      // 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,
          ...type268,
          ...type2006,
          ...type2017,
          ...type258,
          obstacle: type272 || state.uavRealTimeData.obstacle,
          healthData: type275 || state.uavRealTimeData.healthData,
          batteryList,
          msg: type270,
          msgList,
          uploadAirline: type261,
          airlineProgress: type265,
        },
      });

      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 {
          // 更新挂载数据
          let mountList = state.mountList.map((item) => {
            if (item.mountId === type259.mountId) {
              return {
                ...item,
                ...type259
              };
            }
            return item;
          });
          commit("setState", { key: "mountList", value: 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的对象,原因未知
        // 更新轨迹
        let flag = positions.some(val=> val.x == UAVDataParser(state.uavRealTimeData).position.x && val.y == UAVDataParser(state.uavRealTimeData).position.y)
        if (!flag) {
          positions.push(UAVDataParser(state.uavRealTimeData).position);
        }
        // console.log(positions,"positions.x");
      }

      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 === 2) {
      window.$mmc_stl.$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_stl.$store.state.MMCFlightControlCenter.userInfo.userName;
        const token = window.$mmc_stl.$store.state.MMCFlightControlCenter.token;
        window.$mmc_stl.$store
          .dispatch("MMCGroundStation/init", {
            url: window.$mmc_stl.$store.state.MMCFlightControlCenter.wsUrl,
            userInfo: {
              type: 100,
              systemCode: "mmc",
              state: 1,
              username,
              token,
              appId: "40003",
            },
            loginCallback() {
              // 订阅取数据不一定有用, ws的订阅需要后端做了处理才生效, 未处理则会收到所有无人机的数据, 负担非常大
              window.$mmc_stl.$store.dispatch(
                "MMCGroundStation/subscribe",
                state.uav.deviceId
              );
            },
          })
          .then(() => {
            console.log("地面站连接成功");
          });
      } catch (e) {
        console.log("地面站连接失败", e);
      }
    }
  },
  /**
   * 取消订阅
   * @param {} param0
   */
  unsubscribe({ state, dispatch }) {
    if (state.uav.network === 2) {
      window.$mmc_stl.$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_stl.$store.dispatch(
        "MMCGroundStation/unsubscribe",
        state.uav.deviceId
      );
      window.$mmc_stl.$store.dispatch("MMCGroundStation/end");
    }

    dispatch("destroy");
  },
  /**
   * 断开ws连接
   * @param {*} param0
   */
  end({ state, dispatch }) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/end");
    window.$mmc_stl.$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_stl.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_stl.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_stl.viewer.flyTo(state.uavModelEntity, {
        offset: new Cesium.HeadingPitchRange(
          0,
          -Cesium.Math.PI_OVER_TWO,
          10000
        ),
      });
    }
  },

  /**
   * 一键起飞
   * @param {function} data.callback  //完成回调
   * @param {object} data.taskInfoId //任务id
   */
  async takeOff({ state, commit }, data) {
    console.log(state.airlineData, data);
    if (state.uav.network == 2) {
      try {
        let flightSortieId;
        if(data.taskInfoId){
          flightSortieId = await TaskInfo.createTaskRecord({
            taskInfoId: data.taskInfoId || undefined,
            deviceId: state.uav.deviceId,
            reouteId: state.airlineData.id,
          })
        } else {
          // 生成架次号
          flightSortieId = await TaskInfo.flightSortieId({
            device_id: state.uav.deviceId,
            reouteId: state.airlineData.id,
          });
        }
        
        /*  const flightSortieId = {
          data: `tmj-v4-${Date.now()}`
        } */
        // 上传航线指令
        const waypointList = state.airlineData?.content;
        window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
          topic: "PX4/OBTAIN/" + state.uav.deviceId,
          data: {
            type: window.$mmc_stl.$store.state.MMCMQTT.orders.航线上传,
            data: {
              taskId: state.airlineData.id,
              flightSortiesID: flightSortieId.data,
              waypointList: waypointList,
              autoFlightSpeed: state.airlineData.baseSpeed || 6,
              finishedAction: "GO_HOME",
              headingMode: "AUTO",
              isExitMissionOnRCSignalLostEnabled: true,
              maxFlightSpeed: 12,
            },
          },
          callback() {},
        });

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

        // 起飞指令
        commit("setState", {
          key: "waitAirlineUpload",
          value: true,
        });
        let time = setInterval(() => {
          if (state.uavRealTimeData.uploadAirline) {
            clearInterval(time);
            window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
              topic: "PX4/OBTAIN/" + state.uav.deviceId,
              data: {
                type: window.$mmc_stl.$store.state.MMCMQTT.orders.航线一键起飞,
                data: {
                  taskId: state.airlineData.id,
                  seq: 0,
                },
              },
              callback() {
                data?.callback && data.callback(true, flightSortieId.data);
              },
            });
            // 清空261数据
            let dataSet = window.$mmc_stl.$store.state.MMCMQTT.dataSet;
            dataSet[state.uav.deviceId][261] = null;

            window.$mmc_stl.$store.commit("MMCMQTT/setSate", {
              key: "dataSet",
              value: dataSet,
            });
            commit("setState", {
              key: "uavRealTimeData",
              value: {
                ...state.uavRealTimeData,
                uploadAirline: null,
              },
            });
          }
        }, 1000);

        // 做个保险, 要是因为各种原因导致没飞起, 超过一分钟删除循环定时器
        setTimeout(() => {
          clearInterval(time);
        }, 60000);
      } catch (e) {
        console.log("一键起飞失败", e);
        data?.callback && data.callback(false);
      }
    } else {
      // 地面站链路
      window.$mmc_stl.$store.dispatch("MMCGroundStation/order", {
        order: "航线上传",
        data: {
          cmdValue: state.airlineData?.id,
        },
        deviceHardId: state.uav.deviceId,
      });

      // 起飞指令
      setTimeout(() => {
        window.$mmc_stl.$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_stl.$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_stl.$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_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$store.state.MMCMQTT.orders.原地降落,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$store.state.MMCMQTT.orders.暂停航线任务,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$store.state.MMCMQTT.orders.继续航线任务,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$store.state.MMCMQTT.orders.返航,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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 "地面站链路不支持指点移动";
    }
  },
  /**
   * 模式切换
   * @param {*} param0
   * @param {object} data
   * @param {number} data.id 模式id
   * @param {function} data.callback
   */
  modeChange({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$store.state.MMCMQTT.orders.无人机模式切换,
          data: data.id,
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      data?.callback && data.callback(true);
    }
  },
  /**
   * 手动模式
   */
  modeManual({ state }, data) {
    if (state.uav.network == 2) {
      window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$store.state.MMCMQTT.orders.无人机模式切换,
          data: "AUTO_MISSION",
        },
        callback() {
          data?.callback && data.callback(true);
        },
      });
    } else {
      // 地面站链路
      data?.callback && data.callback(true);
    }
  },
  /**
   * 挂载控制
   */
  mountControl({ state }, data) {
    console.log(
      {
        type: 514,
        data: data,
      },
      "xxx"
    );
    if (state.uav.network == 2) {
      window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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,
      };
      let isQingLiu = state.isQingLiu;
      if (data.isQingLiu !== undefined) {
        isQingLiu = data.isQingLiu;
      }
      if (isQingLiu) {
        streamData.data.messageID = 1017;
        streamData.data.data.status = data.recordControl;
      } else {
        streamData.data.messageID = 1006;
        streamData.data.data.recordControl = data.recordControl;
      }
      window.$mmc_stl.$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_stl.$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,
      };
      let isQingLiu = state.isQingLiu;
      if (data.isQingLiu !== undefined) {
        isQingLiu = data.isQingLiu;
      }
      if (isQingLiu) {
        streamData.data.messageID = 1016;
      } else {
        streamData.data.messageID = 1007;
      }
      window.$mmc_stl.$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_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: window.$mmc_stl.$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_stl.$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.getDeviceDetail({
      id: data?.id || state.uav.id,
    });
    if (
      res.data.currentOperator &&
      res.data.currentOperator ===
        window.$mmc_stl.$store.state.MMCFlightControlCenter.userInfo.id
    ) {
      return true;
    }
    return false;
  },
  /**
   * 网络切换
   * @param {*} param0
   * @param {*} data 网络类型 0自动切换，1图传、2专网，3公网
   */
  networkChange({ state }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PX4/OBTAIN/" + state.uav.deviceId,
      data: {
        type: window.$mmc_stl.$store.state.MMCMQTT.orders.链路切换,
        data,
      },
      callback() {},
    });
  },
  // 键盘控制
  keyControl({ state }, data) {
    console.log(data, "键盘控制");
    if (state.uav.network == 2) {
      window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PX4/OBTAIN/" + state.uav.deviceId,
        data: {
          type: 538,
          data: data,
        },
        callback() {
          data.callback && data.callback(true);
        },
      });
    }
  },
};

const getters = {
  /**
   * 选中挂载的实时数据
   */
  selectMountPayload(state) {
    if (state.selectMount) {
      let find = state.mountList.find(
        (item) => item.mountId === state.selectMount.mountId
      );
      if (find) {
        return find.payload;
      } else {
        throw Error("选中的挂载不在挂载列表中!");
      }
    } else {
      return null;
    }
  },
};

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

/**
 * 生成飞机坐标与姿态信息
 * @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,
  };
}
