<template>
  <div class="taskListBox">
    <div class="header">
      <div class="title">
        <img src="../../assets/images/mount_head.png" />
        <div class="font">任务库</div>
      </div>
    </div>
    <el-form class="task-main" label-width="60px">
      <el-form-item label="任务库">
        <el-cascader
          filterable
          popper-class="mmc"
          size="mini"
          class
          style="width: 100%"
          v-model="selectedTaskId"
          :options="taskListAll"
          clearable
          :show-all-levels="false"
          placeholder="请选择任务"
          :props="{
              children: 'children',
              label: 'name',
              value: 'id',
            }"
          @change="onChangeTask"
        >
          <template slot-scope="{ data }">
            <el-tooltip class="item" effect="dark" :content="data.name" placement="top-start">
              <span>{{ data.name }}</span>
            </el-tooltip>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="航线">
        <el-tooltip content="航线名称" placement="top">
          <el-input
            v-if="isSelectTask || selectedAirway.id !== -1"
            disabled
            v-model="selectedAirway.name"
            placeholder="请选择航线"
            class
            style="width: 100%"
            size="mini"
          ></el-input>
          <el-button v-else class="select-airway__btn" @click="showFlywayDialog = true">选择航线</el-button>
        </el-tooltip>
      </el-form-item>
      <div class="btn" @click="onStartTask">一键任务</div>
      <!-- <div class>
        <span class="btn__add-line">
          <span class="f8"></span> 创建航线
        </span>
      </div>-->
    </el-form>
    <LineList v-if="showFlywayDialog" @close="showFlywayDialog = false;" @change="onChangeLine"></LineList>
  </div>
</template>
<script>
import LineList from "./components/lineList";
import { Utils } from "../../../../../../../../lib/cesium";
import { mapState, mapActions } from "vuex";

const airwayEntities = []; // 航线实体
let point_entity = null;

