<template>
  <div class="sm-function-module-content" v-show="cameraShow">
    <Tabs value="">
      <TabPane :label="Resource.flyRoute" name="fxxl">
        <!-- <label class="label-container">{{ Resource.flyRoute }}</label>
        <input
          class="sm-input"
          type="file"
          accept=".fpf"
          id="flyFile"
          style="width: 100%"
        /> -->
        <div class="importFly">
          <span>{{ Resource.flyRoute }}</span>
          <input type="file" accept=".fpf" id="flyFile" style="width: 100%" />
        </div>
        <div class="flybox">
          <i
            class="el-icon-video-play flyBtn"
            @click="flyStart"
            :title="Resource.startFly"
          ></i>
          <i
            class="el-icon-video-pause flyBtn"
            @click="flyPause"
            :title="Resource.pauseFly"
          ></i>
          <i
            class="el-icon-document-delete flyBtn"
            @click="flyStop"
            :title="Resource.stopFly"
          ></i>
        </div>
        <div class="sm-function-module-sub-section">
          <label class="label-container">{{ Resource.stopChoose }}</label>
          <select
            class="sm-select"
            id="stopList"
            v-model="stopSelected"
          ></select>
        </div>
        <div class="sm-function-module-sub-section">
          <label class="label-container">{{ Resource.observe }}</label>
          <div class="flexbox">
            <el-button type="primary" size="mini" @click="onSpinClk">{{
              Resource.rotatePoint
            }}</el-button>
            <el-button type="primary" size="mini" @click="onCancelSpinClk">
              {{ Resource.cancelRotatePoint }}
            </el-button>
            <!-- <label>{{ Resource.pauseFly }}</label>
            <input type="checkbox" v-model="stopFlyCircle" />
            <label>{{ Resource.rotateCirculation }}</label>
            <input type="checkbox" v-model="circulation" /> -->
            <el-checkbox v-model="stopFlyCircle">{{
              Resource.pauseFly
            }}</el-checkbox>
            <el-checkbox v-model="circulation">{{
              Resource.rotateCirculation
            }}</el-checkbox>
          </div>
          <label class="label-container">{{ Resource.rotateSpeed }}</label>
          <div class="sm-solider-input-box">
            <input
              class="min-solider"
              min="0"
              max="50"
              step="0.1"
              style="width: 63%"
              type="range"
              v-model="speed"
            />
            <input
              class="min-solider"
              min="0"
              max="50"
              step="0.1"
              style="width: 34%"
              type="number"
              v-model="speed"
            />
          </div>
        </div>
        <div class="sm-function-module-sub-section">
          <label class="label-container">{{ Resource.underground }}</label>
          <br />
          <label class="sm-viewshed-label-right">{{
            Resource.openUnderground
          }}</label>
          <input type="checkbox" v-model="underground" />
          <div class="sm-function-module-sub-section">
            <label class="label-container">{{
              Resource.cameraMinimumZoomDistance
            }}</label>
            <input
              class="sm-input-long"
              min="0"
              type="number"
              v-model="cameraMinimumZoomDistance"
            />
          </div>
          <div class="sm-function-module-sub-section">
            <label class="label-container">{{
              Resource.SurfaceTransparency
            }}</label>
            <input
              class="sm-input-long"
              min="0"
              max="1.0"
              step="0.01"
              type="number"
              v-model="SurfaceTransparency"
            />
          </div>
        </div>
      </TabPane>
      <TabPane :label="Resource.createFlyRoute" name="cjfxxl">
        <div class="icon-list" style="width: 12.96rem">
          <span
            v-for="(item, index) in state.itemOptions"
            :key="index"
            class="icon-span"
            :title="item.lable"
            :class="item.isSelect ? 'selected-icon' : ''"
            @click="changleIconItem(item)"
          >
            <i
              class="iconfont iconSize"
              :class="item.iconName"
              style="margin-top: 0px"
            ></i>
          </span>
        </div>
        <div v-show="state.customRouteNames.length > 0">
          <div class="row-item">
            <span>已经添加站点</span>
            <div>
              <!-- <n-select
                v-model="state.selectedAddedStopIndex"
                :options="state.routeStops"
                label-field="stopName"
                value-field="index"
              /> -->
              <el-select v-model="state.selectedAddedStopIndex">
                <el-option
                  v-for="item in state.routeStops"
                  :key="item.value"
                  :label="item.stopName"
                  :value="item.index"
                >
                </el-option>
              </el-select>
            </div>
          </div>

          <div class="row-item" style="margin-bottom: 0px">
            <span></span>
            <div class="row-content" style="display: flex">
              <el-checkbox v-model="showRoute" /><span class="checkbox-lable"
                >显示路线</span
              >
              <el-checkbox v-model="showStop" /><span class="checkbox-lable"
                >显示站点</span
              >
            </div>
          </div>

          <div>
            <label class="label-container">飞行速度</label>
            <div class="sm-solider-input-box">
              <input
                class="min-solider"
                min="0"
                max="500"
                step="1"
                style="width: 63%"
                type="range"
                v-model="state.routeSpeed"
              />
              <span>{{ state.routeSpeed }}</span>
            </div>
          </div>

          <!-- <div class="block">
            <span class="demonstration">飞行速度</span>
            <el-slider v-model="state.routeSpeed" step="1" min="0" max="500" style="width: 63%"></el-slider>
            <span>{{ state.routeSpeed }}</span>
          </div> -->

          <div class="icon-list" style="width: 12.96rem">
            <span
              v-for="(item, index) in state.actionOptions"
              :key="index"
              class="icon-span"
              :title="item.lable"
              :class="item.isSelect ? 'selected-icon' : ''"
              @click="changleIconItemAction(item)"
            >
              <i
                class="iconfont iconSize"
                :class="item.iconName"
                style="margin-top: 0px"
              ></i>
            </span>
          </div>

          <div class="btn-row-item" style="margin-left: 0.94rem">
            <el-button
              type="info"
              color="#3499E5"
              text-color="#fff"
              @click="downLoad"
              style="margin-right: 0.1rem; margin-left: 0.03rem"
              >下载</el-button
            >
            <el-button
              class="btn-secondary"
              @click="clearRoute"
              color="rgba(255, 255, 255, 0.65)"
              ghost
              >清除</el-button
            >
          </div>
        </div>
        <!-- <rotate></rotate> -->
        <div class="row-item">
        <span>绕点旋转</span>
        <!-- <div style="width: 12.96rem">
          <n-switch v-model="state.rotateShow" size="small" />
        </div> -->
        <el-switch
          v-model="state.rotateShow"
          active-color="#13ce66"
          inactive-color="#ff4949"
        >
        </el-switch>
      </div>
        <div v-show="state.rotateShow">
          <div class="flexbox">
            <el-button type="primary" size="mini" @click="onSpinClk">{{
              Resource.rotatePoint
            }}</el-button>
            <el-button type="primary" size="mini" @click="onCancelSpinClk">
              {{ Resource.cancelRotatePoint }}
            </el-button>
            <el-checkbox v-model="stopFlyCircle">{{
              Resource.pauseFly
            }}</el-checkbox>
            <el-checkbox v-model="circulation">{{
              Resource.rotateCirculation
            }}</el-checkbox>
          </div>
          <label class="label-container">{{ Resource.rotateSpeed }}</label>
          <div class="sm-solider-input-box">
            <input
              class="min-solider"
              min="0"
              max="50"
              step="0.1"
              style="width: 63%"
              type="range"
              v-model="speed"
            />
            <input
              class="min-solider"
              min="0"
              max="50"
              step="0.1"
              style="width: 34%"
              type="number"
              v-model="speed"
            />
          </div>
        </div>
      </TabPane>
    </Tabs>
  </div>
