<template>
  <div
    class="ZTGlobal"
    style="width: 100%; padding: 1rem 1rem 0rem 1rem; color: white"
  >
    <el-row :gutter="10">
      <el-col :span="24">
        <div class="titleHeader">
          <el-switch
            v-model="isNightscaoe"
            active-text="开启夜景"
            inactive-text="关闭夜景"
            @change="handleChange"
          >
          </el-switch>
          <el-tooltip content="点击后可直接在光源参数中保存" placement="top">
            <el-button type="primary" size="mini" @click="openDgyAddVisibility"
              >添加光源</el-button
            >
          </el-tooltip>

          <el-button type="danger" size="mini" @click="dgyremove"
            >删除光源</el-button
          >
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="10">
      <el-col :span="10">
        光源列表：
        <el-row>
          <el-col :span="24" style="border: 1px solid #fff">
            <el-table
              ref="dgytable"
              :show-header="false"
              :data="gyTableData"
              :highlight-current-row="true"
              @current-change="handleCurrentChange"
              style="width: 100%"
            >
              <el-table-column
                prop="lightname"
                label="光源名称"
              ></el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-col>
      <el-col :span="14">
        光源参数：
        <el-row>
          <el-col :span="24" style="border: 1px solid #fff">
            <el-form
              ref="dgyform"
              :model="dgyform"
              label-width="80px"
              style="padding: 1rem 1rem 0rem 1rem"
            >
              <el-form-item label="光源名称">
                <el-input
                  size="mini"
                  v-model="dgyform.lightname"
                  placeholder="请输入光源名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="光源类型">
                <el-select
                  size="mini"
                  v-model="dgyform.lighttype"
                  placeholder="请选择光源类型"
                >
                  <el-option label="点光源" value="点光源"></el-option>
                  <el-option label="聚光灯" value="聚光灯"></el-option>
                  <el-option label="直射光" value="直射光"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="光源颜色">
                <el-color-picker
                  size="mini"
                  v-model="dgyform.color"
                ></el-color-picker>
                <el-button size="mini" @click="addPoint"
                  >添加光源位置</el-button
                >
              </el-form-item>
              <!-- <el-form-item label="X坐标(度)">
                <el-input-number
                  size="mini"
                  v-model="dgyform.location.x"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="Y坐标(度)">
                <el-input-number
                  size="mini"
                  v-model="dgyform.location.y"
                ></el-input-number>
              </el-form-item>-->
              <!-- <el-form-item label="光源高度">
                <el-input-number
                  size="mini"
                  v-model="dgyform.location.z"
                ></el-input-number>
              </el-form-item> -->
              <el-form-item
                label="扩散距离"
                v-if="dgyform.lighttype != '直射光'"
              >
                <el-input-number
                  size="mini"
                  v-model="dgyform.cutoffdistance"
                  :min="0"
                  :max="10000"
                ></el-input-number>
              </el-form-item>
              <el-form-item
                label="衰减因子"
                v-if="dgyform.lighttype != '直射光'"
              >
                <el-input-number
                  size="mini"
                  v-model="dgyform.decay"
                  :min="0"
                  :max="10000"
                ></el-input-number>
              </el-form-item>
              <el-form-item label="光源强度">
                <el-input-number
                  size="mini"
                  v-model="dgyform.intensity"
                  :min="0"
                  :max="10000"
                ></el-input-number>
              </el-form-item>
            </el-form>
            <div class="SaveCenter">
              <el-button size="mini" type="primary" @click="onSubmit"
                >保存</el-button
              >
              <el-button size="mini" @click="resetForm">取消</el-button>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { v4 as uuidv4 } from "uuid";
import Nightscape from "@/components/Combinations/NightscapeAnalysis/index.js";
import {
  listZtLightList,
  addZtLightList,
  updateZtLightList,
  delZtLightList,
} from "@/api/zt/ztApi.js";
let entityPointLightPairs = new Map(),
  entitySpotLightPairs = new Map(),
  entityDirectionalLightPairs = new Map(),
  pointLightSourceDrawHandler = null,
  spotOrDirectionalLightSourceDrawHandler = null,
  spotOrDirectionalLightSourceCountHandler = null,
  spotOrDirectionalLightSourceAdding = false,
  spotOrDirectionalLightPositions = [];