export default {
  name: "taskList",
  components: { LineList },
  props: {},
  inject: ["rootNode", "bus"],
  data() {
    return {
      // 选择的任务id
      selectedTaskId: [],
      // 航线数据
      flightList: [],
      // 选择的航线
      selectedAirway: {
        name: "",
        id: -1,
      },
      // 航线选择窗口
      showFlywayDialog: false,
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", ["cesiumViewer"]),
    ...mapState("MMCFlightControlCenter/uav", ["taskList", "uav"]),
    taskListAll() {
      return [{ name: "选择航线自动生成任务", id: -1 }, ...this.taskList];
    },
    /**
     * 是否选择任务
     */
    isSelectTask() {
      return this.selectedTaskId[0] !== -1;
    },
    /**
     * 选择的任务数据
     */
    selectedTask() {
      let find = this.taskList.find((item) => {
        return item.id === this.selectedTaskId[this.selectedTaskId.length - 1];
      });
      return find;
    },
  },
  watch: {
    selectedAirway() {
      this.clearAirwayEntities();
      if (this.selectedAirway.id !== -1) {
        try {
          this.createAirwayEntities(JSON.parse(this.selectedAirway.content));
        } catch (e) {
          console.log("绘制航线失败", e);
        }
      }
    },
  },
  async created() {
    this.bus.$on("startTask", this.onStartTask);
  },
  beforeDestroy() {
    this.clearAirwayEntities();
  },
  methods: {
    ...mapActions("MMCFlightControlCenter/uav", ["isTakeOver"]),
    /**
     * 更改航线事件
     */
    onChangeLine(data) {
      this.selectedAirway = data;
    },
    /**
     * 一键任务事件
     */
    async onStartTask() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning("请先接管无人机");
        return;
      }

      // 判断是否选择了航线
      if (this.selectedAirway.id === -1) {
        this.$message.warning("请选择航线");
        return;
      }
      try {
        await this.$confirm("请确认是否进行一键任务操作?", "安全确认", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          customClass: "uav_controlPane",
          showClose: false,
        });
        this.$store.commit("MMCFlightControlCenter/uav/setState", {
          key: "airlineData",
          value: this.selectedAirway,
        });
        this.$store.dispatch("MMCFlightControlCenter/uav/takeOff", {
          callback(status) {
            if (status) {
              this.$message.success("一键任务指令发送成功");
            } else {
              this.$message.error("一键任务指令发送失败");
            }
          },
        });
        this.rootNode.$emit(
          "uavStartTask",
          this.uav,
          this.selectedTask,
          this.selectedAirway
        );
      } catch (e) {}
    },
    /**
     * 更改任务事件
     */
    onChangeTask() {
      this.selectedAirway = this.selectedTask?.airway || {
        name: "",
        id: -1,
      };
    },
    // 两点距离
    create_label(before, after) {
      const before_wgs84 = Utils.transformCartesian2WGS84(before);
      const after_wgs84 = Utils.transformCartesian2WGS84(after);

      const center_lng = (before_wgs84.lng + after_wgs84.lng) / 2;
      const cetner_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: cetner_lat,
        alt: alt,
      });

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

      let label_entity = this.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),
        },
      });
      airwayEntities.push(label_entity);
    },
    // 清除航线
    clearAirwayEntities() {
      airwayEntities.forEach((item) => {
        this.cesiumViewer.entities.remove(item);
      });
    },
    createAirwayEntities(polyline) {
      let pointPositions = [];
      const label_arr = [];
      polyline.content.forEach((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)
        );
        point_entity = this.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)
          },
          id: JSON.stringify({
            ...item,
            type: "flight_point",
            index: index,
          }),
        });
        airwayEntities.push(point_entity);
        if (label_arr.length > 1 && !this.isEditting) {
          const before = label_arr[label_arr.length - 2];
          const after = label_arr[label_arr.length - 1];
          this.create_label(before, after);
        }
      });

      pointPositions =
        Cesium.Cartesian3.fromDegreesArrayHeights(pointPositions);

      const redLine = this.cesiumViewer.entities.add({
        name: "Red line on terrain",
        polyline: {
          positions: new Cesium.CallbackProperty(() => {
            return pointPositions;
          }, false),
          width: 4,
          // clampToGround: true,
          // zIndex: -99,
          material: Cesium.Color.fromCssColorString("#1890FF"),
          // material: ({
          //   // material: Cesium.Color.fromCssColorString('#1890FF'),
          //   color: Cesium.Color.RED,
          //   outlineWidth: 2,
          //   outlineColor: Cesium.Color.fromCssColorString('#FFF')
          // })
          // // clampToGround: true,
          // material: new Cesium.PolylineOutlineMaterialProperty({
          //   color: Cesium.Color.fromCssColorString('#1890FF'),

          //   // outlineWidth: 2,
          //   // outlineColor: Cesium.Color.fromCssColorString('#FFF'),
          // }),
        },
      });
      this.cesiumViewer.flyTo(redLine);
      airwayEntities.push(redLine);
    },
  },
};
</script>
<style lang="scss" scoped>
.taskListBox {
  min-height: 254px;
  width: 380px;
  background: rgba(9, 32, 87, 0.7);
  border-radius: 10px;
  transition: 0.3s;

  .header {
    display: flex;
    justify-content: space-between;
    height: 32px;
    background: linear-gradient(
      180deg,
      #9198ff 0%,
      rgba(45, 81, 153, 0.45) 40%,
      #05091a 100%
    );
    box-shadow: inset 0px 0px 10px 2px #3f9dff;
    border-radius: 10px 10px 0px 0px;
    border: 1px solid #427dff;
    .title {
      display: flex;
      align-items: center;
      margin-left: 10px;
      .font {
        font-size: 20px;
        font-family: YouSheBiaoTiHei;
        color: #14faff;
        line-height: 26px;
        text-shadow: 0px 1px 1px rgba(2, 32, 56, 0.2);
        background: linear-gradient(
          135deg,
          #e3aa77 0%,
          #f5cda9 38%,
          #f9ecd3 58%,
          #fcdbb1 79%,
          #edb07a 100%
        );
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
      }
    }
    .active {
      background-image: linear-gradient(
        180deg,
        #9198ff 0%,
        rgba(45, 81, 153, 0.22) 40%,
        #05091a 100%
      );
      border: 1px solid #70daf9;
      box-shadow: inset 0 0 10px 2px #3f9dff;
      font-family: MicrosoftYaHei-Bold;
      font-size: 14px;
      color: #70daf9;
      letter-spacing: 0;
      font-weight: 700;
    }

    .default {
      background-image: linear-gradient(
        180deg,
        #9198ff 0%,
        rgba(45, 81, 153, 0.22) 40%,
        #05091a 100%
      );
      border: 1px solid #70daf9;
      font-family: MicrosoftYaHei-Bold;
      font-size: 14px;
      color: rgba(112, 218, 249, 0.5);
      letter-spacing: 0;
      font-weight: 700;
    }
  }
  .task-main::v-deep {
    padding: 38px 30px;
    position: relative;

    .el-form-item__label {
      color: #fff;
    }

    .btn__add-line {
      position: absolute;
      bottom: 20px;
      right: 20px;
      font-size: 10px;
      color: #43deff;
      cursor: pointer;
    }
  }

  .btn {
    width: 122px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    margin: 0 auto;
    margin-bottom: 10px;
    color: #fff;
    background: url("../../assets/images/btn_lan.png") no-repeat;
    background-size: 100% 100%;
    cursor: pointer;
  }
}
.select-airway__btn {
  width: 100%;
  height: 30px;
  padding: 0;
}
</style>
