<template>
  <div class="stl-timed-task">
    <div class="cf m5 f12">
      {{ $t('common.主机库状态') }}：<span :class="apronInfo.masterStatus ? 'green' : ' red'">{{
        apronInfo.masterStatus ? $t('common.正常') : apronInfo.descText
      }}</span>
    </div>
    <div class="timed-task-header">
      <div class="header__column flex2">{{ $t('common.序号') }}</div>
      <div class="header__column flex2">{{ $t('common.机库名称') }}</div>

      <div class="header__column status">{{ $t('common.状态') }}</div>
      <div class="header__column flex2">{{ $t('common.距离') }}(km)</div>
    </div>
    <div
      class="timed-task-main"
      v-loading="loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <div
        class="row"
        :class="{ single: i % 2 != 0 }"
        v-for="(item, i) in skipList"
        :key="i"
      >
        <div class="row__column flex2">
          <span class="f12">
            <span class="mr10">
              <el-checkbox
                @change="changeFn(item)"
                v-model="item.active"
                :label="item.i"
                :disabled="!item.slaveStatus"
              ></el-checkbox> </span
            >{{ i + 1 }}
          </span>
        </div>
        <div class="row__column flex2">
          <el-tooltip
            class="item"
            effect="dark"
            :content="item.name"
            placement="top-start"
          >
            <span class="f12">{{ item.name }}</span>
          </el-tooltip>
        </div>
        <div class="row__column flex2">
          <el-tooltip
            :content="item.descText"
            class="item"
            effect="dark"
            placement="top-start"
          >
            <span
              class="f12"
              :class="{
                'text-red': !item.slaveStatus,
                'text-green': item.slaveStatus,
              }"
              >{{ item.slaveStatus ? $t('common.空闲') : $t('common.忙碌') }}</span
            >
          </el-tooltip>
        </div>
        <div class="row__column status" style="color: rgb(255, 189, 54)">
          <el-tooltip
            class="item"
            effect="dark"
            :content="String(item.targetDistance / 1000)"
            placement="top-start"
          >
            <span class="f12">{{
              (item.targetDistance / 1000)?.toFixed(2)
            }}</span>
          </el-tooltip>
        </div>
      </div>
    </div>
    <div class="task-add-btn" v-if="skipList.length > 0">
      <div class="task-add__btn" @click="creareLine">{{ $t('common.生成航线') }}</div>
      <div class="task-add__btn" @click="oneClickTask">{{ $t('common.一键任务') }}</div>
    </div>

    <div class="overlay" v-if="dialogVisible" v-interact>
      <div class="dialog-header">
        <div>
          <img src="../../../../assets/images/mount_head.png" />
          <span class="title vas">{{ $t('common.航线信息') }}</span>
        </div>
        <span class="cp w40 h40 cf pt15" @click="handleClose">X</span>
      </div>
      <div class="p10">
        <div class="stl-timed-task-ht wih100 f12 ml13 stl-timed-task-jk">
          <div class="wih100 tr">
            <div class="dib">
              {{ uav.uav && uav.uav.name }} --- {{ activeItem.name }}
            </div>
            <span style="color: #3388ff" class="ml56 cp pr130" @click="showLine"
              >{{ $t('common.预览') }}</span
            >
          </div>
        </div>
        <div class="stl-timed-task-ht mt16 cf">
          <div class="lh34 f12">{{ $t('common.飞行高度设置') }}：</div>
          <div class="bg">
            <el-input
              @blur="isEditing.height = false"
              size="mini"
              v-if="isEditing.height"
              v-model="flightHeight"
              type="number"
            />
            <span v-else class="indent">{{ flightHeight }} m</span>
          </div>
          <div class="text ml10 cp lh34" @click="toggleEdit('height')">
            {{ $t('common.编辑') }}
          </div>
        </div>
        <div class="stl-timed-task-ht mt16">
          <div class="lh34 f12">{{ $t('common.飞行速度设置') }}：</div>
          <div class="bg">
            <el-input
              @blur="isEditing.speed = false"
              size="mini"
              v-if="isEditing.speed"
              v-model="flightSpeed"
              type="number"
            />
            <span class="indent" v-else>{{ flightSpeed }} m/s</span>
          </div>
          <div class="text ml10 cp lh34" @click="toggleEdit('speed')">{{ $t('common.编辑') }}</div>
        </div>
        <div class="mt16">
          {{ $t('common.飞行总距离') }}：{{ activeItem.targetDistance?.toFixed(2) }}{{ $t('common.公里') }}
        </div>
      </div>
      <div class="tc mt50">
        <el-button size="mini" @click="handleClose">{{ $t('common.取消') }}</el-button>
        <el-button type="primary" size="mini" @click="handleConfirm"
          >{{ $t('common.确定') }}</el-button
        >
      </div>
    </div>

    <!-- <leapFrogFlighDialog :showClose="false" :dialogType="2" width="420px" title="低电量预警" :visible.sync="dialogVisible" @confirm="handleConfirm">
      <p class="tc">警告；低电量！！后续后续航程无法完成，当前未找到 合适机场充电，请确认是否进行返航！！</p>
      <div class="tc mt20">
        <span>30s</span><span class="cred ml15"> 强制返航</span>
      </div>
    </leapFrogFlighDialog>
    <leapFrogFlighDialog :showClose="false" :dialogType="2" width="420px" title="低电量预警" :visible.sync="dialogVisible" @confirm="handleConfirm">
      <p class="tc">警告；低电量！！当前已有合适机场充电，请确认
        是否进行返航！！</p>
      <div class="tc mt20">
        <span>30s</span><span class="cred ml15"> 前往>></span>
      </div>
    </leapFrogFlighDialog> -->
    <leapFrogDialog
      :title="$t('common.蛙跳飞行')"
      :visible.sync="leapFrogDialogVisible"
      @confirm="handleConfirm"
    ></leapFrogDialog>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import leapFrogFlighDialog from "./components/leapFrogFlighDialog";
