<template>
  <div class="cpt-dashboard-airway ml20">
    <div class="airway-inner">
      <div class="form-item">
        <div class="form-input">
          <div class="cf jcsb">
            <div class="label_box w120">任务库</div>
            <el-cascader filterable popper-class="cpt-observe-mspace-dashboard-airway_popper" v-model="taskCateId"
              :options="airway_list" clearable :show-all-levels="false" placeholder="请选择任务" :props="{
                children: 'children',
                label: 'taskTitle',
                value: 'id',
                emitPath: false,
              }">
              <template slot-scope="{  data }">
                <el-tooltip :disabled="data.taskTitle.length < 11" class="item" effect="dark" :content="data.taskTitle"
                  placement="top-start">
                  <span>{{ data.taskTitle }}</span>
                </el-tooltip>
              </template>
            </el-cascader>
          </div>
          <div class="form_box pr jcsb mt20" >
            <div class="label_box cf w119">航线名称</div>
            <el-input class="label_box_input dib" v-model="ruleForm.flight_line" disabled />
            <el-tooltip class="dib pa right25 top10" effect="dark" content="显示航线" placement="top">
              <i class="el-icon-view cp lh40 dib" :style="showFlightLineFlag ? 'color:#02cfd4' : 'color:#fff'"
                @click="showFlightLine"></i>
            </el-tooltip>
          </div>
          <!-- <el-tooltip content="定位" placement="top">
              <i
                
                @click="this.handle_airway_change"
                class="iconfont ml10 cfc f20 cp mr5 icon-dingwei2"
              />
            </el-tooltip>
            <el-tooltip content="上传航线" placement="top">
              <i
                @click="upload__airway"
                
                class="iconfont f20 cfc cp ml10 mr5 icon-shangchuandaowurenji"
              />
            </el-tooltip> -->
        </div>
     <el-tooltip content="上传航线" placement="top">
          <div class="icon-box mt50">
            <span
              @click="handle_upload_airway"
              title="上传航线"
              class="iconfont icon-hangxianshangchuan cfc cp"
            ></span>
          </div>
            </el-tooltip> 

      </div>
    </div>
    <!-- <div class="form-item">
        <div class="form-label">飞行模式</div>
        <div class="form-input">
          <el-select
            @change="handle_change_uav_mode"
            v-model="mode"
            placeholder="请选择飞行模式"
          >
            <el-option
              v-for="item in drd.uav_mode"
              :key="item.data"
              :label="item.label"
              :value="item.data"
            />
          </el-select>
        </div>
      </div> -->
    <!-- <div class="form-item cf">
      摇 杆&nbsp; &nbsp;
      <div class="form-input">
        <el-select @change="handle_change_rocker_mode" v-model="recoker" placeholder="请选择摇杆模式">
          <el-option v-for="item in drd.rocker_mode" :key="item.id" :label="item.label" :value="item.id" />
        </el-select>
      </div>
    </div> -->
  </div>
  </div>
</template>