</template>

<script>
let flyManager,
  camera,
  flyCircleDrawHandler,
  createXml,
  currentStops,
  routeCollection;
let flyLineXmls = [];
import tool from "./tool";
import createFlyLine_xml from "./fly-line-xml.js";
import rotate from "./rotate.vue";
// ,
// let pointLightSourceDrawHandler,
//   spotOrDirectionalLightSourceDrawHandler,
//   spotOrDirectionalLightSourceCountHandler,
//   spotOrDirectionalLightSourceAdding = false,
//   spotOrDirectionalLightPositions = [],
//   entityPointLightPairs = new Map(), // Entity和点光源对象的键值对
//   entitySpotLightPairs = new Map(), // Entity和聚光灯对象的键值对
//   entityDirectionalLightPairs = new Map(); // Entity和平行光对象的键值对

export default {
  name: "sceneCamera",
  components: {
    rotate,
  },
  data() {
    return {
      sharedState: store.state,
      stopSelected: [],
      stopFlyCircle: false,
      circulation: true,
      flyCirclePoint: null,
      speed: 1,
      underground: false,
      SurfaceTransparency: 1,
      cameraMinimumZoomDistance: -1000,
      isDestroyFlag: true,

      // 设置默认值数据
      state: {
        routeType: "customRoute", //自定义还得指定路线类型
        fileSrc: "", //文件地址,不能同时使用fpfUrl
        fpfUrl: null, //指定fpf路径
        selectedStopIndex: 0, //选中当前站点
        addCurrentStopIndex: 0, // 记录当前添加站点的索引并赋值给站点index，以便n-select
        showRoute: false, //显示路线
        showStop: false, //显示站点
        currentStopNames: [], //当前路线的站点名称集合
        currentStopNamesIndex: 0, // 记录当前路线的索引并赋值，以便n-select
        //自定义
        customRouteNames: [], //保存自定义路线名称
        addCurrentRouteIndex: 0, // 当前路线索引，以便n-select
        customRouteSelectedIndex: null, //自定义选中路线索引
        routeStops: [], //自定义当前路线的站点集合
        selectedAddedStopIndex: undefined, //自定义已加站点选中索引
        //站点
        setStopName: "Stop-1", //设置当前站点名称
        setStopSpeed: 0, // 设置当前站点速度
        stopPlayMode: "StopPause", //设置站点模式:默认停留
        waitTime: 0, //停留时间
        surroundDuration: 1, //环绕模式时间
        //飞行路线设置
        isAlongline: false, //获取或者设置该飞行路线是否是沿线飞行。
        routeSpeed: 200, //飞行路线速度
        isSaveAutoFlag: false,
        //   allRoutes:[]
        itemOptions: [
          {
            index: 1,
            lable: "添加站点",
            iconName: "el-icon-circle-plus-outline",
            isSelect: false,
          },
          {
            index: 2,
            lable: "删除站点",
            iconName: "el-icon-delete",
            isSelect: false,
          },
          {
            index: 3,
            lable: "恢复",
            iconName: "el-icon-refresh-right",
            isSelect: false,
          },
          {
            index: 4,
            lable: "保存",
            iconName: "el-icon-document",
            isSelect: false,
          },
        ],
        actionOptions: [
          {
            index: 1,
            lable: "播放",
            iconName: "el-icon-video-play",
            isSelect: false,
          },
          {
            index: 2,
            lable: "暂停",
            iconName: "el-icon-video-pause",
            isSelect: false,
          },
          {
            index: 3,
            lable: "停止",
            iconName: "el-icon-help",
            isSelect: false,
          },
        ],
      },
      showRoute: false, //显示路线
      showStop: false, //显示站点
    };
  },

  computed: {
    cameraShow: function () {
      return this.sharedState.sceneAtttribute[1];
    },
    SceneAtttributeShow: function () {
      return this.sharedState.toolBar[3];
    },
  },
  beforeDestroy() {
    if (this.isDestroyFlag && camera) {
      camera = undefined;
      if (flyCircleDrawHandler) {
        // flyCircleDrawHandler.destroy();
        flyCircleDrawHandler = undefined;
      }
      if (flyManager) {
        flyManager.destroy();
        flyManager = this.undefined;
      }
    }
  },
  mounted() {
    if (this.SceneAtttributeShow && this.basicOptions) {
      this.init();
    }
    //初始化站点文件保存
    this.initFlyManager();
  },
  methods: {
    //子组件部分
    init() {
      if (camera) {
        return;
      }
      camera = scene.camera;
      camera.flyCircleLoop = true;
    },
    flyStart() {
      console.log(flyManager, "flyManager");

      // if (flyManager) {
      //   flyManager.play();
      // } else {
      let routes = new Cesium.RouteCollection(viewer.entities);
      let fileInput = document.getElementById("flyFile");
      let file = fileInput.files[0];
      if (!file) {
        return; // 没有选择fpf文件无法开始执行
      }
      let reader = new FileReader();
      reader.onload = function (e) {
        // 读取操作完成时出发
        let XMLContent = e.target.result;

        routes.fromXML(XMLContent);
      };
      reader.readAsBinaryString(file);
      //创建飞行管理对象
      flyManager = new Cesium.FlyManager({
        scene: scene,
        routes: routes,
      });
      flyManager.stopArrived.addEventListener(function (routeStop) {
        routeStop.waitTime = 1;
      });
      if (flyManager.readyPromise) {
        Cesium.when(flyManager.readyPromise, function () {
          let currentRoute = flyManager.currentRoute;
          currentRoute.isLineVisible = true;
          currentRoute.isStopVisible = true;

          let allStops = flyManager.getAllRouteStops();
          let menu = document.getElementById("stopList");
          for (let i = 0, j = allStops.length; i < j; i++) {
            let option = document.createElement("option");
            option.textContent = Resource.stop + (i + 1);
            console.log(Resource, "asdas");

            option.value = allStops[i].index;
            menu.appendChild(option);
          }
          flyManager.play();
        });
      }
      // }
    },
    flyPause() {
      flyManager && flyManager.pause();
    },
    flyStop() {
      flyManager && flyManager.stop();
    },
    onSpinClk(evt) {
      this.isDestroyFlag = false;
      if (!flyCircleDrawHandler) {
        flyCircleDrawHandler = new Cesium.DrawHandler(
          viewer,
          Cesium.DrawMode.Point
        );
        flyCircleDrawHandler.activeEvt.addEventListener(function (isActive) {
          if (isActive == true) {
            viewer.enableCursorStyle = false;
            viewer._element.style.cursor = "";
            document.body.classList.add("drawCur");
          } else {
            viewer.enableCursorStyle = true;
            document.body.classList.remove("drawCur");
          }
        });
        flyCircleDrawHandler.drawEvt.addEventListener((result) => {
          this.flyCirclePoint = result.object.position;
          viewer.entities.removeById("fly-circle-point");
          viewer.entities.add({
            id: "fly-circle-point",
            position: this.flyCirclePoint,
            billboard: {
              image: "@/../static/images/flypng/flyCircle.png",
              scaleByDistance: new Cesium.NearFarScalar(10, 1.0, 1000, 0.1),
              disableDepthTestDistance: Number.POSITIVE_INFINITY, // 关闭深度检测，使billboard不至于被裁剪
            },
          });
          camera.stopFlyCircle(); // 先停止之前的旋转，再开始新的旋转
          camera.flyCircle(this.flyCirclePoint);
          flyCircleDrawHandler.clear();
        });
      }
      flyCircleDrawHandler.activate();
    },
    onCancelSpinClk() {
      this.isDestroyFlag = true;
      camera.stopFlyCircle();
      viewer.entities.removeById("fly-circle-point");
      this.flyCirclePoint = null;
    },

    // 功能切换
    changleIconItem(item) {
      this.state.itemOptions.map((itemObj) => {
        if (itemObj.index == item.index) {
          itemObj.isSelect = true;
        } else {
          itemObj.isSelect = false;
        }
      });

      switch (item.index) {
        case 1: {
          this.addStop();
          break;
        }
        case 2: {
          this.deleteStop();
          break;
        }
        case 3: {
          this.restStops();
          break;
        }
        case 4: {
          this.saveStop();
          break;
        }
        default:
          break;
      }
    },

    // 添加站点
    addStop() {
      if (flyManager) {
        flyManager.stop();
      }
      let point = viewer.camera.position;
      let position = tool.CartesiantoDegrees(point);
      let stop = {
        stopName: this.state.setStopName,
        index: this.state.addCurrentStopIndex,
        point: position,
        heading: viewer.camera.heading,
        tilt: viewer.camera.pitch,
        speed: this.state.setStopSpeed,
        stopPlayMode: this.state.stopPlayMode,
        surroundDuration: this.state.surroundDuration,
        waitTime: this.state.waitTime,
      };
      this.state.routeStops.push(stop);
      if (this.state.isSaveAutoFlag) {
        this.saveStop(); // 一旦添加站点，立即保存
      }
      let routeLen = this.state.routeStops.length;
      if (routeLen > 0)
        this.state.addCurrentStopIndex =
          this.state.routeStops[routeLen - 1].index + 1; // 保证新增的站点index始终比前一位大1
      this.$message.success(`${"站点添加成功"}: ${this.state.setStopName}`);

      if (this.state.routeStops.length > 0) {
        let len = this.state.routeStops.length;
        let lastStopName = this.state.routeStops[len - 1].stopName;
        let index = lastStopName.split("-")[1] || 1;
        let name = "Stop-" + (Number(index) + 1);
        this.state.setStopName = name;
      }
      this.state.selectedAddedStopIndex =
        this.state.routeStops[this.state.routeStops.length - 1].index;
    },

    // 清除选中站点
    deleteStop() {
      let delIndex = this.state.routeStops.findIndex(
        (e) => e.index == this.state.selectedAddedStopIndex
      );
      this.state.routeStops.splice(delIndex, 1);
      if (this.state.routeStops.length > 1 && this.state.isSaveAutoFlag) {
        this.saveStop(); // 一旦删除站点，实时保存
      }
      if (this.state.routeStops.length > 0) {
        this.state.selectedAddedStopIndex =
          this.state.routeStops[this.state.routeStops.length - 1].index;
        return;
      }
      this.state.selectedAddedStopIndex = undefined;
      this.state.setStopName = "Stop-1";
    },

    // 重置当前路线
    restStops() {
      let route = flyManager.currentRoute;
      if (route) {
        route.isLineVisible = false;
        route.isStopVisible = false;
      }
      this.state.setStopName = "Stop-1";
      this.state.routeStops = [];
      this.state.addCurrentStopIndex = 0;
      this.state.selectedAddedStopIndex = 0;
      // this.state.routeStops.length = 0;
      // this.state.setStopSpeed = 0;
      // this.state.stopPlayMode = "StopPause";
      // this.state.waitTime = 0;
      // this.state.surroundDuration = 1;
    },

    // 保存站点
    saveStop() {
      console.log(5, this.state.routeStops);
      if (this.state.routeStops.length < 2) {
        if (this.state.customRouteNames.length == 0) {
          this.$message.waring("至少两个节点才能保存");
          console.log(1111);
        }
        return;
      }

      // 飞行路线配置
      let route = {
        routeName: "飞行路线-1",
        index: this.state.addCurrentRouteIndex,
        speed: this.state.routeSpeed,
        isAlongLine: "False",
        routeStops: this.state.routeStops,
      };
      let xml = createXml.createXMLflyLine(route);
      flyLineXmls[0] = xml;
      this.state.isSaveAutoFlag = true; //一旦点击保存，开启实时自动保存
      // 保证只有一条飞行路线
      if (this.state.customRouteNames.length === 0) {
        this.state.customRouteNames.push({
          label: route.routeName,
          value: route.index,
        });
      }
      this.updateRouteCollection();
      this.state.addCurrentRouteIndex++;
      if (this.state.customRouteSelectedIndex === null)
        this.state.customRouteSelectedIndex = 0;
    },

    // 更新飞行路径
    updateRouteCollection() {
      flyManager && flyManager.stop();
      let route = flyManager.currentRoute;
      if (route) route.clear(); //清除之前的
      routeCollection = new Cesium.RouteCollection(viewer.entities); //飞行路线底层默认第一条路线，所以重新new
      routeCollection.fromXML(flyLineXmls[0]); // 默认飞行路径只有一条
      this.readyPromise();
    },
    // 异步飞行管理准备就绪函数
    readyPromise() {
      routeCollection.readyPromise.then(() => {
        flyManager.routes = routeCollection;
        let route = flyManager.currentRoute;
        route.isLineVisible = this.state.showRoute;
        route.isStopVisible = this.state.showStop;
        this.updateCurrentStops();
      });
    },
    // 更新当前路线站点
    updateCurrentStops() {
      this.state.currentStopNames.length = 0;
      currentStops = flyManager.getAllRouteStops();
      this.state.currentStopNamesIndex = 0;
      for (let i = 0, j = currentStops.length; i < j; i++) {
        let stopName = currentStops[i].stopName || "Stop" + (i + 1);
        this.state.currentStopNames.push({
          label: stopName,
          value: this.state.currentStopNamesIndex,
        });
        this.state.currentStopNamesIndex++;
      }
    },

    //初始化飞行管理
    initFlyManager() {
      routeCollection = new Cesium.RouteCollection(viewer.entities);
      flyManager = new Cesium.FlyManager({
        scene: viewer.scene,
        routes: routeCollection,
      });
      createXml = new createFlyLine_xml();
    },

    // 操作切换
    changleIconItemAction(item) {
      this.state.actionOptions.map((itemObj) => {
        if (itemObj.index == item.index) {
          itemObj.isSelect = true;
        } else {
          itemObj.isSelect = false;
        }
      });

      switch (item.index) {
        case 1: {
          this.flyStart(); //开始
          break;
        }
        case 2: {
          this.flyPause(); //暂停
          break;
        }
        case 3: {
          this.flyStop(); //停止
          break;
        }
        default:
          break;
      }
    },

    // 下载选择的飞行路线fpf文件
    downLoad() {
      let data = flyLineXmls[this.state.customRouteSelectedIndex];
      if (!data) return;
      let blob = new Blob([data]); //将返回的数据包装成blob（方法的具体使用参考mdn）
      let alink = document.createElement("a");
      alink.download = "fly-route.fpf"; //文件名,大部分浏览器兼容,IE10及以下不兼容
      alink.href = URL.createObjectURL(blob); //根据blob 创建 url
      alink.click(); //自动点击
    },

    // 清除选中飞行路线
    clearRoute() {
      flyManager.stop();
      if (flyLineXmls.length < 1) return;
      flyLineXmls.splice(this.state.customRouteSelectedIndex, 1);
      this.state.customRouteNames.splice(
        this.state.customRouteSelectedIndex,
        1
      );
      if (flyLineXmls.length > 0) {
        this.state.customRouteSelectedIndex = 0;
        return;
      }
      this.state.customRouteSelectedIndex = null;
      this.state.currentStopNames.length = 0;
      let route = flyManager.currentRoute;
      if (route) route.clear(); //清除之前的
      this.state.routeStops = [];
      this.state.setStopName = "Stop-1";
      this.state.isSaveAutoFlag = false;
      this.state.selectedAddedStopIndex = undefined;
      this.state.addCurrentStopIndex = 0;
    },
  },

  watch: {
    cameraShow: function (val) {
      if (val) {
        this.init();
      }
    },
    stopSelected(val) {
      //各个站点事件
      flyManager && flyManager.pause();
      let index = Number(val);
      let route = flyManager.currentRoute;
      let stop = route.get(index);
      flyManager.currentStopIndex = index;
      flyManager.viewToStop(stop);
    },
    stopFlyCircle(val) {
      if (val) {
        camera.stopFlyCircle();
      } else {
        if (this.flyCirclePoint) {
          camera.flyCircle(this.flyCirclePoint);
        }
      }
    },
    circulation(val) {
      camera.flyCircleLoop = val;
    },
    speed(val) {
      camera.speedRatio = Number(val);
    },
    underground(val) {
      viewer.scene.undergroundMode = val;
      if (val) {
        viewer.scene.screenSpaceCameraController.minimumZoomDistance = Number(
          this.cameraMinimumZoomDistance
        );
      } else {
        viewer.scene.screenSpaceCameraController.minimumZoomDistance = 1;
      }
    },
    cameraMinimumZoomDistance(val) {
      viewer.scene.screenSpaceCameraController.minimumZoomDistance =
        Number(val);
    },
    SurfaceTransparency(val) {
      viewer.scene.globe.globeAlpha = parseFloat(val);
    },
    showRoute(val) {
      let route = flyManager.currentRoute;
      if (route) route.isLineVisible = val;
    },
    showStop(val) {
      let route = flyManager.currentRoute;
      if (route) route.isStopVisible = val;
    },
  },
};
</script>

<style lang="scss" scoped>
@import "camera";
</style>
