<template>
  <div class="soilMositure">
    <div class="otgCard">
      <div class="box1">
        <span class="sp1"></span><span class="sp2">样本库</span>
      </div>
      <div class="otgCardContent">
        <el-form :inline="true" :model="simpleForm" class="demo-form-inline">
          <el-form-item style="margin-left: 15px">
            <el-cascader v-model="simpleForm.sampleFun" :disabled="sampleFun !== ''" :options="funcOpt" size="mini"
              placeholder="请选择抽样方法" popper-class="cascader-popper" @change="changeSampleFun" clearable
              :show-all-levels="false"></el-cascader>
            <el-button v-if="isDeepSpace" class="edit-btn" plain size="mini" type="primary" icon="el-icon-edit-outline"
              @click="editDeepSpace"></el-button>
          </el-form-item>
          <el-form-item>
            <el-input v-model="simpleForm.sampleNum" size="mini" placeholder="请输入样本个数"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="samplesCk">确定</el-button>
          </el-form-item>
        </el-form>
        <el-table ref="multipleTable" v-loading="loading" element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :data="simpleData"
          tooltip-effect="dark" :header-cell-style="headerRowClass" style="width: 98%; margin-left: 1%; margin-top: 15px"
          highlight-current-row @current-change="tableRowClk" :stripe="true" :cell-style="tableRowClassName" height="370">
          <el-table-column label width="35">
            <template slot-scope="scope">
              <el-radio :label="scope.row" v-model="radioClkMsg"></el-radio>
            </template>
          </el-table-column>
          <el-table-column label="序号" type="index" width="70">
          </el-table-column>
          <el-table-column prop="samplesId" label="样本编号" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="纬度(°)" sortable show-overflow-tooltip>
            <template slot-scope="scope">{{
              parseFloat(scope.row.measureLat.toFixed(8))
            }}</template>
          </el-table-column>
          <el-table-column label="经度(°)" sortable>
            <template slot-scope="scope">{{
              parseFloat(scope.row.measureLong.toFixed(8))
            }}</template>
          </el-table-column>
          <el-table-column label="采样时间" sortable prop="collectDate" show-overflow-tooltip>
          </el-table-column>
          <el-table-column label="选取点纬度" prop="sameNameLat"></el-table-column>
          <el-table-column label="选取点经度" prop="sameNameLong"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope"><i class="el-icon-delete"
                @click="deleteSelected(scope.$index, simpleData)"></i></template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div class="sceneShow">
      <div class="box1">
        <span class="sp1"></span><span class="sp2">同名点选取</span>
      </div>
      <div class="sscPre">
        <div class="sscTitle">
          <div class="sscCircle"></div>
          <span>产品展示</span>
        </div>
        <div class="sscTitle">
          <div class="sscCircle"></div>
          <span>局部放大图</span>
        </div>
        <div class="sscTitle">
          <div class="sscCircle"></div>
          <span>辅助图像</span>
        </div>
      </div>
      <div class="sscPre">
        <div :class="checkRealityWait ? 'sceneShowContent onBorder' : 'sceneShowContent'" id="sceneShowContent">
          <!-- <div v-show="checkRealityWait" class="topContent">
            <span class="mapTitle">待检验正射校正产品图</span>
          </div> -->
          <div :id="checkRealityWait ? 'mapContent' : 'cesiumContent'">
            <canvas v-show="checkRealityWait" id="grid"></canvas>
            <otg-product-info v-show="screenImgStg" @removeLayer="removeLayer('far')"
              @addLayer="addLayer('far')"></otg-product-info>
            <div id="farViewer" @click="pickValueFar">
              <div v-show="checkRealityWait" class="compass">
                <img src="../../../assets/images/compass_one.svg" alt="" style="width: 100%; height: 100%;">
              </div>
              <canvas v-show="checkRealityWait" id="scaleBar"></canvas>
            </div>
          </div>
          <div v-show="checkRealityWait" class="bottomCont">
            <span>制图单位：中国科学院空天信息创新研究院</span><br />
            <span>制图日期：{{ createImgTime }}</span>
          </div>
        </div>
        <div class="sceneShowContent">
          <div id="nearViewer" style="height: 100%; width: 100%"></div>
          <otg-product-info @removeLayer="removeLayer('near')" @addLayer="addLayer('near')"></otg-product-info>
          <div class="poiCK">
            <el-button type="primary" :disabled="ckPoint" @click="ckSamePoi">选取点</el-button>
            <el-button type="primary" style="margin: 5px 0px" :disabled="savePoint" @click="saveSamePoi">保存点</el-button>
          </div>
        </div>
        <div class="sceneShowContent">
          <div style="height: 100%">
            <img id="alImg" src="static/images/otg3.png" style="height: 100%; width: 100%" alt="fzImg" />
          </div>
          <div class="imgCtrl">
            <el-radio-group v-model="imgChoose" @change="changeImg">
              <el-radio label="pointPs">点之记</el-radio><br />
              <el-radio label="nearImg" style="margin: 5px 0 5px 0">近景</el-radio><br />
              <el-radio label="farImg">远景</el-radio>
            </el-radio-group>
          </div>
        </div>
      </div>
    </div>
    <SampleSetting :stepSampling="stepSampling" @handleStepSampling="handleStepSampling"
      @handleDepthList="handleDepthList" :sampleCldFun="sampleCldFun" ref="sampleSettingPanel"></SampleSetting>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import OtgProductInfo from "@/components/otgProductInfo";