<script>
  import API from "@/api";
  import { Utils } from "mmc/utils/cesium";
  let airline_entitys = [];
  let air_line_preview = [];
  export default {
    props: {
      uav_mode: {
        type: String,
        default: () => "",
      },
      async_airway_drd: {
        type: Function,
        default: () => () => { },
      },
    },
    data() {
      return {
        mode: "",
        taskCateId: "",
        recoker: 1,
        airway_list: [],
        ruleForm: {
          flight_line_id: null,
          height: null,
          flight_line: null,
          id: "",
        },
        showFlightLineFlag: false,
        TaskList: [],

        drd: {
          airway: [],
          rocker_mode: [
            { id: 1, label: "自动模式" },
            { id: 2, label: "手动模式" },
          ],
        },
        ws: null,
      };
    },
    methods: {
      change(val) {
        // this.$emit('change', val)
      },
      showFlightLine() {
        if (!this.ruleForm.flight_line) return this.$message.info("暂无航线");
        this.showFlightLineFlag = !this.showFlightLineFlag;
        if (this.showFlightLineFlag) {
          this.handleAirLinePreview(this.selectLineList, true);
        } else {
          this.clear_airline_entitys();
        }
      },
      clear_airline_entitys() {
        let viewer = window.viewer;
        airline_entitys.forEach((item) => {
          viewer.entities.remove(item);
        });
      },
      
      // 航线数据
      async list_airway() {
        let res = await API.AIRWAY.getApprovedTask();
        if (res) {
          let jqList = [],
            ctList = [],
            lsList = [];
          for (let i = 0; i < res.length; i++) {
            if (res[i].taskCateId == 1) {
              jqList.push(res[i]);
            }
            if (res[i].taskCateId == 2) {
              ctList.push(res[i]);
            }
            if (res[i].taskCateId == 3) {
              lsList.push(res[i]);
            }
          }
          let airway_list = [
            {
              id: "警情任务",
              taskTitle: "警情任务",
              children: jqList,
            },
            {
              id: "常态任务",
              taskTitle: "常态任务",
              children: ctList,
            },
            {
              id: "临时任务",
              taskTitle: "临时任务",
              children: lsList,
            },
          ];
          this.airway_list = airway_list;
        }
      },
      handle_upload_airway() {
        if (!this.ruleForm.flight_line_id) {
          return this.$el_message("请选择航线", null, "error");
        }
        this.$emit("upload-airway", this.ruleForm.flight_line_id);
      },
      async drd_ariway() {
        let data = await this.async_airway_drd();
        this.drd.airway = data || [];
      },

      async handleAirLinePreview (item, state) {
      try {
        let viewer = window.viewer;
        if (airline_entitys?.length) {
          airline_entitys.forEach((item) => {
            viewer.entities.remove(item);
          });
        }
        let res = {};
        air_line_preview.forEach((item) => {
          viewer.entities.remove(item);
        });
        if (state) {
          res.flightCourseJson = item.flightCourseJson;
        } else {
          // res = await API.TASK.JingQingTrack({
          //   taskId: item.flightLineId,
          // });
        }
        // 有航点高度和距离的代码
        if (res?.flightCourseJson) {
          let positions = [];
          let center = [];
          let polyline = JSON.parse(res.flightCourseJson);
          let label_arr = [];
          let _this = this;
          polyline.points.forEach((item, index) => {
            positions.push(item.lon, item.lat, item.alt);
            label_arr.push(
              Cesium.Cartesian3.fromDegrees(item.lon, item.lat, item.alt)
            );
            let point_entity = viewer.entities.add({
              position: Cesium.Cartesian3.fromDegrees(
                item.lon,
                item.lat,
                item.alt
              ),
              name: "show_airline_point",
              point: {
                pixelSize: 10,
                color: Cesium.Color.fromCssColorString("#00A9A9"),
              },
              label: {
                text: String(item.alt) + "m",
                scale: 0.6,
                font: "bold 28px Microsoft YaHei",
                fillColor: Cesium.Color.fromCssColorString("#FF7F09"),
                horizontalOrigin: Cesium.VerticalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.CENTER,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
                showBackground: false,
                outlineWidth: 0,
                pixelOffset: new Cesium.Cartesian2(25, -10),
              },
            });
            airline_entitys.push(point_entity);
            if (label_arr.length > 1) {
              let before = label_arr[label_arr.length - 2];
              let after = label_arr[label_arr.length - 1];

              _this.create_label(before, after);
            }
          });

          positions = Cesium.Cartesian3.fromDegreesArrayHeights(positions);

          let redLine = viewer.entities.add({
            name: "Red line on terrain",
            polyline: {
              positions: new Cesium.CallbackProperty(() => {
                return positions;
              }, false),
              width: 4,
              // material: Cesium.Color.RED,
              material: Cesium.Color.fromCssColorString("#00A9A9"),
              // clampToGround: true,
            },
          });
          viewer.flyTo(redLine);
          airline_entitys.push(redLine);
        } else {
          this.$el_message("暂无航线", () => { }, "error");
        }
      } catch (error) {
        this.$el_message("暂无航线", () => { }, "error");
      }
    },
        // 显示距离
        create_label (before, after) {
      let viewer = window.viewer;
      let before_wgs84 = Utils.transformCartesian2WGS84(before);
      let after_wgs84 = Utils.transformCartesian2WGS84(after);

      let center_lng = (before_wgs84.lng + after_wgs84.lng) / 2;
      let cetner_lat = (before_wgs84.lat + after_wgs84.lat) / 2;
      let alt = (after_wgs84.alt + before_wgs84.alt) / 2;

      let position = Utils.transformWGS842Cartesian({
        lng: center_lng,
        lat: cetner_lat,
        alt: alt + 10,
      });

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

      let label_entity = viewer.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),
        },
      });
      airline_entitys.push(label_entity);
    },
    },
    watch: {
      uav_mode: {
        handler(value) {
          this.mode = value;
        },

      },
      ruleForm: {
        handler(newVal) {
          this.$store.commit("task/SET_FlLIGHTN_DETAIL", newVal);
        },
        deep: true,
      },
      taskCateId: {
        handler(newVal) {
          // 清除状态
          this.showFlightLineFlag = false;
          this.clear_airline_entitys();
          this.ruleForm.flight_line_id = "";
          this.ruleForm.flight_line = "";
          let arr = [];
          if (this.airway_list[0]?.children) {
            arr.push(...this.airway_list[0].children);
          }
          if (this.airway_list[1]?.children) {
            arr.push(...this.airway_list[1].children);
          }
          if (this.airway_list[2]?.children) {
            arr.push(...this.airway_list[2].children);
          }

          if (arr.length > 0) {
            let item = arr.find((item) => item.id === newVal);
            if (item) {
              this.$store.commit("checksafe/SET_LINE", {
                destination: item.destination,
                taskTitle: item.taskTitle,
              });
              this.selectLineList = item;
              this.ruleForm.flight_line_id = item.flightLineId;
              this.ruleForm.flight_line = item.flightName;
              this.ruleForm.id = item.id;
            }
          }
        },
      },
      immediate: true,
      deep: true,
    },
    mounted() {
      this.drd_ariway();
      this.list_airway();
    },
    beforeDestroy() {
      if (this.ws) {
        this.ws.close();
        this.ws = null;
      }
    },
  };
