<template>
  <div>
    <div class="ctx-box">
      <div class="form-box" v-show="!visible">
        <el-form :model="airline" :rules="rules">
          <el-form-item label="航线名称">
            <el-input v-model="airline.filename" placeholder="请输入航线名称" />
          </el-form-item>
          <el-form-item label="起始位置" prop="destination">
            <div class="item-group">
              <el-autocomplete :popper-append-to-body='false' v-model="start.name" :fetch-suggestions="handle_query_address_async"
                placeholder="请输入起始位置" :trigger-on-focus="false" @select="
                  (item) => {
                    handle_select_address(item, 'start');
                  }
                " clearable>
                <template slot-scope="{ item }">
                  <div>
                    <span style="font-size: 14px; color: #333">{{
                      item.name
                      }}</span>
                    <span style="font-size: 12px; color: #999; margin-left: 12px">{{ item.address }}</span>
                  </div>
                </template>
              </el-autocomplete>
              <div @click="handle_pick('start')" class="el-icon-location-outline"></div>
            </div>
          </el-form-item>
          <el-form-item label="目的位置" prop="destination">
            <div class="item-group">
              <el-autocomplete :popper-append-to-body='false' v-model="end.name" :fetch-suggestions="handle_query_address_async" placeholder="请输入目标位置"
                :trigger-on-focus="false" @select="
                  (item) => {
                    handle_select_address(item, 'end');
                  }
                " clearable>
                <template slot-scope="{ item }">
                  <div>
                    <span style="font-size: 14px; color: #333">{{
                      item.name
                      }}</span>
                    <span style="font-size: 12px; color: #999; margin-left: 12px">{{ item.address }}</span>
                  </div>
                </template>
              </el-autocomplete>
              <div @click="handle_pick('end')" class="el-icon-location-outline"></div>
            </div>
          </el-form-item>
          <el-form-item label="默认高度">
            <div class="item-group">
              <el-input v-model="airline.height" />
              <span class="unit">( m )</span>
            </div>
          </el-form-item>
          <el-form-item label="默认速度" prop="baseSpeed">
            <div class="item-group">
              <el-input v-model="airline.baseSpeed" />
              <span class="unit">( m/s )</span>
            </div>
          </el-form-item>
        </el-form>
        <div class="bottom-box cp" @click="handle_autoPlan">飞行航线</div>
      </div>
    </div>

    <div class="choose" v-show="visible">
      <div class="ctx-box mt25">
        <span class="aotu_tip">已自动规划{{ planlist.length }}条航线：</span>
        <div class="planlist" v-for="(item, index) in planlist" :key="index">
          <el-radio model="radio" :label="item.name">航线A：距离{{ item.distance / 1000 }}km，时长{{
            item.duration
            }}s</el-radio>
        </div>
      </div>
      <div class="btns">
        <div @click="close" class="btn ml80 cp">重新规划</div>
        <div @click="handle_sava" class="btn ml50 cp">保存</div>
      </div>
    </div>
  </div>
</template>

