import moment from "moment";
import { Control_API, TaskInfo } from "../api";

function initHangarRealTimeData() {
  return {
    chargerPower: 0, //充电电源，0-未知，1-打开，2-关闭
    cover: 0, //舱盖，0-未知，1-关闭，2-打开，3-正在关闭,4-正在打开
    driverPower: 0, // 伺服电源，0-未知，1-打开，2-关闭
    folder: 0, // 回中器，0-未知，1-夹紧，2-放松，3-夹紧过程，4-放松过程
    hangarHumid: 0, // 停机坪内湿度，单位：%
    hangarMode: 0, // 停机坪模式，0-未知，1-正常模式，2-休眠模式
    hangarPower: 0, // 停机坪电源，0-未知，1-打开，2-关闭
    hangarTemp: 0, // 停机坪内温度,单位：度
    inLamp: 0, // 内部灯，0-未知，1-打开，2-关闭
    lifts: 0, // 起降台，0-未知，1-降下，2-升起，3-降下过程，4-升起过程
    outCameraPower: 0, // 外置摄像头电源，0-未知，1-打开，2-关闭
    outLamp: 0, // 外部灯，0-未知，1-打开，2-关闭
    processStatus: 0, // 0-空闲 、1-正在执行出仓待命、2-正在执行回收入仓、3-正在执行充电流程 、4-正在结束充电流程、5-正在执行休眠流程、6-正在执行预热流程、7-正在执行初始化、8-未初始化 、9-正在执行关舱流程 、10-正在执行回中器操作、99-正在执行飞行任务
    remotePower: 0, // 遥控电源，0-未知，1-打开，2-关闭
    rfPower: 0, // 射频电源，0-未知，1-打开，2-关闭
    rtkPower: 0, // RTK 基站电源，0-未知，1-打开，2-关闭
    videoPower: 0, // 机载视频电源，0-未知，1-打开，2-关闭
    waterWarn: 0, // 水浸报警，0-未知，1-报警，2-正常
    msg: {
      // 2063 飞控应答消息
      number: 0, // 包序列号
      text: "", // 文本内容
      type: 1, // 系统消息数据：2063
    },
    msgList: [], //飞控应答消息记录
    weatherStation: {
      // 2066 气象站数据
      rain: 0, // 雨量，0-无雨，1-有雨
      homeLat: 0, // 停机坪纬度，单位 deg
      homeLon: 0, // 停机坪经度，单位 deg
      humidity: 0, // 湿度，单位：%
      light: 0, // 光照，单位：lux
      number: 0, // 包序列号
      homesatellite: 0, // 停机坪卫星数
      temp: 0, // 温度，单位：C
      weatherHumid: 0, // 气象站湿度，单位：%
      weatherTemp: 0, // 气象站温度，单位：度
      windDirection: 0, // 风向，单位：deg
      windSpeed: 0, // 风速，单位 m/s
    },
  };
}