</script>

<style lang="scss" scoped>
  .cpt-dashboard-airway {
    width: 360px;
    padding-top: 10px;
    position: relative;
    box-sizing: border-box;

    &::before {
      width: 1px;
      height: 90px;
      content: " ";
      display: block;
      position: absolute;
      right: 0;
      top: 50%;
      background-image: linear-gradient(206deg,
          rgba(36, 146, 252, 0) 5%,
          #2492fc 56%,
          rgba(36, 146, 252, 0) 100%);
      transform: translateY(-50%);
    }

    .airway-inner {
      .form-item {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        &:last-child {
          margin-bottom: 0px;
        }

        .form-label {
          font-family: Microsoft YaHei;
          font-size: 14px;
          color: #b3bbc5;
          letter-spacing: 0;
          text-align: right;
          font-weight: 400;
          width: 75px;
          padding-right: 5px;
          box-sizing: border-box;
        }

        .form-input {

          // display: flex;
          // align-items: center;
          .icon-box {
            color: #08c2d1;
            margin-left: 5px;
            cursor: pointer;

            .iconfont {
              font-size: 30px;
            }
          }
        }
      }
    }
  }

  ::v-deep {
    .el-select {
      .el-input {
        .el-input__inner {
          height: 30px;
          background: #000000;
          border: 1px solid #08c2d1;
          border-radius: 2px;
          color: #08c2d1;
          font-size: 12px;
        }

        .el-input__suffix {
          .el-input__icon {
            line-height: 30px;
          }
        }
      }
    }
  }
</style>
<style lang="scss" scoped>
  ::v-deep .el-input__inner {
    background: #0b1138 !important;
    border: 1px solid rgba(8, 255, 255, 0.49) !important;
    ;
  }
  .el-cascader{}
</style>