<template>
  <div id="mapApp">
    <div class="btn" v-if="nowObj['前时相']">
      <!-- <el-button @click="drawer = true">打开抽屉</el-button> -->
      <span class="sx qsx">前时相:{{ nowObj["前时相"] }}</span>
      <span class="sx hsx">后时相:{{ nowObj["后时相"] }}</span>
    </div>
    <MapView :maptype="maptype" ref="MapView" />

    <!-- <el-drawer
      v-model="drawer"
      :with-header="false"
      :modal="false"
      :wrapperClosable="false"
      modal-class="mask-layer"
      size="28vw"
    > -->
    <div class="jctbCon">
      <div class="tbTitle">
        <span>监测图斑{{ newObj.name }}</span>
        <el-select
          v-model="domains"
          multiple
          collapse-tags
          placeholder="请选择其它搜索条件"
          @change="handleChange"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
            :disabled="item.value == '监测编号' ? true : false"
          >
          </el-option>
        </el-select>
        <el-button @click="handleDownload">下载</el-button>
        <!-- <el-input
            placeholder="请输入监测编号查询"
            prefix-icon="el-icon-search"
            v-model="queryParams['监测编号']"
            @change="getTemplate()"
          >
          </el-input> -->
        <div class="demo-input-suffix">
          监测编号:
          <el-input
            placeholder="请输入监测编号查询"
            prefix-icon="el-icon-search"
            v-model="queryParams['监测编号']"
            @change="getTemplate()"
          >
          </el-input>
        </div>
        <div class="demo-input-suffix" v-for="(ditem, i) in domains" :key="i">
          {{ ditem + ":" }}
          <el-input
            :placeholder="'请输入' + ditem + '查询'"
            prefix-icon="el-icon-search"
            v-model="queryParams[ditem]"
            @change="getTemplate()"
          >
          </el-input>
          <el-button @click.prevent="removeDomain(ditem)">删除</el-button>
        </div>
      </div>
      <div class="numCard">
        <div class="cardItem">
          <span>监测图斑个数(个):</span>
          <span>{{ newObj.spotsnumber }}</span>
        </div>
        <div class="cardItem jc">
          <span>监测面积(亩):</span>
          <span>{{ newObj.spotsarea }}</span>
        </div>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%"
        @row-click="tableClick"
      >
        <el-table-column
          :prop="templateList[i]"
          :label="templateList[i]"
          show-overflow-tooltip
          v-for="(item, i) in templateList"
          :key="i"
          :width="templateList[i] == '监测编号' ? 200 : ''"
          align="center"
        >
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click.stop="handleDetails(scope.row)"
              >详情</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getTemplate"
      />
    </div>
    <!-- </el-drawer> -->
    <el-dialog title="详细信息" :visible.sync="dialogVisible" width="30%">
      <!-- <CustomDetails :model="infoObj" :config="detailInfos"></CustomDetails> -->
      <el-descriptions class="margin-top" :column="1">
        <el-descriptions-item
          :label="item"
          v-for="(item, i) in descriptionsList"
          :key="i"
          >{{ infoObj[item] }}</el-descriptions-item
        >
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import MapView from "../MapView.vue";
import CustomDetails from "@/components/custom-detailsInfo.vue";
import parse from "wellknown";
// import { pinyin } from "pinyin-pro";
import {
  getPcsj,
  listPcsjXQList,
  getPcsjXQ,
  getXqListMap,
  getXqListKey,
  getXqIdMap,
  getXqIdKey,
} from "@/api/supervise/pcsj";
import { detailInfos } from "./config";
import "ol/ol.css";
// import { get as getProjection, transform } from "ol/proj.js";
import Map from "ol/Map";
import View from "ol/View";
import TileLayer from "ol/layer/Tile";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import Feature from "ol/Feature";
import LineString from "ol/geom/LineString";
import Stroke from "ol/style/Stroke";
import Fill from "ol/style/Fill";
import { Vector as LayerVec } from "ol/layer";
import { Style, Icon } from "ol/style";
import { Point } from "ol/geom";
import { Vector as SourceVec, XYZ } from "ol/source";
import Tile from "ol/layer/Tile";
import { OSM } from "ol/source";
import * as control from "ol/control";
import * as coordinate from "ol/coordinate";
import ImageLayer from "ol/layer/Image";
import ImageStatic from "ol/source/ImageStatic";
import Draw from "ol/interaction/Draw";
import GeoJSON from "ol/format/GeoJSON";
// import { transform } from "@/utils/transformUtils";
import { removeWebGLTile, addTiff } from "@/utils/help";

