import uav from "./uav";
import hangar from "./hangar";
import { Control_API } from "../api";
import { Utils } from "../lib/cesium";

export default {
  namespaced: true,
  state: {
    devMode: false, //开发模式, 使用开发环境接口
    token: "", //登录token
    userInfo: null, //用户信息
    cesiumViewer: null, // cesium的viewer实例
    cesiumImagesLayers: {
      //cesium的地图图层
      street: {
        //街道影像
        show: false,
      },
      satellite: {
        //卫星影像
        show: false,
      },
      night: {
        //夜景影像
        show: false,
      },
      text: {
        // 地图标注
        show: false,
      },
    },
    cesium3DModels: [], //cesium的3D模型
    listCollapse: false, //无人机或机库列表是否折叠
    airwayEntities: [], //航线实体集合, 元素为new Cesium.EntityCollection()创建
    useSTLAirway: true, //是否使用标准航线库
    useTimedTask: false, //是否使用定时任务
  },
  mutations: {
    /**
     * 单纯的给state赋值
     * @param {*} param0
     * @param {*} data {key: '', value}
     */
    setState(state, data) {
      try {
        state[data.key] = data.value;
      } catch (e) {
        console.log("setDate err", e);
      }
    },
  },
  actions: {
    /**
     * 切换3D模型展示
     * @param {Object} param0
     * @param {Object} data
     * @param {Boolean} data.show 是否展示
     */
    switch3DModelsShow({ state }, data) {
      state.cesium3DModels.forEach((layer) => {
        layer.visible = data.show;
      });
    },
    /**
     * 判断是否已接管
     * @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 !== state.userInfo.id) {
        return false;
      }
      return true;
    },
    /**
     * 绘制航线距离文字标签
     * @param {*} param0
     * @param {object} data
     * @param {*} data.before 起点经纬度
     * @parma {*} data.after 终点经纬度
     */
    createDistanceLabel({ state }, data) {
      const { before, after } = data;
      const before_wgs84 = Utils.transformCartesian2WGS84(before);
      const after_wgs84 = Utils.transformCartesian2WGS84(after);

      const center_lng = (before_wgs84.lng + after_wgs84.lng) / 2;
      const center_lat = (before_wgs84.lat + after_wgs84.lat) / 2;
      const alt = (after_wgs84.alt + before_wgs84.alt) / 2;

      const position = Utils.transformWGS842Cartesian({
        lng: center_lng,
        lat: center_lat,
        alt: alt,
      });

      const text = `${Cesium.Cartesian3.distance(before, after).toFixed(2)} m`;

      let label_entity = state.cesiumViewer.entities.add({
        id: `label_${before}`,
        position: position,
        label: {
          text: text,
          scale: 0.5,
          font: "bold 30px Microsoft YaHei",
          fillColor: Cesium.Color.fromCssColorString("#fff"),
          horizontalOrigin: Cesium.VerticalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          showBackground: true,
          backgroundPadding: new Cesium.Cartesian2(10, 10),
        },
      });
      return label_entity;
    },
    /**
     * 清除航线
     * @param {*} param0
     * @param {object} data
     * @param {number} data.id
     */
    clearAirwayEntities({ state, commit }, data) {
      if (data?.id) {
        let find;
        // 过滤掉要清除的航线对象集合
        let list = state.airwayEntities.filter((item) => {
          if (item.airwayId === data.id) {
            find = item;
            return false;
          }
          return true;
        });
        if (find) {
          find.values.forEach((entity) => {
            state.cesiumViewer.entities.remove(entity);
          });
          find.removeAll();
        }
        commit("setState", {
          key: "airwayEntities",
          value: list,
        });
      } else {
        state.airwayEntities.forEach((item) => {
          item.values.forEach((entity) => {
            state.cesiumViewer.entities.remove(entity);
          });
          item.removeAll();
        });
      }
    },
    /**
     * 创建航线
     * @param {} param0
     * @param {Object} data
     * @param {number} data.id
     * @param {array} data.polyline 航线数据
     */
    createAirwayEntities({ state, dispatch }, data) {
      const { polyline } = data;
      let pointPositions = [];
      const label_arr = [];

      // 实体集合
      var entityCollection = new Cesium.EntityCollection();
      entityCollection.airwayId = data.id; // 由于id属性不允许更改，这里使用airwayId来使用

      polyline.forEach(async (item, index) => {
        item.longitude = Number(item.longitude);
        item.latitude = Number(item.latitude);
        item.alt = Number(item.alt);
        pointPositions.push(item.longitude, item.latitude, item.alt);
        label_arr.push(
          Cesium.Cartesian3.fromDegrees(item.longitude, item.latitude, item.alt)
        );
        let point_entity = state.cesiumViewer.entities.add({
          position: Cesium.Cartesian3.fromDegrees(
            item.longitude,
            item.latitude,
            item.alt
          ),
          name: "show_airline_point",
          point: {
            pixelSize: 20,
            color: Cesium.Color.RED,
            color: Cesium.Color.fromCssColorString("#1890FF"),
            // fillColor: Cesium.Color.RED,
            outlineWidth: 2,
            outlineColor: Cesium.Color.fromCssColorString("#FFF"),
            // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
          },
          label: {
            // text: String(item.altitude) + 'm',
            text: String(index + 1),
            scale: 0.5,

            font: "bold 24px Microsoft YaHei",
            // fillColor: Cesium.Color.BLUE,
            fillColor: Cesium.Color.fromCssColorString("#fff"),
            horizontalOrigin: Cesium.VerticalOrigin.CENTER,
            verticalOrigin: Cesium.VerticalOrigin.CENTER,
            disableDepthTestDistance: Number.POSITIVE_INFINITY,
            outlineWidth: 0,
            // showBackground: true,
            // backgroundColor: Cesium.Color.fromCssColorString("#1890FF")
            // pixelOffset: new Cesium.Cartesian2(25, -10),
            // backgroundPadding: new Cesium.Cartesian2(10, 10)
          },
        });
        entityCollection.add(point_entity);
        if (label_arr.length > 1) {
          const before = label_arr[label_arr.length - 2];
          const after = label_arr[label_arr.length - 1];
          let labelEntity = await dispatch("createDistanceLabel", {
            before,
            after,
          });
          entityCollection.add(labelEntity);
        }
      });

      pointPositions =
        Cesium.Cartesian3.fromDegreesArrayHeights(pointPositions);

      const redLine = state.cesiumViewer.entities.add({
        name: "Red line on terrain",
        polyline: {
          positions: new Cesium.CallbackProperty(() => {
            return pointPositions;
          }, false),
          width: 4,
          material: Cesium.Color.fromCssColorString("#1890FF"),
        },
      });
      entityCollection.add(redLine);
      state.cesiumViewer.flyTo(redLine);

      state.airwayEntities.push(entityCollection);
    },
  },
  getters: {
    //地面站websocket url
    wsUrl(state) {
      if (!state.devMode) {
        return "wss://tmj.mmcuav.cn/websocket";
      } else {
        return "wss://test.tmj.mmcuav.cn/websocket";
      }
    },
    //飞控中心mqtt url
    mqttUrl(state) {
      if (!state.devMode) {
        return "wss://fkzx.mmcuav.cn:8884/mqtt";
      } else {
        return "wss://test.fkzx.mmcuav.cn:8884/mqtt";
        // return "wss://fkzx.mmcuav.cn:8884/mqtt";
      }
    },
  },
  modules: {
    uav,
    hangar,
  },
};