import leapFrogDialog from "./components/leapFrogDialog";
let EntityList = [];
export default {
  name: "hangarTimedTask",
  components: {
    leapFrogFlighDialog,
    leapFrogDialog,
  },
  inject: ["rootNode", "bus"],
  props: {
    type: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      dialogVisible: false,
      // 当前选中要跳转的机
      activeItem: {},
      descCodeList: {
        0: "ok!",
        4401: this.$t('common.降落点位置未设置'),
        4402: this.$t('common.目标机库有无人机在舱内'),
        4403: this.$t('common.主跳转机库无人机不在舱内'),
        4404: this.$t('common.当前正在执行流程非可跳跃状态'),
        4405: this.$t('common.天气不宜飞行'),
        4406: this.$t('common.电量不足已飞至目标机库'),
      },
      apronInfo: {
        // chargeRemaining: 0,
        // computeDistance: 0,
        // descCode: 0,
        // descText: "",
        // deviceId: "",
        // height: 0,
        // latitude: 22.709333137094063,
        // longitude: 113.90762329101564,
        // masterStatus: true,
        // slaveStatus: true,
        // targetDistance: 0,
        // uavDeviceId: "",
        // name: "当前鹰巢11"
      },
      leapFrogDialogVisible: false,
      dialogVisible: false,
      selectedItems: [], // 选中的项目
      loading: false,
      skipList: [
        // {
        //   active: false,
        //   name: "鹰巢1",
        //   chargeRemaining: 0,
        //   computeDistance: 0,
        //   descCode: 0,
        //   descText: "",
        //   deviceId: "LMMC3X2KUAV202311063",
        //   height: 120,
        //   latitude: 22.545458392873208,
        //   longitude: 113.88856887817384,
        //   masterStatus: true,
        //   slaveStatus: true,
        //   targetDistance: 123,
        //   uavDeviceId: "LMMC3X2KUAV202501112",
        // },
        // {
        //   active: false,
        //   name: "鹰巢2",
        //   chargeRemaining: 0,
        //   computeDistance: 0,
        //   descCode: 0,
        //   descText: "",
        //   deviceId: "LMMC3X2KUAV20231106311",
        //   height: 120,
        //   latitude: 23.4551254223,
        //   longitude: 120.2155112,
        //   masterStatus: false,
        //   slaveStatus: true,
        //   targetDistance: 123,
        //   uavDeviceId: "LMMC3X2KUAV202501112",
        // },
      ],
      flightHeight: 100,
      flightSpeed: 5,
      isEditing: {
        height: false,
        speed: false,
      },
      intervalId: null,
    };
  },
  watch: {
    "uavRealTimeData.isFlying": {
      handler: function (newVal, oldVal) {
        if (oldVal === false && newVal === true) {
          console.log(this.$t('common.飞行状态'));
        }
      },
      deep: true,
      immediate: true,
    },
  },
  computed: {
    ...mapState("MMCFlightControlCenter", [
      "uav",
      "uavRealTimeData",
      "airwayEntities",
    ]),
    ...mapState("MMCFlightControlCenter/hangar", [
      "hangarRealTimeData",
      "hangar",
      "taskList",
    ]),
    // 选中的任务的飞行计划
    selectTaskFlightPlan() {
      return [];
    },
  },
  methods: {
    isTakeOverHangar() {
      return this.$store.dispatch("MMCFlightControlCenter/hangar/isTakeOver");
    },
    async oneClickTask() {
      if (!(await this.isTakeOverHangar())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      if (!this.apronInfo.masterStatus) {
        return this.$message.warning(this.apronInfo.descText);
      }
      // 执行前先校验主机库状态 0 未正常
      if (this.apronInfo && this.apronInfo.descCode != 0) {
        let { descCode } = this.apronInfo;
        return this.$message.warning(this.descCodeList[descCode]);
      }
      // 选择了调点再执行
      let data = this.skipList.filter((item) => item.active);
      if (data.length > 0) {
        this.activeItem = data[0];
      }
      if (!this.activeItem.deviceId) return this.$message.warning(this.$t('common.请选择跳点'));
      let { flightSpeed, flightHeight } = this;
      this.rootNode.$emit("apronUavSkipEvent", {
        // 主机库序列号
        masterDeviceId: this.hangar.deviceId,
        // 从机库设备序列号
        slaveDeviceId: this.activeItem.deviceId,
        altitude: flightHeight,
        speed: flightSpeed,
        callback: (res) => {
          resolve();
        },
      });
    },
    // 改变飞行日志弹框状态
    changeflyLogStatus(falg) {
      this.$store.commit("MMCFlightControlCenter/setState", {
        key: "flyLogStatus",
        value: falg,
      });
    },
    showLine() {
      let { height, latitude, longitude, name } = this.activeItem;
      let apronPosition = Cesium.Cartesian3.fromDegrees(
        this.apronInfo.longitude,
        this.apronInfo.latitude,
        this.apronInfo.height
      );
      // 创建一个带有图片的实体
      const apronEntity = window.$mmc_stl.viewer.entities.add({
        position: apronPosition, // 设置图片的位置（经纬度和高度）
        label: {
          text: this.apronInfo.name,
          font: "14pt monospace",
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian3(0.0, 32, 0.0),
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0.0,
            5000
          ),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          zIndex: 5000,
        },
        billboard: {
          image: require("../../assets/images/无人机库.png"), // 图片资源路径
          width: 50, // 图片宽度（可选，单位为像素）
          height: 60, // 图片高度（可选，单位为像素）
          eyeOffset: new Cesium.Cartesian3(0, 0, -10), // 图片与位置坐标的偏移量（可选）
          scale: 1, // 图片缩放比例（可选）
        },
      });
      EntityList.push(apronEntity);
      let imageEntityPosition = Cesium.Cartesian3.fromDegrees(
        longitude,
        latitude,
        height
      );
      // 创建一个带有图片的实体
      const imageEntity = window.$mmc_stl.viewer.entities.add({
        position: imageEntityPosition, // 设置图片的位置（经纬度和高度）
        label: {
          text: name,
          font: "14pt monospace",
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 2,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian3(0.0, 32, 0.0),
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0.0,
            10000
          ),
          disableDepthTestDistance: Number.POSITIVE_INFINITY,
          zIndex: 5000,
        },
        polyline: new Cesium.PolylineGraphics({
          positions: [apronPosition, imageEntityPosition],
          width: 4,
          material: Cesium.Color.RED,
          clampToGround: true,
          zIndex: 5000,
        }),
        billboard: {
          image: require("../../assets/images/无人机库.png"), // 图片资源路径
          width: 50, // 图片宽度（可选，单位为像素）
          height: 60, // 图片高度（可选，单位为像素）
          eyeOffset: new Cesium.Cartesian3(0, 0, -10), // 图片与位置坐标的偏移量（可选）
          scale: 1, // 图片缩放比例（可选）
        },
      });
      EntityList.push(imageEntity);
      const polyCenter = Cesium.BoundingSphere.fromPoints([
        apronPosition,
        imageEntityPosition,
      ]).center;
      console.log("PolyCenter:", polyCenter); // 调试信息
      let entityLabel = window.$mmc_stl.viewer.entities.add({
        position: polyCenter,
        label: {
          text: this.activeItem.targetDistance + "km",
          font: "14pt monospace",
          style: Cesium.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 4,
          eyeOffset: new Cesium.Cartesian3(0.0, 0.0, -10),
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(0, 0),
        },
      });
      EntityList.push(entityLabel);

      // 飞入到该实体位置
      window.$mmc_stl.viewer.camera.flyTo({
        destination: Cesium.Cartesian3.fromDegrees(longitude, latitude, 20000), // 设置相机目标位置
        duration: 2, // 飞行动画持续时间（秒）
      });
    },
    changeFn(item) {
      this.skipList.forEach((data) => {
        if (data.deviceId != item.deviceId) {
          data.active = false;
        }
      });
      this.activeItem = item;
    },
    getTaskList(deviceId) {
      return new Promise((resolve) => {
        this.rootNode.$emit("leapFrogFlighGet", {
          deviceId,
          callback: (res) => {
            if (res.skipList) {
              this.skipList = res.skipList.map((item) => {
                return {
                  ...item,
                  active: this.activeItem.deviceId == item.deviceId,
                };
              });
            }
            if (res.apronInfo) {
              this.apronInfo = res.apronInfo;
            }
            this.$nextTick(() => {
              resolve();
            });
          },
        });
      });
    },
    toggleEdit(type) {
      this.isEditing[type] = !this.isEditing[type];
    },
    async creareLine() {
      if (!(await this.isTakeOverHangar())) {
        this.$message.warning(this.$t('common.请先接管设备'));
        return;
      }
      let data = this.skipList.filter((item) => item.active);
      if (data.length > 0) {
        this.activeItem = data[0];
        this.changeflyLogStatus(true);
        this.dialogVisible = true;
      } else {
        this.$message.warning(this.$t('common.请选择跳点'));
      }
    },
    handleConfirm() {
      this.clearEntity();
      this.dialogVisible = false;
    },
    handleClose() {
      this.dialogVisible = false;
      this.flightHeight = 100;
      this.flightSpeed = 5;
      this.clearEntity();
    },
    clearEntity() {
      if (EntityList.length > 0) {
        EntityList.forEach((item) => {
          window.$mmc_stl.viewer.entities.remove(item);
        });
      }
    },
  },
  created() {
    this.intervalId = setInterval(() => {
      this.getTaskList(this.hangar.deviceId);
    }, 3000);
  },
  beforeDestroy() {
    clearInterval(this.intervalId); // 清除定时器
    this.clearEntity();
  },
};
</script>

