<template>
  <div class="normal-task">
    <el-form label-width="60px">
      <el-form-item label="任务库">
        <el-select
          v-model="selectedTaskId"
          popper-class="mmc"
          @change="onChangeTask"
          placeholder="请选择任务"
          clearable
        >
          <template v-if="showTaskList">
            <el-option
              v-for="item in taskListAll"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </template>
        </el-select>
      </el-form-item>
      <el-form-item label="航线">
        <el-button
          v-if="selectedTaskId !== -1"
          :disabled="selectedTaskId === ''"
          @click="onStartTask"
        >一键任务</el-button>
        <el-button v-else @click="showFlywayDialog = true">请选择航线</el-button>
      </el-form-item>
    </el-form>
    <LineList v-if="showFlywayDialog" @close="showFlywayDialog = false;" @change="onChangeLine"></LineList>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import LineList from "./components/lineList";
import { AirLine } from "../../../../../../../../../../api";
import hangarStatusDict from "../../hangarStatusDict";

export default {
  name: "normalTask",
  components: {
    LineList,
  },
  inject: ["rootNode", 'bus'],
  data() {
    return {
      // 选择的任务id
      selectedTaskId: "",
      // 选择的航线
      selectedAirway: {
        name: "",
        id: -1,
      },
      // 航线选择窗口
      showFlywayDialog: false,
      showTaskList: true, //用于任务列表更改时强制刷新组件
      taskListAll: [],
    };
  },
  computed: {
    ...mapState("MMCFlightControlCenter/hangar", [
      "hangarRealTimeData",
      "hangar",
      "taskList",
    ]),
    /**
     * 是否选择任务
     */
    isSelectTask() {
      return this.selectedTaskId[0] !== -1;
    },
    /**
     * 选择的任务数据
     */
    selectedTask() {
      let find = this.taskList.normal.find((item) => {
        return item.id === this.selectedTaskId;
      });
      return find;
    },
  },
  watch: {
    selectedAirway() {
      this.clearAirwayEntities();
      if (this.selectedAirway.id !== -1) {
        try {
          let airway = JSON.parse(this.selectedAirway.content);
          this.createAirwayEntities({
            polyline: airway.content,
            id: airway.id,
          });
        } catch (e) {
          console.log("绘制航线失败", e);
        }
      }
    },
  },
  created() {
    this.rootNode.$emit("hangarChangeTaskTab", {
      type: 1,
    });
    this.updateTaskList();
    //todo 通过iframe嵌入时, 不知道为什么无法监听this.$store.state.MMCFlightControlCenter.hangar.taskList的变化, 会导致任务列表不更新, 通过事件方式强制更新
    this.bus.$on('updateHangarTaskList', this.updateTaskList);  
  },
  beforeDestroy() {
    this.clearAirwayEntities();
    this.bus.$off('updateHangarTaskList', this.updateTaskList);
  },
  methods: {
    ...mapActions("MMCFlightControlCenter", [
      "createAirwayEntities",
      "clearAirwayEntities",
    ]),
    /**
     * 更新任务列表
     */
    updateTaskList() {
      console.log('updateTaskList');
      this.taskListAll = [
        {
          id: -1,
          name: "选择航线自动生成任务",
        },
        ...this.$store.state.MMCFlightControlCenter.hangar.taskList.normal || [],
      ];
    },
    /**
     * 更改任务事件
     */
    async onChangeTask() {
      if (this.selectedTask?.airwayId) {
        let res = await AirLine.routeDetail({
          id: this.selectedTask?.airwayId,
        });
        if (res.code === 200) {
          this.selectedAirway = res.data;
        }
      } else {
        this.selectedAirway = {
          name: "",
          id: -1,
        };
      }
    },
    /**
     * 更改航线事件
     */
    onChangeLine(data) {
      this.selectedAirway = data;
      if (data) {
        this.rootNode.$emit("hangarAddTask", {
          type: 1, //1: 日常任务 2.定时任务 3.周期任务
          airway: data, //航线数据
          callback: ({ id }) => {
            // 返回新增任务后的任务id
            this.selectedTaskId = id;
          },
        }); // 根节点发送机库任务新增事件
      }
    },
    /**
     * 一键任务事件
     */
    async onStartTask() {
      // 判断是否选择了航线
      if (this.selectedAirway.id === -1) {
        this.$message.warning("请选择航线");
        return;
      }
      try {
        await this.$confirm("请确认是否进行一键任务操作?", "安全确认", {
          cancelButtonText: "取消",
          confirmButtonText: "确定",
          customClass: "uav_controlPane",
          showClose: false,
        });
        // 当前机库状态是否空闲
        if ([0, 8].includes(this.hangarRealTimeData.processStatus)) {
          this.$store.commit("MMCFlightControlCenter/hangar/state", {
            key: "airlineData",
            value: this.selectedAirway,
          });
          this.$store.dispatch("MMCFlightControlCenter/hangar/takeOff", {
            callback: (status) => {
              if (status) {
                this.$message.success("一键任务指令发送成功");
              } else {
                this.$message.error("一键任务指令发送失败");
              }
            },
          });
          this.rootNode.$emit("hangarStartTask", {
            type: 1, //1: 日常任务 2:定时任务 3:周期任务
            hangar: this.hangar,
            task: this.selectedTask,
            airway: this.selectedAirway,
          });
        } else {
          // 获取当前机库状态
          const statusItem = hangarStatusDict.find(
            (item) => item.value === this.hangarRealTimeData.processStatus
          );
          this.$message.warning(statusItem?.label || "");
        }
      } catch (e) {}
    },
  },
};
</script>

<style lang="scss" scoped>
.normal-task ::v-deep {
  padding: 32px 16px;

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

  .el-form-item__content {
    > * {
      width: 100%;
    }
  }
}
</style>