import {
  getSamplesList,
  getSampleData,
  getSamplesByLayer,
  setSamePoi,
  getProjPos,
} from "@/api/lang/pendingOrder";

import otgCesiumUtils from "@/lib/otgCesiumUtils";
import SampleSetting from "@/components/ration/sampleSetting/index.vue";
import WKT from "terraformer-wkt-parser";
import Formator from "@/mixins/formator";
import cu from "@/lib/cesiumUtils";
import { drawScaleTwo, drawGrid, getNowFormatDate } from "@/lib/utils"
export default {
  components: { Pagination, SampleSetting, OtgProductInfo },
  mixins: [Formator],
  props: {
    sampleFun: {
      require: true,
      type: String,
    },
    sampleCldFun: {
      require: false,
      type: String,
    },
    pixelFun: {
      require: true,
      type: String,
    },
    geoWorkSpace: {
      require: true,
      type: String,
    },
    geoLayerName: {
      require: true,
      type: String,
    },
    geoLayerPos: {
      require: true,
    },
    pixelNum: {
      require: true,
    },
    orderId: {
      require: true,
    },
    productSubType: {
      require: true,
    },
    projection: {
      require: true,
    },
    checkRealityWait: {
      require: true,
    }
  },
  data() {
    return {
      simpleForm: {
        sampleFun: "",
        sampleNum: "",
        pageNum: 1,
        pageSize: 13,
      },
      simpleData: [],
      loading: true,
      allSampleData: [],
      multipleSelection: [],
      simpleDataTotal: 0,
      total: 0,
      radioClkMsg: "",
      imgChoose: "pointPs",
      ckPoint: true,
      savePoint: true,
      stepSampling: false,
      collectPointSignPic: "static/images/otg3.png", //点之记
      measurePicClose: "static/images/otg2.png", //实测近景
      measurePicDistant: "static/images/otg1.png", //实测远景
      funcOpt: [],
      isDeepSpace: false,
      depthList: [],
      createImgTime: null,
      screenImgStg: true,
    };
  },
  mounted() {
    otgCesiumUtils.initCesium(["farViewer", "nearViewer"]);
    otgCesiumUtils.addlayer(this.geoWorkSpace, this.geoLayerName);
    const cLon = (
      (Number(this.geoLayerPos[0]) + Number(this.geoLayerPos[2])) /
      2
    ).toFixed(8);
    const cLat = (
      (Number(this.geoLayerPos[1]) + Number(this.geoLayerPos[3])) /
      2
    ).toFixed(8);
    otgCesiumUtils.flyToLayer(cLon, cLat);
  },
  created() {
    this.funcOpt = this.configration.funcOpt;
    this.getSqlData();
    this.initParam();
  },
  watch: {
    checkRealityWait(val) {
      if (val) {
        this.screenImgStg = false;
        this.addPointInScreenImg();
        window.selfDefine.farViewer.scene.postRender.addEventListener(this.addScale);
        window.selfDefine.farViewer.scene.postRender.addEventListener(this.addGrid);
        this.createImgTime = getNowFormatDate();
      } else {
        this.removeListener();
        this.createImgTime = null;
        this.screenImgStg = true;
      }
    }
  },
  destroyed() {
    this.removeListener();
  },
  methods: {
    addScale() {
      let barWidth = undefined;
      let currentScaleUnit = undefined;
      var geodesic = new Cesium.EllipsoidGeodesic();
      var distances = [
        1, 2, 3, 5, 10, 20, 30, 50, 100, 200, 300, 500, 1000, 2000, 3000, 5000,
        10000, 20000, 30000, 50000, 100000, 200000, 300000, 500000, 1000000,
        2000000, 3000000, 5000000, 10000000, 20000000, 30000000, 50000000,
      ];
      // Find the distance between two pixels at the bottom center of the screen.
      let scene = window.selfDefine.farViewer.scene;
      let width = scene.canvas.clientWidth;
      let height = scene.canvas.clientHeight;
      let left = scene.camera.getPickRay(
        new Cesium.Cartesian2((width / 2) | 0, height - 1)
      );
      let right = scene.camera.getPickRay(
        new Cesium.Cartesian2((1 + width / 2) | 0, height - 1)
      );
      let globe = scene.globe;
      let leftPosition = globe.pick(left, scene);
      let rightPosition = globe.pick(right, scene);
      if (!Cesium.defined(leftPosition) || !Cesium.defined(rightPosition)) {
        barWidth = undefined;
        currentScaleUnit = undefined;
        return;
      }
      let leftCartographic =
        globe.ellipsoid.cartesianToCartographic(leftPosition);
      let rightCartographic =
        globe.ellipsoid.cartesianToCartographic(rightPosition);
      geodesic.setEndPoints(leftCartographic, rightCartographic);
      let pixelDistance = geodesic.surfaceDistance;
      // Find the first distance that makes the scale bar less than 100 pixels.
      let maxBarWidth = 100;
      let distance;
      for (
        let i = distances.length - 1;
        !Cesium.defined(distance) && i >= 0;
        --i
      ) {
        if (distances[i] / pixelDistance < maxBarWidth) {
          distance = distances[i];
        }
      }
      if (Cesium.defined(distance)) {
        currentScaleUnit =
          distance >= 1000
            ? "km" : "m";
        barWidth = distance >= 1000
          ? (distance / 1000).toString()
          : distance.toString();
      } else {
        barWidth = undefined;
        currentScaleUnit = undefined;
      }
      drawScaleTwo(barWidth, currentScaleUnit)
    },
    addGrid() {
      const cesiumExtent = window.selfDefine.farViewer.camera.computeViewRectangle();
      const params = {};
      params.xmax = Cesium.Math.toDegrees(cesiumExtent.east);
      params.ymax = Cesium.Math.toDegrees(cesiumExtent.north);
      params.xmin = Cesium.Math.toDegrees(cesiumExtent.west);
      params.ymin = Cesium.Math.toDegrees(cesiumExtent.south);
      drawGrid(6, 6, 'farViewer', [params.xmax, params.ymax, params.xmin, params.ymin])
    },
    removeListener() {
      window.selfDefine.farViewer.scene.postRender.removeEventListener(this.addScale);
      window.selfDefine.farViewer.scene.postRender.removeEventListener(this.addGrid);
    },
    addPointInScreenImg() {
      const dl = this.multipleSelection;
      for (let i in dl) {
        const lon = dl[i].measureLong,
          lat = dl[i].measureLat,
          alt = 10;
        otgCesiumUtils.addPointToViewer(lon, lat, alt);
      }
    },
    handleStepSampling(newVal) {
      this.stepSampling = newVal;
    },
    handleDepthList(newVal) {
      this.depthList = newVal;
    },
    editDeepSpace() {
      this.stepSampling = true;
    },
    initParam() {
      if (this.sampleCldFun) {
        this.simpleForm.sampleFun = new Array(
          this.sampleFun,
          this.sampleCldFun
        );
      } else {
        this.simpleForm.sampleFun = new Array(this.sampleFun);
      }
      const ssf = Number(this.simpleForm.sampleFun[0]);
      if (
        this.simpleForm.sampleFun.length >= 1 &&
        ssf === 2 &&
        Number(this.simpleForm.sampleFun[1]) === 0
      ) {
        this.isDeepSpace = true;
      } else {
        this.isDeepSpace = false;
      }
    },
    changeSampleFun(sfVal) {
      if (Array.isArray(sfVal)) {
        const ssf = Number(sfVal[0]);
        if (sfVal.length >= 1 && ssf === 2 && Number(sfVal[1]) === 0) {
          this.isDeepSpace = true;
        } else {
          this.isDeepSpace = false;
        }
      }
    },
    samplesCk() {
      const self = this;
      if (self.simpleForm.sampleFun[0] === "") {
        self.$message.error("请选择抽样方法");
        return false;
      }
      const ssf = self.simpleForm.sampleFun,
        st = self.simpleDataTotal,
        ssn = self.simpleForm.sampleNum;
      if (ssn == "") {
        this.$message.error("请选择抽样个数");
        this.getSqlData();
        return false;
      }
      if (ssn > st) {
        this.$message.error("抽样数不可大于总样本数量");
        return false;
      }
      if (ssn < 0) {
        this.$message.error("样本个数不可为负数");
        return false;
      }
      if (Number(ssf[0]) === 2) {
        const stepSampParams = self.$refs.sampleSettingPanel;
        const hierarchyVal = ssf[1];
        if (hierarchyVal === "" || hierarchyVal === undefined) {
          self.stepSampling = true;
          return false;
        }
        const ssForm = new FormData();
        ssForm.append("samplesList", JSON.stringify(this.allSampleData));
        ssForm.append("stepType", Number(hierarchyVal));
        ssForm.append("orderID", this.orderId);
        if (hierarchyVal === "0") {
          const depthList = this.depthList;
          ssForm.append("condition", JSON.stringify(depthList));
        } else if (hierarchyVal === "2") {
          const jsonContent = JSON.parse(stepSampParams.jsonContent);
          const jg = jsonContent.geometries;
          const newPolygon = [];
          for (let i in jg) {
            const jsonContentWKT = WKT.convert(jg[i]);
            newPolygon.push({ coordinates: jsonContentWKT });
          }
          ssForm.append("condition", JSON.stringify(newPolygon));
        }
        ssForm.append("splCount", ssn);
        getSamplesByLayer(ssForm).then((res) => {
          if (res.length === 0 || res == []) {
            self.multipleSelection = self.simpleData = [];
            cu.removePoint();
            this.$message.error("当前分层设置返回列表为空");
            return false;
          } else {
            const dl = [];
            for (let i in res) {
              const ri = res[i];
              for (let j in ri) {
                dl.push(ri[j]);
              }
            }
            self.multipleSelection = self.simpleData = dl;
            cu.removePoint();
            for (let i in dl) {
              cu.addPoint(dl[i].lon, dl[i].lat, dl[i].alt);
            }
          }
        });
      } else {
        // console.log("111111", st);
        const spFrom = new FormData();
        spFrom.append("sampleFun", Number(ssf[0])); //抽样方法
        spFrom.append("minNum", 0);
        spFrom.append("MaxNum", st - 1); //样本总数
        spFrom.append("splCount", ssn); //抽样个数
        getSampleData(spFrom).then((res) => {
          const dl = [];
          for (const i in res) {
            dl.push(self.allSampleData[res[i]]);
          }
          self.multipleSelection = self.simpleData = dl;
        });
      }
    },
    headerRowClass() {
      return "background:#E4E9F1; font-weight: bold;color: #645f5f;text-align:center";
    },
    tableRowClassName({ rowIndex }) {
      if ((rowIndex + 1) % 2 !== 0) {
        return "background:#F5F7FA;text-align:center";
      } else {
        return "background:#FFFFFF;text-align:center";
      }
    },
    tableRowClk(row) {
      this.radioClkMsg = row;
      otgCesiumUtils.removePoint();
      const lon = row.measureLong,
        lat = row.measureLat,
        alt = 10;
      otgCesiumUtils.addPointToFarViewer(lon, lat, alt);
      otgCesiumUtils.addPointToNearViewer(lon, lat, alt);
      this.ckPoint = false;
      const cus = this.configration.urlprefix.samePoiImgsUrl;
      if (row.collectPointSignPic !== null) {
        // console.log("111111", row.collectPointSignPic);
        this.collectPointSignPic = row.collectPointSignPic;
        var alImgDom = document.getElementById("alImg");
        alImgDom.src = this.collectPointSignPic;
      }
      if (row.measurePicClose !== null)
        this.measurePicClose = row.measurePicClose;
      if (row.measurePicDistant !== null)
        this.measurePicDistant = row.measurePicDistant;
    },
    // 选择相同的点
    ckSamePoi() {
      otgCesiumUtils.drawPoint((point) => {
        this.radioClkMsg.sameNameLong = Number(point[0]);
        this.radioClkMsg.sameNameLat = Number(point[1]);
        this.radioClkMsg.sameAlt = Number(point[2]);
      });
      this.savePoint = false;
    },
    // 保存相同的点
    saveSamePoi() {
      const rc = this.radioClkMsg;
      const samePoi = new FormData();
      samePoi.append("landDataAssociatedID", rc.id);
      samePoi.append("sameNamePointLong", rc.sameNameLong);
      samePoi.append("sameNamePointLat", rc.sameNameLat);
      getProjPos({
        project: this.projection,
        lon: rc.sameNameLong,
        lat: rc.sameNameLat,
      }).then((res) => {
        if (res.code === 200) {
          samePoi.append("projectionSameNamePointLon", rc.sameNameLong);
          samePoi.append("projectionSameNamePointLat", rc.sameNameLat);
          setSamePoi(samePoi).then((res) => {
            if (res.code === 200) {
              this.$message({
                message: "同名点保存成功",
                type: "success",
              });
              this.ckPoint = true;
              this.savePoint = true;
              otgCesiumUtils.stopDrowPoi();
            }
          });
        }
      });
    },
    changeImg(val) {
      var alImgDom = document.getElementById("alImg");
      switch (val) {
        case "pointPs":
          alImgDom.src = this.collectPointSignPic;
          break;
        case "nearImg":
          alImgDom.src = this.measurePicClose;
          break;
        case "farImg":
          alImgDom.src = this.measurePicDistant;
      }
    },
    getSqlData() {
      getSamplesList(this.orderId).then((res) => {
        // console.log("111111111", res);
        if (res.code == 200) {
          this.multipleSelection =
            this.allSampleData =
            this.simpleData =
            res.data.list;
          this.loading = false;
          this.$refs.multipleTable.toggleAllSelection();
          let min = Number.MAX_SAFE_INTEGER;
          let max = Number.MIN_SAFE_INTEGER;
          this.$store.commit("setAltRange", null);
          this.allSampleData.forEach((k, v) => {
            k.dataTime = this.formatDatetime(k.dataTime);
            if (!k.alt) {
              min = 0, max = 0;
            } else {
              min = min > k.alt ? k.alt : min;
              max = max < k.alt ? k.alt : max;
            }
          });
          if (this.allSampleData.length > 0) {
            this.$store.commit("setAltRange", min + "," + (max + 1));
          }
          this.simpleDataTotal = this.total = res.data.list.length;
        }
      });
    },
    deleteSelected(index, simpleData) {
      simpleData.splice(index, 1);
    },
    pickValueFar() {
      otgCesiumUtils.handleClickFar();
    },
    pickValueNear() {
      otgCesiumUtils.handleClickNear();
    },
    addLayer(layerType) {
      if (layerType === "far")
        otgCesiumUtils.addFarlayer(this.geoWorkSpace, this.geoLayerName);
      else if (layerType === "near")
        otgCesiumUtils.addNearlayer(this.geoWorkSpace, this.geoLayerName);
    },
    removeLayer(layerType) {
      if (layerType === "far") otgCesiumUtils.clearFarLayers();
      else if (layerType === "near") otgCesiumUtils.clearNearLayers();
    },
  },
};
</script>