<script>
  import API from "@/api";
  import { Utils } from "mmc/utils/cesium";
  import axios2 from "axios";
  let SWXT_AUTOPLAN_URL = "http://32.128.12.138:21009/service/lbs/route/driving3";
  let handler = null;
  let data_srouce = null;
  let location_icon = null;
  let positions = [];

  export default {
    data() {
      var validateSpeed = (rule, value, callback) => {
        if (value < 2 || value > 15) {
          return callback(new Error("速度最大值为15，最小值为2"));
        }
      };
      return {
        rules: {
          baseSpeed: [
            { validator: validateSpeed, required: false, trigger: "blur" },
          ],
        },
        visible: false,
        airline: {
          filename: "",
          baseSpeed: 2,
          height: 100,
          destination: null,
          start: null,
        },
        planlist: [],
        start: {
          name: "",
          lng: 0,
          lat: 0,
        },
        end: {
          name: "",
          lng: 0,
          lat: 0,
        },
        radio: "1",
        positionsArr: [], //四维图新接口返回的所有航点（加了高度）
        positionsArr_y: [], //四维图新接口返回的所有航点
        lineDistance: 0, //四维图新接口返回的所有距离
        lineTime: "", //四维图新接口返回的用时
      };
    },
    inject: ["g_cesium_layer", "change_page"],
    methods: {
      // 点击自动航线的数据处理
      async handle_autoPlan() {
        // if (this.airline.filename == "") {
        //   this.$message.info('请输入航线名称！')
        // } else if(this.airline.height>15 || this.airline.height<2){
        //   this.$$message.info("航线速度允许最大值为15，最小值为2！请重新输入！")
        // }else {
        this.visible = true;
        // let data = {
        //   data: {
        //     rows: [
        //       {
        //         distance: 3366,
        //         duration: 553,
        //         niIds:
        //           "36546132,1,47;36546348,0,14;5119103,0,52;5106931,0,116;5106932,0,8;88050931,0,388;88050932,0,29;49719812,0,52;49719813,0,30;5106942,0,8;32083179,1,31;32083178,1,48;5224350,1,49;5119076,1,8;5119075,0,9;5224359,0,39;64858180,0,74;64858181,0,13;5230535,0,35;17430867,0,32;17430868,0,52;17430861,0,6;17430862,0,161;79278741,0,89;79278742,0,4;35802389,0,14;35802391,0,27;35802392,0,28;35802388,0,32;35802386,0,27;35802384,0,25;35802382,0,37;19497879,0,61;79278650,0,71;79278651,0,92;17430784,1,89;17430783,1,46;5119128,0,19;9226583,0,5;9226589,0,12;9226600,0,21;79278614,1,35;79278615,1,17;79278611,0,31;9226583,1,5;5119128,1,19;17430783,0,46;17430784,0,89;79278645,0,73;79278646,0,44;5227435,0,183;33254441,0,135;33254442,0,14;49512318,0,54;49512340,0,14;49512367,0,36;49512368,0,23;14663945,0,55;14663946,0,49;15781919,0,68;15781920,0,45;61613576,0,26;61613577,0,32;5117564,0,36;5117567,0,11;5117565,0,36;5119051,1,30;61613575,1,27;61613574,1,45;63929499,0,14;63929500,0,19;76828946,0,55;",
        //         routelatlon:
        //           "120.14201,33.3824;120.14248,33.38251;120.14248,33.38251;120.14251,33.38239;120.1426,33.3821;120.14264,33.38193;120.14264,33.38193;120.14301,33.38193;120.14364,33.38189;120.14389,33.38187;120.14398,33.38186;120.14444,33.38187;120.14524,33.38175;120.14571,33.38165;120.14615,33.38155;120.14646,33.38145;120.1467,33.38136;120.1469,33.38125;120.14709,33.38117;120.14744,33.38093;120.14779,33.38067;120.1479,33.38058;120.14801,33.38049;120.14838,33.38014;120.14859,33.37994;120.14864,33.37988;120.14878,33.37963;120.14899,33.37924;120.14921,33.37884;120.14921,33.37884;120.14926,33.37884;120.14932,33.37883;120.14963,33.37907;120.14974,33.37915;120.14985,33.37925;120.15022,33.37952;120.15032,33.3796;120.1506,33.37981;120.15087,33.38001;120.15106,33.38015;120.15129,33.38032;120.15134,33.38036;120.15174,33.38065;120.152,33.38082;120.15272,33.38124;120.15272,33.38124;120.15337,33.3807;120.1534,33.38067;120.15343,33.38064;120.15353,33.38055;120.15373,33.38037;120.15393,33.38018;120.15417,33.37996;120.15436,33.37978;120.15439,33.37975;120.15453,33.37961;120.15479,33.37936;120.15521,33.37894;120.1557,33.37845;120.15577,33.3784;120.15636,33.37784;120.15636,33.37784;120.15565,33.3773;120.15529,33.37702;120.15529,33.37702;120.15515,33.37714;120.15512,33.37718;120.15504,33.37727;120.15493,33.37743;120.15493,33.37743;120.1553,33.3775;120.1553,33.3775;120.15538,33.37736;120.15538,33.37736;120.15512,33.37718;120.15512,33.37718;120.15515,33.37714;120.15529,33.37702;120.15529,33.37702;120.15565,33.3773;120.15636,33.37784;120.15699,33.37824;120.15737,33.37848;120.15768,33.37866;120.15784,33.37877;120.15818,33.37901;120.15888,33.37954;120.15999,33.38033;120.1601,33.38041;120.1601,33.38041;120.16035,33.38004;120.16039,33.37999;120.16047,33.37988;120.16067,33.3796;120.16079,33.37942;120.16109,33.37899;120.16135,33.37861;120.16147,33.37843;120.16169,33.37808;120.16192,33.37772;120.16207,33.37752;120.16224,33.37727;120.16224,33.37727;120.16227,33.37729;120.16227,33.37729;120.16231,33.37732;120.16214,33.37755;120.16205,33.37767;120.16203,33.3777;120.16199,33.37776;120.16176,33.37812;120.16176,33.37812;120.16188,33.37819;120.16205,33.37828;120.16205,33.37828;120.16225,33.37804;120.16232,33.37799;120.1624,33.37799;120.16249,33.37804;",
        //         trafficSpeeds: "?x72",
        //       },
        //     ],
        //   },
        //   errcode: 0,
        //   errmsg: "",
        // };
        let sPoint = this.start.lng + "," + this.start.lat;
        let ePoint = this.end.lng + "," + this.end.lat;
        let data = await axios2
          .get(SWXT_AUTOPLAN_URL, {
            params: {
              sPoint: sPoint,
              ePoint: ePoint,
              st: 4,
              appKey: "f31add2975584a2b8c1d606e3f112f5a",
            },
          })
          .then((res) => {
            return res.data.data;
          });
        // let data1 = data.rows[0].routelatlon.replace(/\;/g, ",").split(",");
        // let data_y = data.rows[0].routelatlon.replace(/\;/g, ",").split(",");
        // this.positionsArr_y = data_y
        //   .slice(0, data_y.length - 1)
        //   .map((item) => item * 1);

        let item = data.rows[0].item
        console.log("item", item)
        let crr = []
        item.forEach(v => {
          console.log("vv-->", v);
          let arr = v.turnlatlon.split(",")
          crr.push(Number(arr[0]), Number(arr[1]))
        })
        console.log("crr:", crr);
        this.positionsArr_y = crr
        // this.positionsArr_y = item.reduce((total, item, index) => {
        //   console.log("885885");
        //   let arr = item.split(",")
        //   total.push(arr[0], arr[1])
        //   console.log("total:", total);
        //   return total
        // },[])
        // this.positionsArr_y = data.rows[0].item.reduce((total, item, index) => {
        //   let arr = item.split(",")
        //   total.push(arr[0], arr[1])
        //   console.log("total:", total);
        //   return total
        // },[])

        console.log("positionsArr_y:", this.positionsArr_y);

        this.positionsArr = this.positionsArr_y.reduce((total, item, index) => {
          total.push(item);
          if ((index + 1) % 2 === 0) {
            total.push(10);
          }
          return total;
        }, []);
        console.log("positionsArr:", this.positionsArr);
        this.lineDistance = data.rows[0].distance;
        this.duration = data.rows[0].duration;
        this.planlist = data.rows;
        this.handle_autoPlan_map();
        // }
      },

      // 点击自动航线的地图显示
      async handle_autoPlan_map() {
        const _this = this;
        let cesium_layer = this.g_cesium_layer();
        let viewer = cesium_layer.viewer();
        if (this.positionsArr.length > 2) {
          let potiion = Utils.transformWGS842Cartesian({
            lng: Number(_this.end.lng),
            lat: Number(_this.end.lat),
            alt: 20000,
          });
          console.log("potiion:", potiion);
          viewer.camera.flyTo({
            destination: potiion,
          });
        }
        data_srouce = new Cesium.CustomDataSource("airway_autoedit");
        await viewer.dataSources.add(data_srouce);
        let entities = data_srouce.entities;
        console.log("map-_this.positionsArr", _this.positionsArr);
        entities.add({
          polyline: {
            width: 3, 
            arcType: Cesium.ArcType.NONE,
            material: new Cesium.PolylineArrowMaterialProperty(
              Cesium.Color.PURPLE
            ),
            positions: new Cesium.CallbackProperty(() => {
              return Cesium.Cartesian3.fromDegreesArrayHeights(
                _this.positionsArr
              );
            }, false),
          },
        });
      },

      handle_query_address_async(address, cb) {
        API.MAP.Geo({ keywords: address })
          .then((res) => {
            cb(res.data.data.rows);
          })
          .catch((e) => cb([]));
      },

      close() {
        this.visible = false;
      },

      // 表单位置信息索引
      handle_select_address(item, type) {
        if (item) {
          let location = item.location.split(",");
          this[type].name = item.name;
          this[type].lng = Number(location[0]);
          this[type].lat = Number(location[1]);

          let cesium_layer = this.g_cesium_layer();
          let viewer = cesium_layer.viewer();
          let potiion = Utils.transformWGS842Cartesian({
            lng: this[type].lng,
            lat: this[type].lat,
            alt: 1000,
          });
          viewer.camera.flyTo({
            destination: potiion,
          });
          this.init_location_icon(potiion);
        }
      },
      // handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
      // handler.setInputAction(async (movement) => {
      //   let windowPosition = movement.position;
      //   let pickedObject = viewer.scene.pick(windowPosition);
      //   let position = Utils.getCartesian3FromPX(viewer, movement.position);
      //   console.log("position-->",position);
      //   let wgs84 = Utils.transformCartesian2WGS84(position);
      //   let address = await API.MAP.Regeo({
      //     location: `${wgs84.lng},${wgs84.lat}`,
      //   });
      //   console.log("address-->", address);
      //   if (address) {
      //     this[type].name = address;
      //     this[type].lng = wgs84.lng;
      //     this[type].lat = wgs84.lat;
      //   } else {
      //     this.$el_message("地址解析失败", () => {}, "error");
      //   }
      // }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
      // },

      // 点击表单旁图标定位
      async handle_pick(type) {
        handler = new Cesium.ScreenSpaceEventHandler(viewer.canvas);
        handler.setInputAction(async (movement) => {
          let position = Utils.getCartesian3FromPX(viewer, movement.position);
          let wgs84 = Utils.transformCartesian2WGS84(position);
          let address = await API.MAP.Regeo({
            location: `${wgs84.lng},${wgs84.lat}`,
          });

          if (address) {
            this[type].name = address;
            this[type].lng = wgs84.lng;
            this[type].lat = wgs84.lat;

            // 生成图标
            data_srouce = new Cesium.CustomDataSource("airway_edit");
            await viewer.dataSources.add(data_srouce);
            let entities = data_srouce.entities;
            entities.add({
              position: new Cesium.CallbackProperty(() => {
                return Cesium.Cartesian3.fromDegrees(
                  Number(this[type].lng),
                  Number(this[type].lat)
                );
              }, false),
              billboard: {
                width: 36,
                height: 36,
                image: require(`mmc/assets/images/icons/${type}Point.png`),
                horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
                verticalOrigin: Cesium.VerticalOrigin.Bottom,
                // heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                disableDepthTestDistance: Number.POSITIVE_INFINITY,
              },
            });
          } else {
            this.$el_message("地址解析失败", () => { }, "error");
          }
          handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOWN) &&
            (handler = null);
        }, Cesium.ScreenSpaceEventType.LEFT_DOWN);
      },

      init_location_icon(position) {
        let cesium_layer = this.g_cesium_layer();
        let viewer = cesium_layer.viewer();

        if (location_icon) {
          location_icon.position = position;
        } else {
          location_icon = viewer.entities.add({
            position,
            billboard: {
              width: 36,
              height: 36,
              image: require("mmc/assets/images/icons/icon_location.png"),
              horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
              verticalOrigin: Cesium.VerticalOrigin.Bottom,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
            },
          });
        }
      },

      // 点击保存
      handle_sava() {
        let points = this.positionsArr_y;
        let arr = [];
        for (var i = 0; i < points.length; i = i + 2) {
          arr.push({
            lon: points[i],
            lat: points[i + 1],
            alt: 0,
            pitch: 0,
            gimbalPitch: 0,
            action: [],
            uuid: i + "HHYYHH" + i + 1,
          });
        }
        const reqObj = {
          filename: this.airline.filename,
          line: {
            baseSpeed: this.airline.baseSpeed,
          },
          points: arr,
          baseSpeed: this.airline.baseSpeed,
        };
        this.airline.baseSpeed = Number(this.airline.baseSpeed);
        let options = {
          distance: this.lineDistance,
          flightCourseJson: JSON.stringify(reqObj),
          flightName: this.airline.filename,
          pointCount: points.length,
          time: parseInt(this.lineDistance / this.airline.baseSpeed),
          destination: this.end.name,
          lng: this.end.lng,
          lat: this.end.lat,
        };
        (this.airline = {
          filename: "",
          baseSpeed: 100.0,
          height: 100.0,
          destination: null,
          start: null,
        }),
          this.$emit("add", options);
      },
      destroy_cesium_handler() {
        let viewer = window.viewer;
        viewer.scene.globe.depthTestAgainstTerrain = false;

        if (handler) {
          // handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
          handler && handler.destroy() && (handler = null);
          handler = null;
        }

        if (data_srouce) {
          data_srouce.entities.removeAll();
          viewer.dataSources.remove(data_srouce, true);
          data_srouce = null;
          this.positionsArr = [];
          this.start.lng = 0;
          this.start.lat = 0;
          this.end.lng = 0;
          this.end.lat = 0;
        }
      },
      // clear_entities() {
      //   noFlyEntities.forEach((item) => {
      //     viewer.entities.remove(item);
      //   });
      //   electricFenceEntities.forEach((item) => {
      //     viewer.entities.remove(item);
      //   });
      //   noFlyEntities = [];
      //   electricFenceEntities = [];
      // },
      change_close() {
        let viewer = window.viewer;
        viewer.scene.globe.depthTestAgainstTerrain = false;
        // this.change_page();
      },
    },
    computed: {
      cesium_layer() {
        return this.g_cesium_layer();
      },
    },
    destroyed() {
      this.destroy_cesium_handler();
      // this.clear_entities();
    },
  };