export default {
  components: {
    MapView,
    CustomDetails,
  },
  data() {
    return {
      options: [],
      domains: [], //存储动态搜索列表
      // value: ["监测编号"], //下拉框选中的值
      maptype: "normal",
      total: 0,
      queryParams: {
        监测编号: "", //监测编号
        pageNum: 1,
        pageSize: 10,
        pcsjid: this.$route.query.id,
      },
      drawer: true,
      direction: "rtl",

      tableData: [],
      newObj: {
        name: "f52d8b03a7214d9098ca44a7ea641d9b",
        spotsnumber: 0,
        spotsarea: 0,
      },
      curPageResultLayer: {},
      vectorLayer: {},
      nowObj: {},
      itemObj: {}, //用于存储分屏高亮的实体
      dialogVisible: false,
      infoObj: {},
      detailInfos: detailInfos,
      templateList: [],
      descriptionsList: [], //详情描述列表存储字段
      envelopegeomObj: {}, //用于存储进入页面飞入视角的对象
    };
  },
  mounted() {
    // 绑定事件，编写回调函数
    this.$nextTick(() => {
      getPcsj(this.$route.query.id).then((response) => {
        this.newObj = response.data;

        // if (this.newObj.envelopegeom && this.newObj.envelopegeom != "") {
        //   if (typeof this.newObj.envelopegeom === "string") {
        //     let geom = this.newObj.envelopegeom;
        //     this.newObj.envelopegeom = parse(geom);
        //   }
        //   let features = new GeoJSON().readFeatures(this.newObj.envelopegeom);
        //   this.envelopegeomObj = new VectorLayer({
        //     source: new VectorSource({
        //       features: features,
        //     }),
        //     style: function (feature) {
        //       return new Style({
        //         stroke: new Stroke({
        //           //边界样式
        //           color: "rgba(255, 0, 0, 1)",
        //           width: 2,
        //         }),
        //       });
        //     },
        //     zIndex: 9999,
        //   });
        //   let fullExtent = this.envelopegeomObj.getSource().getExtent();

        //   window.map["mapDiv"]
        //     .getView()
        //     .fit(fullExtent, window.map["mapDiv"].getSize());
        //   window.map["mapDiv"].addLayer(this.envelopegeomObj);
        // }
      });
      this.getTemplate();
    });
  },

  methods: {
    removeDomain(item) {
      var index = this.domains.indexOf(item);
      if (index !== -1) {
        this.domains.splice(index, 1);
        this.$delete(this.queryParams, item); //删除对象属性
        this.getTemplate();
      }
    },
    handleDelete(row) {
      this.tableData.forEach((item, i) => {
        window.map["mapDiv"].removeLayer(this.curPageResultLayer["mapDiv" + i]);
      });
    },
    handleChange(val) {
      // this.$set(this.queryParams, val, "");
      // this.domains.push(val);
      // this.domains = val;
      if (this.domains.indexOf(val) == -1) {
        this.domains = val;
        this.$set(this.queryParams, val, "");
      } else {
        this.domains.splice(this.domains.indexOf(val), 1);
        this.$delete(this.queryParams, item);
      }
      console.log(this.queryParams, ";this.queryParams", this.domains);
    },
    //动态获取设置的模版字段
    getTemplate() {
      this.handleDelete();
      let arr = [
        "中心点经度",
        "中心点纬度",
        "前时相",
        "后时相",
        "空间信息",
        "geom",
        "前时相对应影像数据",
        "后时相对应影像数据",
      ];
      this.templateList = [];
      this.options = [];

      getXqListKey(this.queryParams).then((res) => {
        res.data.forEach((i) => {
          if (!arr.includes(i)) {
            this.templateList.push(i);
            // this.options.push({
            //   // value: pinyin(i, {
            //   //   pattern: "first",
            //   //   toneType: "none",
            //   //   separator: "",
            //   // }),
            //   label: i,
            // });
            this.options.push({
              value: i,
              label: i,
            });
          }
        });
      });

      getXqListMap(this.queryParams).then((res) => {
        console.log(res, "======");
        this.tableData = res.rows;
        this.total = res.total;
        this.initVectorLayer("mapDiv");
        this.initVectorLayer("mapCon1");
        this.initVectorLayer("mapCon2");
        this.addGeoJson("mapDiv", true);
        this.addGeoJson("mapCon1");
        this.addGeoJson("mapCon2");
      });
    },
    handleDownload() {
      const zipfile = this.newObj.proxypath + ".zip";
      window.open(`${zipfile}`);
    },
    tableClick(row) {
      removeWebGLTile("mapCon1");
      removeWebGLTile("mapCon2");
      let urlQsx = this.newObj.proxypath + row["前时相对应影像数据"];
      let urlHsx = this.newObj.proxypath + row["后时相对应影像数据"];
      if (this.nowObj.id != row.id) {
        this.maptype = "split";
        this.nowObj = row;
        addTiff("mapCon1", urlQsx);
        addTiff("mapCon2", urlHsx);
        this.test(row);
      } else {
        this.maptype = "normal";
        this.nowObj = {};
      }
    },

    getList() {
      listPcsjXQList(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.initVectorLayer("mapDiv");
        this.initVectorLayer("mapCon1");
        this.initVectorLayer("mapCon2");
        this.addGeoJson("mapDiv");
        this.addGeoJson("mapCon1");
        this.addGeoJson("mapCon2");
      });
    },
    handleDetails(row) {
      getXqIdMap({ pcsjid: this.$route.query.id, id: row.id }).then((res) => {
        this.infoObj = res.data;
      });
      getXqIdKey({ pcsjid: this.$route.query.id }).then((res) => {
        this.descriptionsList = res.data;
      });
      this.dialogVisible = true;
    },
    handleClose() {
      this.drawer = false;
    },
    test(item) {
      window.map["mapCon1"].removeLayer(this.itemObj);
      window.map["mapCon2"].removeLayer(this.itemObj);
      if (item.geom && item.geom != "") {
        if (typeof item.geom === "string") {
          let geom = this.tableData[i].geom;
          item.geom = parse(geom);
        }
        let features = new GeoJSON().readFeatures(item.geom);
        this.itemObj = new VectorLayer({
          source: new VectorSource({
            features: features,
          }),
          style: function (feature) {
            return new Style({
              stroke: new Stroke({
                //边界样式
                color: "rgba(255, 0, 0, 1)",
                width: 2,
              }),
            });
          },
          zIndex: 9999,
        });
        window.map["mapCon1"].getView().animate({
          center: [item["中心点经度"], item["中心点纬度"]],
          zoom: 16.5,
          duration: 2000, // 动画持续时间，单位毫秒
        });
        window.map["mapCon1"].addLayer(this.itemObj);
        window.map["mapCon2"].addLayer(this.itemObj);
      }
    },
    //创建监测图斑列表实体
    addGeoJson(name, isfly) {
      this.tableData.forEach((titem, i) => {
        if (titem.geom && titem.geom != "") {
          if (typeof titem.geom === "string") {
            let geom = this.tableData[i].geom;
            titem.geom = parse(geom);
          }
          let features = new GeoJSON().readFeatures(titem.geom);
          var tempName = name + i;
          this.curPageResultLayer[tempName] = new VectorLayer({
            source: new VectorSource({
              features: features,
            }),
            style: function (feature) {
              return new Style({
                stroke: new Stroke({
                  //边界样式
                  color: "rgba(0, 0, 255, 1)",
                  width: 2,
                }),
              });
            },
            zIndex: 9999,
          });
          window.map[name].addLayer(this.curPageResultLayer[tempName]);
        }
      });
      if (isfly) {
        let fullExtent = this.curPageResultLayer[
          name + (this.tableData.length - 1)
        ]
          .getSource()
          .getExtent();
        window.map[name].getView().fit(fullExtent, {
          duration: 3, //动画的持续时间,
          callback: null,
          size: window.map[name].getSize(),
          padding: [500, 500, 500, 500],
          constrainResolution: false, // 允许视图超出分辨率限制
        });
      }
    },
    /**
     * 初始化地图矢量图层
     */
    initVectorLayer(name) {
      if (!this.vectorLayer[name]) {
        let vectorSource = new VectorSource({
          // projection: "EPSG:3857",
        });
        this.vectorLayer[name] = new VectorLayer({
          source: vectorSource,
          style: new Style({
            stroke: new Stroke({
              color: "#f00",
              width: 2,
            }),
          }),
        });
        window.map[name].addLayer(this.vectorLayer[name]);
      }
      if (!this.curPageResultLayer[name]) {
        let vectorSource = new VectorSource();
        this.curPageResultLayer[name] = new VectorLayer({
          source: vectorSource,
          zIndex: 999,
          style: new Style({
            stroke: new Stroke({
              color: "#1f1cd3",
              width: 2,
            }),
          }),
        });
        window.map[name].addLayer(this.curPageResultLayer[name]);
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.btn {
  // position: absolute;
  // top: 0;
  // left: 60px;
  // z-index: 40;
  .sx {
    background: rgb(151, 250, 222);
    padding: 5px 10px;
    border: 1px solid #4949492b;
    border-radius: 5px;
    position: absolute;
    top: 20px;
    left: calc(50% - 420px);
    z-index: 40;
  }

  .hsx {
    left: calc(50% - 220px);
  }
}

// .mask-layer{
//   width: 264px !important;
// }
// ::v-deep .el-drawer__wrapper {
//   position: static !important;
// }

// ::v-deep .el-drawer__container {
//   position: static !important;
// }

// ::v-deep .el-drawer__body {
//   width: 28vw;
// }

.jctbCon {
  position: absolute;
  right: 20px;
  top: 0px;
  width: 28vw;
  padding: 20px;
  .tbTitle {
    display: flex;
    justify-content: space-around;
    justify-content: flex-start;
    flex-wrap: wrap;

    ::v-deep .el-input {
      // width: 28%;
      width: 55%;
    }

    ::v-deep .el-input--suffix {
      width: 100% !important;
    }
  }

  .numCard {
    width: 100%;
    height: 120px;
    display: flex;
    // background-color: rgba(255, 192, 203, 0.272);
    flex-direction: row;
    align-items: center;
    justify-content: space-between;

    .cardItem {
      // width: 230px;
      width: 200px;
      height: 85px;
      background: linear-gradient(
        180deg,
        rgba(30, 198, 149, 1) 0%,
        rgba(30, 198, 149, 1) 0%,
        rgba(51, 204, 204, 1) 100%,
        rgba(51, 204, 204, 1) 100%
      );
      border: none;
      border-radius: 4px;
      -moz-box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.349019607843137);
      -webkit-box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.349019607843137);
      box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.349019607843137);
      font-family: "Arial Negreta", "Arial Normal", "Arial";
      font-weight: 700;
      font-style: normal;
      font-size: 14px;
      color: #ffffff;
      display: flex;
      flex-direction: column;
      justify-content: center;

      span {
        display: inline-block;
        width: 100%;
        height: 39%;
        // background: #faebd78c;
        text-align: center;
      }
    }

    .jc {
      background: linear-gradient(
        90deg,
        rgba(244, 174, 149, 1) 0%,
        rgba(244, 174, 149, 1) 0%,
        rgba(226, 113, 140, 1) 100%,
        rgba(226, 113, 140, 1) 100%
      );
    }
  }
}
</style>
<style scoped>
html,
body {
  padding: 0;
  margin: 0;
  height: 100%;
}

#mapApp {
  width: 100%;
  height: 100%;
}
</style>