const state = {
  hangar: null, // 选择中的机库信息
  showPanel: false, //显示数据面板
  hangarRealTimeData: initHangarRealTimeData(), // 实时数据
  airlineData: null, //航线数据
};

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 = {
  // 通过mqtt更新实时采集数据
  updateByMQTT({ commit, state, dispatch }, data) {
    // mqtt链路
    const type2065 = data[2065]?.data || {};
    const type2063 = data[2063]?.data; //飞控应答消息
    const type3 = data[3]; //机库流程日志
    const type2066 = data[2066]?.data || {}; //气象站数据

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

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

    commit("setState", {
      key: "hangarRealTimeData",
      value: {
        ...state.hangarRealTimeData,
        ...type2065,
        msg: type2063,
        msgList,
        weatherStation: type2066,
      },
    });
  },
  /**
   * 订阅机库数据
   * @param {*} param0
   * @param {object} data
   */
  subscribe({ state, dispatch }) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/subscribe", {
      topic: "APRON/RECEIVE/" + state.hangar.deviceId,
      callback(ok) {
        ok &&
          console.log("mqtt订阅主题", "APRON/RECEIVE/" + state.hangar.deviceId);
      },
    });
    window.$mmc_stl.$store.dispatch("MMCMQTT/subscribe", {
      topic: "PROCESS/RECEIVE/" + state.hangar.deviceId,
      callback(ok) {
        ok &&
          console.log(
            "mqtt订阅主题",
            "PROCESS/RECEIVE/" + state.hangar.deviceId
          );
      },
    });
  },
  /**
   * 取消订阅
   * @param {} param0
   */
  unsubscribe({ state, dispatch }) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/unsubscribe", {
      topic: "APRON/RECEIVE/" + state.hangar.deviceId,
      callback(ok) {
        ok &&
          console.log(
            "mqtt取消订阅主题",
            "APRON/RECEIVE/" + state.hangar.deviceId
          );
      },
    });
    window.$mmc_stl.$store.dispatch("MMCMQTT/unsubscribe", {
      topic: "PROCESS/RECEIVE/" + state.hangar.deviceId,
      callback(ok) {
        ok &&
          console.log(
            "mqtt取消订阅主题",
            "PROCESS/RECEIVE/" + state.hangar.deviceId
          );
      },
    });

    dispatch("destroy");
  },
  /**
   * 销毁机库相关对象
   * @param {} param0
   * @param {*} data
   */
  destroy({ commit, state, dispatch }, data) {
    commit("setState", { key: "hangar", value: null });
    commit("setState", {
      key: "hangarRealTimeData",
      value: initHangarRealTimeData(),
    });
  },
  /**
   * 出库
   * @param {*} param0
   * @param {*} data
   * @param {Function} data.callback
   */
  out({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 2059,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 入库
   * @param {*} param0
   * @param {*} data
   */
  in({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 2073,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 开始充电
   * @param {*} param0
   * @param {*} data
   */
  chargeStart({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 2060,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 结束充电
   * @param {*} param0
   * @param {*} data
   */
  chargeEnd({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 2071,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 预热
   * @param {*} param0
   * @param {*} data
   */
  warmUp({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 2072,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 休眠
   * @param {*} param0
   * @param {*} data
   */
  dormancy({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 2061,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 退出流程
   * @param {*} param0
   * @param {*} data
   */
  processExit({ state, commit, dispatch }, data) {
    window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
      topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
      data: {
        cmdControlType: 100001,
      },
      callback() {
        data?.callback && data.callback();
      },
    });
  },
  /**
   * 一键起飞
   * @param {function} data.callback  //完成回调
   */
  async takeOff({ state }, data) {
    console.log(state.airlineData, data, '1111');
    try {
      // 生成架次号
      const flightSortieId = await TaskInfo.flightSortieId({
        device_id: state.hangar.uav.deviceId,
        reouteId: state.airlineData.id,
        taskInfoId: data.taskInfoId,
      });
      /*  const flightSortieId = {
        data: `tmj-v4-${Date.now()}`
      } */
      // 上传航线指令
      const waypointList = state.airlineData?.content;
      window.$mmc_stl.$store.dispatch("MMCMQTT/publish", {
        topic: "PROCESS/OBTAIN/" + state.hangar.deviceId,
        data: {
          cmdControlType: 100004,
          uavDeviceId: state.hangar.uav.deviceId, //无人机id
          wayLineObj: {
            taskId: state.airlineData.id,
            flightSortiesID: flightSortieId.data,
            waypointList: waypointList,
            autoFlightSpeed: state.airlineData.baseSpeed || 6,
            finishedAction: "GO_HOME",
            headingMode: "AUTO",
            isExitMissionOnRCSignalLostEnabled: true,
            maxFlightSpeed: 12,
          },
        },
        callback() { },
      });
    } catch (e) {
      console.log("一键起飞失败", e);
      data?.callback && data.callback(false);
    }
  },
  /**
   * 判断是否已接管
   * @param { Number } data.id 无人机id
   */
  async isTakeOver({ state }, data) {
    let device = data || state.hangar;
    let res = await Control_API.getDeviceDetail({
      id: device.id,
    });
    if (
      res.data.currentOperator &&
      res.data.currentOperator ===
      window.$mmc_stl.$store.state.MMCFlightControlCenter.userInfo.id
    ) {
      return true;
    }
    return false;
  },
};

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