</script>

<style lang=scss scoped>
  @import "~@/styles/var.scss";
  @import "~@/styles/mixins.scss";

  .title-box {
    height: 56px;
    box-sizing: border-box;
    padding-left: 112px;
    position: relative;
    display: flex;
    justify-content: space-between;
    margin-right: 80px;

    .title {
      font-family: PangMenZhengDao;
      font-size: 22px;
      color: #dce9ff;
      font-weight: 400;
      line-height: 3.2;
      margin-right: 30px;
    }

    .select {
      font-family: PangMenZhengDao;
      font-size: 22px;
      color: #00ffff;
      text-align: center;
      font-weight: 400;
    }

    &::before {
      content: " ";
      display: block;
      position: absolute;
      height: 1px;
      left: 0;
      bottom: 0;
      right: 0;
      background-image: linear-gradient(270deg,
          rgba(0, 117, 221, 0) 0%,
          #3ea4d5 50%,
          rgba(0, 117, 221, 0) 100%);
    }

    .right-box {
      flex: 1;
      display: flex;
      font-family: PangMenZhengDao;
      font-size: 18px;
      color: #20f0f0;
      text-align: center;
      font-weight: 400;
      line-height: 3.8;

      .before-point {
        margin-right: 12px;
      }

      .before-point,
      .after-point {
        cursor: pointer;
        user-select: none;
        margin-left: 15px;

        &.disabled {
          cursor: not-allowed;
        }
      }

      .no {
        margin: 0 10px;
      }
    }
  }

  .ctx-box {
    height: calc(100% - 56px - 88px);
    box-sizing: border-box;
    padding: 25px 0px 0px 70px;
    overflow: auto;

    .form-box {
      ::v-deep .el-form {
        .divider {
          @include linear_gradient_border(0, auto, 0, 0);
          height: 22px;
        }

        .el-form-item {
          .item-group {
            display: flex;
            align-items: center;

            .unit {
              font-family: MicrosoftYaHeiUI;
              font-size: 18px;
              color: rgb(179, 201, 203);
              font-weight: 400;
              margin-left: 12px;
            }

            .iconfont {
              color: rgb(179, 201, 203);
              font-size: 30px;
              margin-left: 0.3em;
              cursor: pointer;
            }

            .el-icon-location-outline {
              color: rgb(179, 201, 203);
              font-size: 30px;
              margin-left: 0.3em;
              cursor: pointer;
            }
          }

          .el-form-item__label {
            font-family: Microsoft YaHei;
            font-size: 16px;
            color: #ccedff;
            text-align: right;
            font-weight: 400;
          }

          .el-input {
            width: 356px;
            height: 40px;
            border: 1px solid #08c2d1;

            .el-input__inner {
              width: 100%;
              border: none;
              border-radius: 0;
              background-color: #000000;
              color: #fff;
            }
          }

          .el-input-number {
            width: 356px;

            .el-input-number__decrease,
            .el-input-number__increase {
              bottom: 1px;
              background: #606266;
              color: #f5f7fa;
              border-radius: 0;
              border: none;
            }

            .el-input-number__decrease {
              left: 1px;
            }

            .el-input-number__increase {
              right: -1px;
            }
          }
        }
      }
    }
  }

  .bottom-box {
    position: absolute;
    bottom: 50px;
    left: 150px;
    width: 300px;
    height: 50px;
    background-color: #08c2d1;

    font-family: PangMenZhengDao;
    font-size: 22px;
    color: #dce9ff;
    text-align: center;
    line-height: 50px;
    font-weight: 400;
  }

  .btns {
    display: flex;
    justify-content: space-between;
    position: absolute;
    bottom: 50px;

    .btn {
      width: 200px;
      height: 50px;
      background-color: #08c2d1;

      font-family: PangMenZhengDao;
      font-size: 22px;
      color: #dce9ff;
      text-align: center;
      line-height: 50px;
      font-weight: 400;
    }
  }

  ::v-deep .el-radio,
  .el-radio__inner,
  .el-radio__input {
    display: block;
    width: 20px;
    height: 20px;

    .el-radio__inner {
      width: 20px;
      height: 20px;
    }
  }

  ::v-deep  .el-radio {
    margin-bottom: 20px;
  }

  ::v-deep  .el-radio__label {
    font-family: MicrosoftYaHeiUI;
    font-size: 18px;
    color: #ccedff;
    text-align: right;
    font-weight: 400;
    line-height: 20px;
    margin-left: 20px;
  }

  .aotu_tip {
    color: #fff;
    font-size: 18px;
    line-height: 18px;
    margin-bottom: 26px;
    display: block;
  }
</style>