<style scoped lang="less">
.otgCard {
  display: inline-block;
  vertical-align: top;
  width: 100%;
  background-color: white;
  font-size: 20px;
  margin-top: 20px;
}

/deep/.otgCard .el-form-item {
  margin-bottom: 0;
}

.otgCardContent {
  margin: 15px;
  height: 450px;
}

.sceneShow {
  width: 100%;
  background-color: white;
  margin-top: 20px;
  padding-bottom: 15px;
}

.sscPre {
  display: flex;
  align-items: center;
  justify-content: center;
}

.sceneShowContent {
  margin: 5px 15px 0 15px;
  width: 33%;
  height: 360px;
  // background-color: rgb(110, 110, 207);
  position: relative;

  .topContent {
    height: 23px;
    width: 100%;
    text-align: center;
    line-height: 23px;

    .mapTitle {
      font-size: 20px;
      font-weight: bold;
    }
  }

  #mapContent {
    height: calc(100% - 100px);
    position: relative;
    padding-left: 70px;
    padding-top: 30px;

    #grid {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      left: 0;
    }

    .compass {
      width: 50px;
      height: 50px;
      position: absolute;
      top: 10px;
      right: 20px;
      z-index: 2;
    }

    #scaleBar {
      width: 200px;
      height: 40px;
      position: absolute;
      bottom: 10px;
      left: 20px;
      z-index: 2;
    }
  }

  #cesiumContent {
    height: 100%;
    position: relative;
  }

  #farViewer {
    // width: calc(100% - 5px);
    width: 100%;
    // height: calc(100% - 5px);
    height: 100%;
    overflow: hidden;
    position: relative;
    // border: 2px solid black;
  }

  .bottomCont {
    height: 60px;
    text-align: left;
    width: fit-content;
    transform: translateX(-100%);
    margin-left: 100%;
    white-space: nowrap;
  }
}