<style lang="scss">
.stl-timed-task {
  height: 230px;
  display: flex;
  flex-direction: column;
  padding: 16px 4px;
  gap: 0px;
  box-sizing: border-box;
  position: relative;
  .green {
    color: green;
  }
  .red {
    color: red;
  }
  .overlay {
    position: fixed;
    top: 20%;
    left: 50%;
    width: 526px;
    height: 300px;
    color: #fff;
    background-color: #222222;
    transform: translate(-50%, -20%);

    .dialog-header {
      background: #3c3c3c;
      text-indent: 1rem;
      height: 40px;
      display: flex;
      justify-content: space-between;

      .title {
        font-size: 20px;
        font-family: YouSheBiaoTiHei;
        color: #14faff;
        line-height: 40px;
        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;
      }
    }
  }

  .timed-task-header {
    display: flex;
    flex-shrink: 0;
    font-size: 14px;
    height: 42px;
    background: #343434;
    font-family: YouSheBiaoTiHei;
    font-size: 16px;
    color: #ebf9ff;

    .header__column {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;

      &.flex2 {
        flex: 2;
      }

      &.status {
        flex: initial;
        width: 70px;
      }
    }
  }

  .timed-task-main {
    color: #fff;
    overflow-y: auto;
    flex: 1;
    z-index: 1;

    .row {
      display: flex;
      color: #fff;
      min-height: 52px;
      background-color: #222222;
      align-items: center;
      gap: 3px;

      &.single {
        background-color: #343434;
      }

      .row__column {
        font-size: 14px;
        flex: 1;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        .text-red {
          color: red;
        }

        .text-green {
          color: green;
        }

        &.col-2 {
          text-overflow: initial;
          font-size: 14px;
        }

        &.flex2 {
          flex: 2;
        }

        &.ctrl {
          display: flex;
          justify-content: center;
          align-items: center;
          gap: 5px;

          i {
            cursor: pointer;
            font-size: 20px;

            &.loading {
              opacity: 0.5;
            }
          }
        }

        &.status {
          flex: initial;
          width: 70px;
          font-size: 14px;
        }
      }
    }
  }

  .task-add-btn {
    display: flex;
    z-index: 1;

    .task-add__btn {
      cursor: pointer;
      width: 100px;
      height: 28px;
      background: #3388ff;
      border-radius: 2px;
      text-align: center;
      line-height: 28px;
      margin: 0 auto;
      margin-bottom: 10px;
      color: #fff;
    }
  }
}

.cred {
  color: #f42e2e;
}

.stl-timed-task-jk {
  overflow-x: auto;
  overflow-y: hidden;
}

.stl-timed-task-ht {
  display: flex;
  color: "#fff";

  .bg {
    background: #191919;
    width: 364px;
    height: 28px;
    line-height: 28px;
    color: #86909c;

    .indent {
      text-indent: 1rem;
      border: 1px solid #4b4b4b;
      border-radius: 5px;
      width: 100%;
      display: inline-block;
    }
  }

  .text {
    font-family: SourceHanSansCN, SourceHanSansCN;
    font-weight: 400;
    font-size: 12px;
    color: #3388ff;
    text-align: center;
    font-style: normal;
  }
}
</style>
