<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="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>
  </div>
</template>

<script>
import { ShapeUpload } from "@/api/ghss/hgxfx.js";
import { ElMessage } from "element-ui";
// import { polygon } from "@turf/turf";
import * as turf from "@turf/turf";
import parse from "wellknown";
let now_dataSources = null;
export default {
  components: {},
  props: {
    //启用的组件，不传为所有
    keys: {
      type: Array,
      default: ["xzq", "hx", "sc", "zbd"],
    },
    activeTabs: {
      type: String,
    },
    type: {
      type: String,
    },
  },
  data() {
    return {
      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,
      },
      handlerDraw: null,
      draw: null, //绘制
      fileList: [], //文件
      fileDataID: "", //存储上传文件获取到的id
      dataSources: null,
    };
  },
  mounted() {
    // this.model.fwlx = this.fwlist[this.$props.keys[0]].id;
  },
  methods: {
    //上传文件
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]; //这一步，是展示最后一次选择文件
        this.clearAll(false);
      }
      const formdata = new FormData();
      formdata.append("file", file.raw);
      formdata.append("fromType", 2);
      formdata.append("fromRoute", this.$route.path);
      ShapeUpload(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.$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();
      // ShapeUpload(formdata).then((res) => {
      //   if (res.success) {
      //     // var layer = myMap.addGeoJson("common_layer", res.data.geojson);
      //     // var url = `${SYS_LAYERS.XZQXZ}/0/query`;
      //     // var geom = layer.getSource().getFeatures()[0].getGeometry();
      //     // 判断绘制范围是否在行政区范围内
      //     let withinRange = true;
      //     // arcMap.SearchWfsData(url, geom, function (fs) {
      //     //   if (fs.length) {
      //     //     fs.map((res) => {
      //     //       let xzqdm = res.get("XZQDM");
      //     //       if (!xzqdm.startsWith(this.userXZQ)) {
      //     //         withinRange = false;
      //     //       }
      //     //     });
      //     //   } else {
      //     //     withinRange = false;
      //     //   }
      //     if (withinRange) {
      //       this.model.xzfw = res.data.filepath;
      //       //     this.model.feature = layer.getSource().getFeatures()[0];
      //       //     this.model.xzmj = new OLTool().Tools.formatArea(
      //       //       this.model.feature.getGeometry(),
      //       //       true
      //       //     );
      //       //     myMap.zoomToextent(layer.getSource().getExtent());
      //     } else {
      //       //     this.clearAll();
      //       //     ElMessage.warning("分析范围超出了权限范围，请重新上传文件！");
      //     }
      //     // });
      //   }
      // });
    },
    // 加载GeoJSON数据
    addPolygon(geojson) {
      // let geojson =
      //   this.$props.type == "hegxfx"
      //     ? "/static/data/ghss/导入.geojson"
      //     : "static/data/draw.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() {
      if (!window.handlerPolygon) {
        common.initHandler("Polygon");
      }
      common.handlerDrawing("Polygon").then(
        (res) => {
          // console.log(res.positions, "------");
          //过滤掉高度
          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);
          // console.log(matrix, "max-----");

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

          const formdata = new FormData();
          // formdata.append("file", file.raw);
          formdata.append("fromType", 1);
          formdata.append("geom", wktPolygon);
          formdata.append("fromRoute", this.$route.path);
          // this.addPolygon();
          ShapeUpload(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.$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.resetDataSources();
      this.model.xzfw = "";
      this.model.xzmj = 0;
      if (clearfile) {
        this.fileDataID = "";
        this.fileList = [];
      }
      common.clearHandlerDrawing("Polygon");
    },
    //输出：重置
    reset() {
      // this.model = {
      //   fwlx: this.fwlist[this.$props.keys[0]].id,
      //   xzfw: "",
      //   xzmj: 0,
      // };
      // this.fileList = []; //文件
      this.clearAll();
    },
    //输出：获取范围
    getRange() {
      return this.model;
    },
  },
  beforeDestroy() {
    this.clearAll();
  },
  watch: {
    // 监听,当路由发生变化的时候执行
    $route: {
      // $route可以用引号，也可以不用引号//to 老路由信息,from  新路由信息
      handler(to, from) {
        this.clearAll();
      },
      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: 14px;
      // line-height: 32px;
      // text-align: center;
    }
  }
}
</style>
