<template>
  <div class="taskListBox">
    <el-form class="task-main" label-width="120px">
      <el-form-item :label="$t('common.任务库') + '：'" v-if="useTask">
        <el-select v-model="selectedTaskId" clearable>
          <el-option v-for="(item, i) in taskList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('common.航线') + '：'">
        <el-select v-model="selectedAirwayId">
          <el-option v-for="(item, i) in airwayList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <div class="btn" @click="onStartTask" v-hover>{{ $t('common.一键任务') }}</div>
    <div class>
      <span class="btn__add-line" @click="showAirwayEdit = true">
        <i class="el-icon-circle-plus-outline"></i>
        <span class="f8"></span> {{ $t('common.创建航线') }}
      </span>
    </div>
    <AirwayEdit v-if="showAirwayEdit" @close="showAirwayEdit = false" @addDone="getAirwayList"></AirwayEdit>
  </div>
</template>
<script>
import { Utils } from "../../../../../../../../../../lib/cesium";
import { mapState, mapActions } from "vuex";
import { Control_API, TaskInfo } from "../../../../../../../../../../api";
import AirwayEdit from "./components/airwayEdit";

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

export default {
  name: "taskList",
  components: { AirwayEdit },
  props: {},
  inject: ["rootNode", "bus"],
  data() {
    return {
      airwayList: [], //航线列表
      selectedAirwayId: "", // 选择的航线
      taskList: [], //任务列表
      selectedTaskId: "", //选择的任务
      airwaySelectDisabled: false, //选择任务后, 禁用航线选择
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter", [
      "cesiumViewer",
      "useSTLAirway",
      "useTask",
    ]),
    ...mapState("MMCFlightControlCenter/uav", ["uav", "uavRealTimeData"]),
    ...mapState("MMCFlightControlCenter/hangar", ["hangar"]),
    // 选择的任务
    selectedTask() {
      let find = this.taskList.find((item) => {
        return item.id == this.selectedTaskId;
      });
      if (find) {
        return find;
      } else {
        return {
          name: "",
          id: -1,
        };
      }
    },
    showAirwayEdit: {
      get() {
        return this.$store.state.MMCFlightControlCenter.showAirwayEdit;
      },
      set(value) {
        this.$store.commit("MMCFlightControlCenter/setState", {
          key: "showAirwayEdit",
          value,
        });
      },
    },
    // 选择的航线
    selectedAirway() {
      let find = this.airwayList.find((item) => {
        return item.id == this.selectedAirwayId;
      });
      if (find) {
        return find;
      } else {
        return {
          name: "",
          id: -1,
        };
      }
    },
  },
  watch: {
    'uavRealTimeData.isFlying': {
      handler: function (newVal,oldVal) {
      if (oldVal === false && newVal === true) {
          this.getTaskInfoRecord()
        }
      },
      deep: true,
      immediate: true,

    },
    selectedTask() {
      if (this.selectedTask.id !== -1) {
        this.airwaySelectDisabled = true;
      } else {
        this.airwaySelectDisabled = false;
      }
      // 任务改变则修改航线选择为任务中的航线
      this.selectedAirwayId = this.selectedTask?.airwayId;
    },
    selectedAirway() {
      this.clearAirwayEntities();
      if (this.selectedAirway.id !== -1) {
        try {
          let airway = this.selectedAirway.content;
          this.createAirwayEntities({
            polyline: airway,
            id: airway.id,
          });
        } catch (e) {
          console.log("绘制航线失败", e);
        }
      } else {
        if (this.selectedTaskId && this.selectedAirwayId == "") {
          this.$message.warning(this.$t('common.未找到相应的航线'));
        }
        this.selectedAirwayId = "";
        this.airwaySelectDisabled = false;
      }
    },
  },
  async created() {
    this.bus.$on("startTask", this.onStartTask);
    await this.getTaskList();
    await this.getAirwayList();
    if(this.uavRealTimeData.isFlying){
      this.getTaskInfoRecord()
    }

  },
  beforeDestroy() {
    this.showAirwayEdit = false;
    this.bus.$off("startTask", this.onStartTask);
    this.clearAirwayEntities();
  },
  methods: {
    ...mapActions("MMCFlightControlCenter", [
      "createAirwayEntities",
      "clearAirwayEntities",
      "apiPointsToFKZXPoints",
    ]),
    ...mapActions("MMCFlightControlCenter/hangar", ["isTakeOver"]),
    async getTaskInfoRecord() {
      let res = await TaskInfo.getTaskInfoRecord({
        deviceId: this.uav && this.uav.deviceId,
      });
      if (res.code === 0) {
        console.log("getTaskInfoRecord", res.data);
        this.selectedTaskId = res.data.taskInfoId;  
       setTimeout(() => {
        this.selectedAirwayId = res.data.reouteId;
       },1000)
      }
    },
    /**
     * 获取任务列表
     */
    getTaskList(id) {
      return new Promise((resolve) => {
        this.rootNode.$emit("taskListGet", {
          pageNo: 1,
          pageSize: 100,
          type: 0,
          putDevice: 2,
          // isHangar: true,
          hangar: this.hangar,
          // taskStatus: 1,
          callback: (res) => {
            this.taskList =res?.records.filter(item => item.status != "已完成");
            this.$nextTick(() => {
              if (id) {
                this.selectedTaskId = id;
              }
              resolve();
            });
          },
        });
      });
    },
    /**
     * 获取航线列表
     */
    getAirwayList(id) {
      return new Promise((resolve) => {
        console.log("getAirwayList", this.taskListAll);
        this.rootNode.$emit("airwayListGet", {
          pageNo: 1,
          pageSize: 100,
          hangar: this.hangar,
          callback: (res) => {
            this.airwayList = res?.records || [];
            this.$nextTick(() => {
              if (id) {
                this.selectedAirwayId = id;
              }
              resolve();
            });
          },
        });
      });
    },
    /**
     * 一键任务事件
     */
    async onStartTask() {
      // 判断是否已接管
      if (!(await this.isTakeOver())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }

      // 判断是否选择了航线
      if (this.selectedAirway.id === -1) {
        this.$message.warning(this.$t('common.请选择航线'));
        return;
      }
      try {
        await this.$confirm(this.$t('common.请确认是否进行一键任务操作'), this.$t('common.安全确认'), {
          cancelButtonText: this.$t('common.取消'),
          confirmButtonText: this.$t('common.确定'),
          customClass: "uav_controlPane",
          showClose: false,
        });
        this.$store.commit("MMCFlightControlCenter/hangar/setState", {
          key: "airlineData",
          value: this.selectedAirway,
        });
        this.$store.dispatch("MMCFlightControlCenter/hangar/takeOff", {
          taskInfoId: this.selectedTaskId,
          callback: (status) => {
            if (status) {
              this.$message.success(this.$t('common.一键任务指令发送成功'));
            } else {
              this.$message.error(this.$t('common.一键任务指令发送失败'));
            }
          },
        });
        this.rootNode.$emit("taskStart", {
          uav: this.uav,
          task: this.selectedTaskId,
          airway: this.selectedAirway,
        });
      } catch (e) { }
    },
  },
};
</script>
<style lang="scss" scoped>
.taskListBox {
  height: 100%;
  width: 100%;
  background: #222222;
  border-radius: 12px;
  transition: 0.3s;
  display: flex;
  flex-direction: column;
  padding: 35px 16px 16px;

  .header {
    flex-shrink: 0;
    display: flex;
    justify-content: space-between;
    height: 32px;
    background: #3c3c3c;
    border-radius: 12px 12px 0px 0px;

    .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-image: -webkit-linear-gradient(right,
            #e3aa77,
            #f5cda9,
            #f9ecd3,
            #fcdbb1,
            #edb07a);
        -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 {
    flex: auto;

    position: relative;
    display: flex;
    flex-direction: column;
    flex-grow: 1;

    .el-form-item {
      flex-grow: 0;
      margin-bottom: 16px;
      $line-height: 32px;

      .el-form-item__label {
        line-height: 1;
        color: #fff;
        line-height: $line-height;
      }

      .el-form-item__content {
        line-height: 1;
        line-height: $line-height;
      }

      .el-select {
        width: 100%;
      }

      .el-input__inner {
        height: $line-height;
      }
    }
  }

  .btn {
    width: 110px;
    height: 32px;
    text-align: center;
    line-height: 32px;
    margin: 0 auto;
    color: #fff;
    background: #3388ff;
    font-family: SourceHanSansCN, SourceHanSansCN;
    font-weight: 400;
    font-size: 14px;
    cursor: pointer;
    border-radius: 4px;
  }

  .btn__add-line {
    position: absolute;
    bottom: 24px;
    right: 16px;
    cursor: pointer;
    font-family: MicrosoftYaHei;
    font-size: 12px;
    color: #3388ff;
  }
}

.select-airway__btn {
  width: 100%;
  height: 30px;
  padding: 0;
}

::v-deep.el-tooltip__popper {
  margin-top: 20px;
}
</style>
