<template>
  <div class="map-range">
    <div class="fwlxrange">
      <div :class="model.xzmj == 0 ? 'pointer' : ''" @click="drawMap">
        <el-button plain icon="edit-pen" size="mini">绘制</el-button>
      </div>
      <el-upload
        class="upload-demo"
        :on-change="handleChange"
        :auto-upload="false"
        :show-file-list="false"
        :file-list="fileList"
        :limit="1"
        accept=".zip"
      >
        <el-button class="upload-btn" icon="Upload" size="mini">导入</el-button>
      </el-upload>
      <!-- <div class="clear" @click="clearAll">清除</div> -->
      <div>
        <el-button size="mini" @click="changePatches">选择图斑</el-button>
      </div>
      <div>
        <el-button size="mini" @click="clearAll">清除</el-button>
      </div>
    </div>
    <div v-if="type != 'cutfill'">
      <span v-if="model.xzmj != 0">{{ model.xzmj }} 亩</span>
      <el-tooltip
        v-if="fileList.length > 0"
        :content="fileList[0].name"
        placement="bottom-start"
      >
        <span class="title-item" style="display: inline-block; width: 100%">{{
          fileList[0].name
        }}</span>
      </el-tooltip>
    </div>
    <el-dialog
      title="选择图斑"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <div class="gdzl">
        <div class="el-col headerSelect">
          <el-select
            v-model="yearsVal"
            placeholder="请选择"
            @change="yearsChange"
            size="mini"
          >
            <el-option
              v-for="item in yearsOpt"
              :key="item.quarter"
              :label="item.quarter"
              :value="item"
            >
            </el-option>
          </el-select>
          <el-cascader
            v-model="updateObj.region"
            :show-all-levels="false"
            :options="store.state.region_tree"
            @change="regionChange1"
            placeholder="行政区"
            size="mini"
            :props="{
              checkStrictly: true,
              expandTrigger: 'hover',
              emitPath: false,
            }"
          ></el-cascader>
          <el-select
            v-model="monitorVal"
            placeholder="请选择"
            @change="typeChange"
            clearable
            size="mini"
          >
            <el-option
              v-for="item in monitorOpt"
              :key="item.dictCode"
              :label="item.dictValue"
              :value="item.dictLabel"
            >
            </el-option>
          </el-select>
        </div>
        <div class="el-col headerInp">
          <el-input
            v-model="input"
            placeholder="请输入监测编号搜索"
            @keyup.enter.native="initNew"
          ></el-input>
          <el-button plain icon="edit-pen" size="mini">查询</el-button>
        </div>
        <el-table
          ref="singleTable"
          :data="active_dableData"
          style="width: 100%"
          height="44vh"
          @selection-change="handleSelectionChange"
          :header-cell-style="{
            background: 'rgba(10, 25, 38, 0.6)',
            color: '#66b1ff',
            fontSize: '14px',
            fontFamily: 'Microsoft YaHei',
            fontWeight: '400',
          }"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column type="index" align="center" width="50">
          </el-table-column>
          <el-table-column
            prop="jcbh"
            label="监测编号"
            align="center"
            width="220"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="jcmj"
            label="监测面积（亩）"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <!-- <el-table-column
            prop="regioncode"
            label="地区编号"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            prop="xmc"
            label="所属区县"
            align="center"
            show-overflow-tooltip
          >
          </el-table-column> -->
          <!-- <el-table-column fixed="right" label="操作" width="90" align="center">
            <template slot-scope="scope">
              <el-button
                @click="handleClick(scope.row)"
                type="text"
                size="small"
                >定位</el-button
              >
              <el-button
                type="text"
                size="small"
                @click="handleDetails(scope.row)"
                >详情</el-button
              >
            </template>
          </el-table-column> -->
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="creatTb">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { ShapeUpload, ShapeUploadV1 } from "@/api/ghss/hgxfx.js";
import { ElMessage } from "element-ui";
import { GetXzqhTree } from "@/api/map";
import {
  GetDateList,
  CodeList,
  JscQueryList,
  JctbList,
  getJctbInfo,
} from "@/api/ghss/jctb.js";
// import { polygon } from "@turf/turf";
import * as turf from "@turf/turf";
import parse from "wellknown";
import { loadGeoJSON } from "@/utils/MapHelper/help.js";
let now_dataSources = null;
let layerSources = {};
export default {
  components: {},
  props: {
    //启用的组件，不传为所有
    keys: {
      type: Array,
      default: ["xzq", "hx", "sc", "zbd"],
    },
    activeTabs: {
      type: String,
    },
    type: {
      type: String,
    },
  },
  data() {
    return {
      dialogVisible: false,
      yearsOpt: [], //检测图斑时间季度数据数组
      monitorOpt: [],
      monitorVal: "",
      yearsVal: "", //时间季度绑定
      input: "", //图斑编号搜索条件绑定
      updateObj: {
        //搜索条件
        region: "4602",
        tab: 1,
        val0: "",
        val1: "",
        val2: "",
      },
      active_dableData: [], //表格数据
      multipleSelection: [], //选择表格选中的数据
      idArr: [], //存储id数组用于删除
      // -----------以上为选择图斑功能所需数据------------
      userXZQ: "", //store.state.user.user.dept.district,
      fwlist: {
        xzq: {
          id: 0,
          name: "行政区",
          icon: "wind-power",
        },
        hx: {
          id: 1,
          name: "绘制",
          icon: "Share",
        },
        sc: {
          id: 2,
          name: "上传",
          icon: "Upload-filled",
        },
        zbd: {
          id: 3,
          name: "坐标点",
          icon: "Location",
        },
      },
      model: {
        fwlx: 0,
        xzfw: "",
        xzmj: 0,
        feature: null,
        yptype:1,
      },
      handlerDraw: null,
      draw: null, //绘制
      fileList: [], //文件
      fileDataID: "", //存储上传文件获取到的id
      dataSources: null,
    };
  },
  mounted() {
    // this.model.fwlx = this.fwlist[this.$props.keys[0]].id;
  },
  methods: {
    creatTb() {
      this.yptype = 2
      this.dialogVisible = false;
      this.multipleSelection.forEach((item, index) => {
        this.model.xzmj += item.jcmj;
        this.fileDataID += item.id + ",";
        item.type = "图斑上图";
        if (item.geom)
          loadGeoJSON(item.geom, "#55A1E3", { isfly: true }, (data) => {
            layerSources[item.jcbh] = data;
            data.entities.values.forEach((entity) => {
              entity.properties = item;
            });
          });
        this.idArr.push(item.jcbh);
      });
      //去掉最后一个逗号(如果不需要去掉，就不用写)
      if (this.multipleSelection.length > 0) {
        this.fileDataID = this.fileDataID.substr(0, this.fileDataID.length - 1);
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    handleClose(done) {
      this.dialogVisible = false;
    },
    typeChange(val) {
      this.updateObj.val2 = val;
    },
    regionChange1(region) {
      this.updateObj.region = region;
    },
    //年份季度改变
    yearsChange(val) {
      val = JSON.parse(JSON.stringify(val));
      this.updateObj.val0 = val.startTime;
      this.updateObj.val1 = val.endTime;
      this.yearsVal = val.quarter;
    },
    getXzqTreeData() {
      GetXzqhTree().then((res) => {
        if (res.data.length > 0) {
          const list = res.data[0].children.filter((item) => {
            return item.label == "三亚市";
          });
          if (list.length > 0) {
            list[0].value = "4602";
            this.xzqTreeData = list[0];
          } else this.xzqTreeData = res.data;
        }
      });

      GetDateList().then((res) => {
        this.yearsOpt = res.data;
        this.updateObj.val0 = res.data[0].startTime;
        this.updateObj.val1 = res.data[0].endTime;
        this.yearsVal = res.data[0].quarter;
      });
      //检测类型分类
      CodeList({
        dictType: "卫片执法后地类分类标准‌",
        pageNum: 1,
        pageSize: 999,
      }).then((res) => {
        if (res.code == 200) {
          this.monitorOpt = res.rows;
        }
      });
    },
    initNew() {
      let obj = {
        hlx: this.updateObj.val2,
        regioncode: this.updateObj.region,
        startTime: this.updateObj.val0,
        endTime: this.updateObj.val1,
        pageNum: 1,
        pageSize: "9999999",
        jcbh: this.input,
      };
      JctbList(obj).then((res) => {
        this.active_dableData = res.rows;
        this.total = res.total;
      });
    },
    changePatches() {
      this.clearAll();
      this.getXzqTreeData();
      this.dialogVisible = true;
    },
    remove() {
      if (this.idArr.length != 0) {
        this.idArr.forEach((item) => {
          viewer.dataSources.remove(layerSources[item]);
        });
      }
    },
    /** ---------------------以上为选择图斑的逻辑方法----------- **/
    //上传文件
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; //这一步，是展示最后一次选择文件
        this.clearAll(false);
      }
      this.yptype = 1
      const formdata = new FormData();
      formdata.append("file", file.raw);
      formdata.append("fromType", 2);
      formdata.append("fromRoute", this.$route.path);
      formdata.append("storeStats", 0);
      formdata.append("followup", "");
      ShapeUploadV1(formdata).then((res) => {
        if (res.success) {
          this.model.xzmj = (res.data.area * 0.0015).toFixed(2);
          // viewer.entities.removeAll();
          this.resetDataSources();
          this.fileDataID = res.data.id;
          this.model.xzfw = res.data.id;
          this.model.geom = res.data.geom;
          this.addPolygon(parse(res.data.geom));
          if (this.$props.type == "cutfill" || this.$props.type == "up") {
            this.$emit("cutfill", this.model.geom);
          }
        }
      });
    },

    //上传文件
    handleChange1(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; //这一步，是展示最后一次选择文件
        this.clearAll(false);
      }
      const formdata = new FormData();

      formdata.append("file", file.raw);
      this.addPolygon();
    },
    // 加载GeoJSON数据
    addPolygon(geojson) {
      let _this = this;
      let polygon = Cesium.GeoJsonDataSource.load(geojson, {
        clampToGround: true,
        stroke: Cesium.Color.RED,
        fill: Cesium.Color.WHITE.withAlpha(0.3),
        strokeWidth: 5,
      });
      polygon.then(function (dataSource) {
        // 将数据源添加到Cesium Viewer
        viewer.dataSources.add(dataSource);
        viewer.zoomTo(dataSource);
        now_dataSources = dataSource;
      });
    },
    resetDataSources() {
      if (now_dataSources) {
        viewer.dataSources.remove(now_dataSources);
        now_dataSources = null;
      }
    },
    //绘制
    drawMap() {
      this.remove(); //删除选择的图斑
      this.yptype = 1
      if (!window.handlerPolygon) {
        common.initHandler("Polygon");
      }
      common.handlerDrawing("Polygon").then(
        (res) => {
          //过滤掉高度
          const filteredArr = res.positions.filter((item, index) => {
            if ((index + 1) % 3 !== 0) {
              return item;
            }
          });
          // 数组变二维数组方法
          function listToMatrix(list, elementsPerSubArray) {
            var matrix = [],
              i,
              k;

            for (i = 0, k = -1; i < list.length; i++) {
              if (i % elementsPerSubArray === 0) {
                k++;
                matrix[k] = [];
              }

              matrix[k].push(list[i]);
            }

            return matrix;
          }

          var matrix = listToMatrix(filteredArr, 2);

          matrix.push(matrix[0]);
          const geojsonPolygon = turf.polygon([matrix]);
          // var parse = require("wellknown"); //引入wellknow
          const wktPolygon = parse.stringify(geojsonPolygon);
          if (this.$props.type == "cutfill") {
            this.model.geom = wktPolygon;
            this.$emit("cutfill", this.model.geom);
            return;
          }
          if (this.$props.type == "up") {
            this.$emit("cutfill", wktPolygon, res.positions);
          }

          const formdata = new FormData();
          // formdata.append("file", file.raw);
          formdata.append("fromType", 1);
          formdata.append("geom", wktPolygon);
          formdata.append("fromRoute", this.$route.path);
          formdata.append("storeStats", 0);
          formdata.append("followup", "");
          // this.addPolygon();
          ShapeUploadV1(formdata).then((res) => {
            if (res.success) {
              this.fileDataID = res.data.id;
              this.model.xzmj = (res.data.area * 0.0015).toFixed(2);
              this.model.xzfw = res.data.id;
              this.model.geom = res.data.geom;
              this.addPolygon(parse(res.data.geom));
              this.$message({
                message: "绘制成功!",
                type: "success",
              });
            }
          });
        },
        (err) => {
          console.log(err);
        }
      );
      window.handlerPolygon.activate();
    },
    clear() {
      if (this.handlerDraw != null) {
        this.handlerDraw.clear();
        viewer.scene.globe.removeAllExcavationRegion();
        this.handlerDraw.deactivate();
        this.handlerDraw = null;
        this.result = null;
      }
    },

    //清除
    clearAll(clearfile = true) {
      //销毁上传创建的面
      // viewer.entities.removeAll();
      this.remove();
      this.resetDataSources();
      this.model.xzfw = "";
      this.model.xzmj = 0;
      if (clearfile) {
        this.fileDataID = "";
        this.fileList = [];
      }
      common.clearHandlerDrawing("Polygon");
    },
    //输出：重置
    reset() {
      this.clearAll();
    },
    //输出：获取范围
    getRange() {
      return this.model;
    },
  },
  beforeDestroy() {
    this.clearAll();
  },
  watch: {
    // 监听,当路由发生变化的时候执行
    $route: {
      // $route可以用引号，也可以不用引号//to 老路由信息,from  新路由信息
      handler(to, from) {
        this.clearAll();
      },
      deep: true, // 深度观察监听
      immediate: true, // 第一次初始化渲染就可以监听到
    },
    updateObj: {
      handler(newVal, oldVal) {
        this.initNew();
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

<style lang="scss" scoped>
.map-range {
  width: 100px;
  // height: 100px;
  color: #fff;
  .xz_type {
    margin-bottom: 10px;
    // display: flex;
    // justify-content: space-between;
    .keyitem {
      width: 100px;
      height: 30px;
      font-size: 16px;
      line-height: 30px;
      display: inline-block;
      cursor: pointer;
    }
  }
  .fwlxrange {
    display: flex;
    justify-content: space-between;
    text-align: center;
    .clear {
      width: 80px;
    }
    /deep/ .el-button--mini {
      background: #0f7ac8;
      border: none;
      border-radius: 0;
      color: #fff;
      width: 60px;
      height: 26px;
      font-size: 12px;
      padding: 0;
      // line-height: 32px;
      // text-align: center;
    }
  }
}
.gdzl {
  .headerSelect {
    width: 100%;
    height: 26px;
    //   background: #00ffff;
    margin: 5px 0px;
    display: flex;
    justify-content: space-between;
    /deep/ .el-select {
      width: 95%;
      // padding: 0 10px;
      // margin-right: 10px;
    }
    /deep/ .el-input--suffix .el-input__inner {
      padding-right: 15px;
      // height: 26px;
      background: #041c3273 !important;
      border: 1px dashed #0f7ac8;
      color: #fff;
    }
    /deep/ .el-cascader {
      // line-height: 26px;
    }
    /deep/.el-input__icon {
      // line-height: 1;
      color: #fff;
    }
    /deep/ .el-input__inner::placeholder {
      color: #fff;
    }
  }
  .headerInp {
    display: flex;
    justify-content: space-between;
    align-items: center;
    /deep/ .el-button--mini {
      background: #0f7ac8;
      border: none;
      border-radius: 0;
      color: #fff;
      width: 60px;
      height: 26px;
      font-size: 12px;
      padding: 0;
    }
    /deep/ .el-input__inner {
      height: 26px;
      width: 80%;
    }
  }
}
.ghzc .el-col .el-cascader--mini {
  width: 33% !important;
}
.ghzc .el-col .el-select {
  width: 33% !important;
}

/deep/ .el-dialog__header {
  padding: 10px 20px 0px;
}
/deep/ .el-dialog__body {
  padding: 0px 20px;
}
</style>