export default {
  data() {
    return {
      tooltip: createTooltip(document.body),
      sharedState: store.state,
      isNightscaoe: false,
      gyTableData: [],
      dgyform: {
        id: "",
        lightname: "",
        lighttype: "点光源",
        color: "#409EFF",
        cutoffdistance: 300,
        decay: 5,
        intensity: 5,
        // location: {
        //   x: 0,
        //   y: 0,
        //   z: 0,
        // },
      },
    };
  },
  props: {
    info: {
      type: Object,
      default: () => {
        return {};
      },
    },
    layerid: {
      type: String,
      default: "",
    },
    lydata: {
      type: Object,
      default: () => {
        return {};
      },
    },
    lyoption: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  computed: {},
  mounted() {
    this.init();
  },
  methods: {
    handleChange() {
      if (this.isNightscaoe) {
        this.startNight(true);
      } else {
        this.startNight(false);
      }
    },

    openDgyAddVisibility() {
      this.resetForm();
    },

    async init() {
      this.hyp = new Cesium.HypsometricSetting();
      this.startNight(false);
      debugger;
      await this.getModelLightData();
    },
    //获取模型灯光数据
    async getModelLightData() {
      let rData = await listZtLightList({
        isModelAssociated: true,
        modelId: this.info.id,
      });
      if (rData.code == 200) {
        rData.rows.forEach((element) => {
          element.location = JSON.parse(element.location);
        });
        this.gyTableData = rData.rows;
        if (this.isNightscaoe) {
          this.addModelLight();
        }
      }
    },

    //夜景开关
    startNight(isNight) {
      if (isNight) {
        Nightscape.openNightSwitch();
        this.addModelLight();
      } else {
        Nightscape.closNightSwitch();
      }
    },
    // 添加模型下的光源
    addModelLight() {
      this.clearLightSource();
      this.gyTableData.forEach((element) => {
        this.addLightSource(element);
      });
    },

    async onSubmit() {
      //更新
      if (this.dgyform.id) {
        // let gydata = this.gyTableData.find((c) => c.id == this.dgyform.id);
        // let data = JSON.parse(JSON.stringify(this.dgyform));
        // gydata.lightname = data.lightname;
        // gydata.color = data.color;
        // gydata.cutoffdistance = data.cutoffdistance;
        // gydata.decay = data.decay;
        // gydata.intensity = data.intensity;
        // gydata.location = data.location;
        // gydata.LightSource = this.dgyform.LightSource;
        this.dgyform.location = JSON.stringify(this.dgyform.location);
        var rownum = await updateZtLightList(this.dgyform);
        this.resetForm();
        if (rownum.code == 200) {
          this.$message({
            message: "修改成功",
            type: "success",
          });
          //更新列表及光源
          this.getModelLightData();
        }
      }
      //添加
      else {
        debugger;
        this.dgyform.id = uuidv4();
        // let data = JSON.parse(JSON.stringify(this.dgyform));
        // data.LightSource = this.dgyform.LightSource;
        // this.gyTableData.push(this.dgyform);
        this.dgyform.location = JSON.stringify(this.dgyform.location);
        this.dgyform.isModelAssociated = true;
        this.dgyform.modelId = this.info.id;
        var rownum = await addZtLightList(this.dgyform);
        this.resetForm();
        if (rownum.code == 200) {
          this.$message({
            message: "添加成功",
            type: "success",
          });
          //更新列表及光源
          this.getModelLightData();
        }
      }

      // this.clearLightSource(false);
    },
    //清空from
    resetForm() {
      this.dgyform = {
        id: "",
        lightname: "",
        lighttype: "点光源",
        color: "#409EFF",
        cutoffdistance: 300,
        decay: 5,
        intensity: 5,
        location: {},
        LightSource: null,
      };
    },
    //删除添加的光源
    async dgyremove() {
      let that = this;
      await delZtLightList(that.currentRow.id);
      scene.removeLightSource(that.currentRow.LightSource);
      that.resetForm();
      //更新列表及光源
      that.getModelLightData();
    },
    //点光源表选中
    handleCurrentChange(row) {
      this.currentRow = row;

      this.clearLightSource();

      if (row) {
        let data = JSON.parse(JSON.stringify(row));
        this.dgyform = data;
        this.dgyform.LightSource = row.LightSource;
      }
    },
    addPoint() {
      switch (this.dgyform.lighttype) {
        case "点光源":
          if (pointLightSourceDrawHandler) {
            pointLightSourceDrawHandler.clear();
            pointLightSourceDrawHandler = null;
          }
          this.initPointLightSourceDrawHandler();
          pointLightSourceDrawHandler.activate();
          break;
        case "聚光灯":
        case "直射光":
          if (spotOrDirectionalLightSourceDrawHandler) {
            spotOrDirectionalLightSourceDrawHandler.clear();
            spotOrDirectionalLightSourceDrawHandler = null;
            spotOrDirectionalLightPositions = [];
            spotOrDirectionalLightSourceDrawHandler.deactivate();
          }
          if (spotOrDirectionalLightSourceCountHandler) {
            spotOrDirectionalLightSourceCountHandler.destroy();
            spotOrDirectionalLightSourceCountHandler = undefined;
          }
          this.initSpotOrDirectionalLightSourceDrawHandler();
          spotOrDirectionalLightSourceAdding = true;
          spotOrDirectionalLightSourceDrawHandler.activate();
          break;
        default:
          break;
      }
    },
    initPointLightSourceDrawHandler() {
      let that = this;
      this.clearLightSource();
      pointLightSourceDrawHandler = new Cesium.DrawHandler(
        viewer,
        Cesium.DrawMode.Point
      );
      pointLightSourceDrawHandler.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");
        }
      });
      pointLightSourceDrawHandler.movingEvt.addEventListener(
        (windowPosition) => {
          that.tooltip.showAt(
            windowPosition,
            `<p>${Resource.clickToConfirmThePositionOfTheLightSource}</p><p>${Resource.clickLightChangeAttributes}</p>`
          );
        }
      );
      pointLightSourceDrawHandler.drawEvt.addEventListener((result) => {
        let xyz = result.object.position;
        let location = this.cartesianToWgs84(xyz.x, xyz.y, xyz.z);
        this.dgyform.location = location;
        let option = {
          color: Cesium.Color.fromCssColorString(this.dgyform.color),
          cutoffDistance: Number(this.dgyform.cutoffdistance),
          decay: Number(this.dgyform.decay),
          intensity: Number(this.dgyform.intensity),
        };
        let pointLight = new Cesium.PointLight(
          new Cesium.Cartesian3.fromDegrees(location.x, location.y, location.z),
          option
        );
        scene.addLightSource(pointLight);
        if (this.dgyform.LightSource) {
          scene.removeLightSource(this.dgyform.LightSource);
        }
        this.dgyform.LightSource = pointLight;
        let entityAsKey = viewer.entities.add({
          id: "point-light-" + new Date().getTime(),
          position: location,
          billboard: {
            image: "@/../static/images/lightSource/pointLight.png",
            scaleByDistance: new Cesium.NearFarScalar(10, 1.0, 1000, 0.1),
            disableDepthTestDistance: Number.POSITIVE_INFINITY, // 关闭深度检测，使billboard不至于被裁剪
          },
        });
        console.log(entityPointLightPairs);
        entityPointLightPairs.set(entityAsKey, pointLight);
        pointLightSourceDrawHandler.clear();
        pointLightSourceDrawHandler = null;
        this.tooltip.setVisible(false);
      });
    },
    initSpotOrDirectionalLightSourceDrawHandler() {
      let that = this;
      that.clearLightSource();
      spotOrDirectionalLightSourceDrawHandler = new Cesium.DrawHandler(
        viewer,
        Cesium.DrawMode.Line
      );
      spotOrDirectionalLightSourceCountHandler =
        new Cesium.ScreenSpaceEventHandler(scene.canvas);
      spotOrDirectionalLightSourceDrawHandler.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");
          }
        }
      );
      spotOrDirectionalLightSourceDrawHandler.movingEvt.addEventListener(
        (windowPosition) => {
          this.tooltip.showAt(
            windowPosition,
            `<p>${Resource.ClickLineDirectionLightSource}</p><p>${Resource.clickLightChangeAttributes}</p>`
          );
        }
      );
      spotOrDirectionalLightSourceDrawHandler.drawEvt.addEventListener(
        (result) => {
          let positions = (result.object && result.object.positions) || result;
          if (positions.length !== 2) {
            return;
          }
          let locations = [];
          locations.push(
            this.cartesianToWgs84(
              positions[0].x,
              positions[0].y,
              positions[0].z
            )
          );
          locations.push(
            this.cartesianToWgs84(
              positions[1].x,
              positions[1].y,
              positions[1].z
            )
          );
          this.dgyform.location = locations;
          if (that.dgyform.lighttype === "聚光灯") {
            let spotLightOptions = {
              color: Cesium.Color.fromCssColorString(this.dgyform.color),
              distance: Number(this.dgyform.cutoffdistance),
              decay: Number(this.dgyform.decay),
              intensity: Number(this.dgyform.intensity),
              angle: Cesium.Math.toRadians(Number(30)),
            };
            let spotLight = new Cesium.SpotLight(
              positions[0],
              positions[1],
              spotLightOptions
            );
            scene.addLightSource(spotLight);
            if (this.dgyform.LightSource) {
              scene.removeLightSource(this.dgyform.LightSource);
            }
            this.dgyform.LightSource = spotLight;
            let entityAsKey = viewer.entities.add({
              id: "spot-light-" + new Date().getTime(),
              position: positions[0],
              billboard: {
                image: "@/../static/images/lightSource/spotLight.png",
                scaleByDistance: new Cesium.NearFarScalar(10, 1.0, 1000, 0.1), // 按照距离调整图片的大小
                disableDepthTestDistance: Number.POSITIVE_INFINITY, // 关闭深度检测，使billboard不至于被裁剪
              },
            });
            entitySpotLightPairs.set(entityAsKey, spotLight);
          } else if (that.dgyform.lighttype === "直射光") {
            let directionalLightOptions = {
              targetPosition: positions[1],
              color: Cesium.Color.fromCssColorString(this.dgyform.color),
              intensity: Number(this.dgyform.intensity),
            };
            let directionalLight = new Cesium.DirectionalLight(
              positions[0],
              directionalLightOptions
            );
            scene.addLightSource(directionalLight);
            if (this.dgyform.LightSource) {
              scene.removeLightSource(this.dgyform.LightSource);
            }
            this.dgyform.LightSource = directionalLight;
            let entityAsKey = viewer.entities.add({
              id: "directional-light-" + new Date().getTime(),
              position: positions[0],
              billboard: {
                image: "@/../static/images/lightSource/directionalLight.png",
                scaleByDistance: new Cesium.NearFarScalar(10, 1.0, 1000, 0.1),
                disableDepthTestDistance: Number.POSITIVE_INFINITY, // 关闭深度检测，使billboard不至于被裁剪
              },
            });
            entityDirectionalLightPairs.set(entityAsKey, directionalLight);
          }
          spotOrDirectionalLightPositions = [];
          spotOrDirectionalLightSourceDrawHandler.clear();
          spotOrDirectionalLightSourceDrawHandler = null;
          this.tooltip.setVisible(false);
        }
      );

      spotOrDirectionalLightSourceCountHandler.setInputAction(function (e) {
        if (spotOrDirectionalLightSourceAdding) {
          spotOrDirectionalLightPositions.push(scene.pickPosition(e.position));
          if (spotOrDirectionalLightPositions.length === 2) {
            if (spotOrDirectionalLightSourceCountHandler) {
              spotOrDirectionalLightSourceCountHandler.destroy();
              spotOrDirectionalLightSourceCountHandler = undefined;
            }
            spotOrDirectionalLightSourceDrawHandler.deactivate();
            spotOrDirectionalLightSourceAdding = false;
            spotOrDirectionalLightSourceDrawHandler.drawEvt.raiseEvent(
              spotOrDirectionalLightPositions
            );
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    addLightSource(gyData) {
      switch (gyData.lighttype) {
        case "点光源":
          let option = {
            color: Cesium.Color.fromCssColorString(gyData.color),
            cutoffDistance: Number(gyData.cutoffdistance),
            decay: Number(gyData.decay),
            intensity: Number(gyData.intensity),
          };
          let pointLight = new Cesium.PointLight(
            new Cesium.Cartesian3.fromDegrees(
              gyData.location.x,
              gyData.location.y,
              gyData.location.z
            ),
            option
          );
          scene.addLightSource(pointLight);
          gyData.LightSource = pointLight;
          break;
        case "聚光灯":
          let spotLightOptions = {
            color: Cesium.Color.fromCssColorString(gyData.color),
            distance: Number(gyData.cutoffdistance),
            decay: Number(gyData.decay),
            intensity: Number(gyData.intensity),
            angle: Cesium.Math.toRadians(Number(30)),
          };
          let spotLight = new Cesium.SpotLight(
            new Cesium.Cartesian3.fromDegrees(
              gyData.location[0].x,
              gyData.location[0].y,
              gyData.location[0].z
            ),
            new Cesium.Cartesian3.fromDegrees(
              gyData.location[1].x,
              gyData.location[1].y,
              gyData.location[1].z
            ),
            spotLightOptions
          );
          scene.addLightSource(spotLight);
          gyData.LightSource = spotLight;
          break;
        case "直射光":
          let directionalLightOptions = {
            targetPosition: new Cesium.Cartesian3.fromDegrees(
              gyData.location[1].x,
              gyData.location[1].y,
              gyData.location[1].z
            ),
            color: Cesium.Color.fromCssColorString(gyData.color),
            intensity: Number(gyData.intensity),
          };
          let directionalLight = new Cesium.DirectionalLight(
            new Cesium.Cartesian3.fromDegrees(
              gyData.location[0].x,
              gyData.location[0].y,
              gyData.location[0].z
            ),
            directionalLightOptions
          );
          scene.addLightSource(directionalLight);
          gyData.LightSource = directionalLight;
          break;
        default:
          break;
      }
    },
    /**
     * 删除灯光
     * @param isRemoveLightSource 是否删除临时灯光
     */
    clearLightSource(isRemoveLightSource = true) {
      for (let key of entityPointLightPairs.keys()) {
        viewer.entities.remove(key);
        if (isRemoveLightSource)
          scene.removeLightSource(entityPointLightPairs.get(key));
      }
      entityPointLightPairs.clear();

      for (let key of entitySpotLightPairs.keys()) {
        viewer.entities.remove(key);
        if (isRemoveLightSource)
          scene.removeLightSource(entitySpotLightPairs.get(key));
      }
      entitySpotLightPairs.clear();

      for (let key of entityDirectionalLightPairs.keys()) {
        viewer.entities.remove(key);
        if (isRemoveLightSource)
          scene.removeLightSource(entityDirectionalLightPairs.get(key));
      }
      entityDirectionalLightPairs.clear();
    },
    cartesianToWgs84(x, y, z) {
      var scene = viewer.scene;
      var positionCartesian = new Cesium.Cartesian3(x, y, z);
      var positionWGS84 =
        scene.globe.ellipsoid.cartesianToCartographic(positionCartesian);
      var longitude = Cesium.Math.toDegrees(positionWGS84.longitude);
      var latitude = Cesium.Math.toDegrees(positionWGS84.latitude);
      var height = positionWGS84.height;
      console.log(longitude + "," + latitude + "," + height);
      debugger;
      return { x: longitude, y: latitude, z: height };
    },
  },
  watch: {
    "dgyform.color": function (val, oldVal) {
      if (this.dgyform && this.dgyform.LightSource) {
        let color = Cesium.Color.fromCssColorString(val);
        this.dgyform.LightSource.color = color;
      }
    },
    "dgyform.cutoffdistance": function (val, oldVal) {
      if (this.dgyform && this.dgyform.LightSource) {
        this.dgyform.LightSource.cutoffDistance = Number(val);
      }
    },
    "dgyform.decay": function (val, oldVal) {
      if (this.dgyform && this.dgyform.LightSource) {
        this.dgyform.LightSource.decay = Number(val);
      }
    },
    "dgyform.intensity": function (val, oldVal) {
      if (this.dgyform && this.dgyform.LightSource) {
        this.dgyform.LightSource.intensity = Number(val);
      }
    },
  },
  beforeDestroy() {
    this.clearLightSource();
    this.startNight(false);
  },
};
</script>
<style lang="scss">
@import "@/../../zt.scss";
</style>
<style lang="scss" scoped>
.el-card {
  border: 0px solid #02a7f0;
}

.el-form-item {
  margin-bottom: 0;
}
</style>