.onBorder {
  border: 1px solid;
  background-color: #fff;
}

.imgCtrl {
  position: absolute;
  bottom: 3px;
  left: 3px;
  width: 90px;
  height: 70px;
  background-color: #aaaaaa;
  padding: 4px 0 0 10px;
}

.poiCK {
  position: absolute;
  bottom: 1px;
  width: 90px;
  height: 60px;
  background-color: #aaaaaa;
  padding: 4px 0 0 10px;
}

.sscTitle {
  margin: 15px 15px 0 15px;
  width: 33%;
  height: 30px;
  display: flex;
  align-items: center;
  font-weight: bold;
  color: gray;
}

.sscCircle {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  background-color: #0072e5;
  margin: 0 4px 0 4px;
}

.box1 {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid rgb(205, 205, 205, 0.5);
}

.sp1 {
  display: inline-block;
  width: 7px;
  height: 26px;
  background-color: #354595;
  vertical-align: top;
  // position: absolute;
  margin-left: 20px;
  margin-top: 8px;
}

.sp2 {
  margin-left: 10px;
  font-size: 20px;
  font-weight: 700;
  color: #354595;
  vertical-align: top;
}

// 分层抽样弹出框设置
/deep/.sampleFunParam .el-upload-dragger .el-icon-upload {
  margin: 0;
  line-height: 30px;
  font-size: 20px;
  color: black;
}

.sampleFunParam .upload-demo {
  display: inline-block;
}

/deep/.sampleFunParam .el-upload-dragger {
  width: 150px;
  height: 35px;
  margin-left: 15px;
  margin-top: 20px;
  border: 1px solid #d9d9d9;
}

/deep/.sampleFunParam .el-dialog__body {
  padding: 20px 10px;
  text-align: center;
}

.edit-btn {
  margin-left: 15px;
}
</style>
