<template>
  <div id="mapApp">
    <div class="btn" v-if="nowObj.qsx">
      <!-- <el-button @click="drawer = true">打开抽屉</el-button> -->
      <span class="sx qsx">前时相:{{ nowObj.qsx }}</span>
      <span class="sx hsx">后时相:{{ nowObj.hsx }}</span>
    </div>
    <div class="bottons" v-if="dialogVisible">
      <div class="divbtn" @click="flyto(nowObj)">
        <div class="divicon point"></div>
        图斑定位
      </div>
      <div class="divbtn" @click="contrast(nowObj)">
        <div class="divicon qh"></div>
        前后对比
      </div>
    </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" v-if="!dialogVisible">
      <div class="tbTitle">
        <span>图斑列表 </span>
        <el-select
          v-model="domains"
          placeholder="请选择其它搜索条件"
          @change="handleChange"
          style="width: 150px; padding-left: 20px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
        <div
          v-if="$route.query.form != 'dataEntry'"
          class="returnlist"
          @click="returnlist"
        ></div>
      </div>
      <numCard :sdlist="sdlist"></numCard>
      <tablePage
        :cloumn="TableHeader"
        :table="{ total, data: tableData }"
        :indexed="false"
        :check="true"
        layout="total, prev, pager, next"
        ref="tableDialogRef"
        @selectChange="handleSelectionChange"
        @currentChange="getTemplate"
        v-model:pageNum="queryParams.pageNum"
        v-model:pageSize="queryParams.pageSize"
      >
        <template #action="{ row, $index }">
          <el-button size="mini" type="text" @click.stop="flyto(row)"
            >定位</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click.stop="tableClick(row, $index)"
            >详情</el-button
          >
        </template>
      </tablePage>
      已选{{ ids.length }}条
      <el-button @click="handleDownload">下载</el-button>
    </div>
    <div class="jctbCon" v-if="dialogVisible">
      <el-button size="mini" @click="returnto()">返回列表</el-button>
      <el-button size="mini" @click="next(false)">上一个</el-button>
      <el-button size="mini" @click="next(true)">下一个</el-button>
      <!-- <div>图斑编号:{{ nowObj.dkbh }}</div> -->
      <Details ref="detailsRef"></Details>
    </div>
    <!-- <CustomDetails :model="infoObj" :config="detailInfos"></CustomDetails> -->
  </div>
</template>

<script>
import MapView from "../MapView.vue";
import numCard from "@/components/numCard.vue";
import CustomDetails from "@/components/custom-detailsInfo.vue";
import Details from "./details.vue";
import parse from "wellknown";
// import { pinyin } from "pinyin-pro";

import { getDkdbList } from "@/api/rsmonitoring/dataEntry";
import { listDkjbxx, getDkjbxx } from "@/api/rsmonitoring/dkjbxx";
import { TableHeader } 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,
    numCard,
    Details,
  },
  data() {
    return {
      options: [
        { label: "监测编号", value: 0 },
        { label: "监测面积", value: 1 },
        { label: "外业时间", value: 2 },
      ],
      sdlist: [
        { name: "待审核", pronum: "155", promj: "151.12" },
        { name: "已审核", pronum: "155", promj: "151.12" },
        { name: "已提交", pronum: "155", promj: "151.12" },
      ],
      domains: 0, //存储动态搜索列表
      // value: ["监测编号"], //下拉框选中的值
      maptype: "normal",
      total: 0,
      queryParams: {
        startTime: "",
        endTime: "",
        auditflowList: [],
        dkmjbs: "",
        dkmj: "",
        descValue: "",
        // 监测编号: "", //监测编号
        pageNum: 1,
        pageSize: 10,
        uploadld: this.$route.query.id,
      },
      drawer: true,
      direction: "rtl",

      tableData: [],
      newObj: {},
      curPageResultLayer: {},
      vectorLayer: {},
      nowObj: {},
      itemObj: {}, //用于存储分屏高亮的实体
      dialogVisible: false,
      TableHeader: TableHeader,
      envelopegeomObj: {}, //用于存储进入页面飞入视角的对象
      ids: [],
    };
  },
  mounted() {
    // 绑定事件，编写回调函数
    this.$nextTick(() => {
      this.newObj = { id: this.$route.query.id };
      if (this.$route.params.queryParams)
        this.queryParams = this.$route.params.queryParams;
      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);
      }
    },
    //动态获取设置的模版字段
    getTemplate() {
      this.handleDelete();
      if (this.$route.query.form == "checkLand") {
        listDkjbxx(this.queryParams).then((res) => {
          this.setList(res);
          if (this.$route.query.index) {
            getDkjbxx(this.$route.query.id).then((res) => {
              this.newObj = res.data;
              this.tableClick(this.newObj, this.$route.query.index || 0);
            });
          }
        });
      } else {
        getDkdbList(this.queryParams).then((res) => {
          this.setList(res);
        });
      }
    },
    setList(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");
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    handleDownload() {
      const zipfile = this.newObj.proxypath + ".zip";
      window.open(`${zipfile}`);
    },
    tableClick(row, index) {
      removeWebGLTile("mapCon1");
      removeWebGLTile("mapCon2");
      if (this.nowObj.id != row.id) {
        this.maptype = "split";
        this.nowObj = { ...row, index };
        addTiff("mapCon1", row["qsxtif"]);
        addTiff("mapCon2", row["hsxtif"]);
        this.test(row);
      } else {
        this.maptype = "normal";
        this.nowObj = {};
      }
      this.handleDetails(row);
    },
    contrast() {
      if (this.maptype == "normal") {
        this.maptype = "split";
      } else {
        this.maptype = "normal";
      }
    },
    next(add) {
      let index = Number(this.nowObj.index) + (add ? 1 : -1);
      if (index == -1 || index == this.tableData.length) {
        this.$modal.msgError(`当前为${add ? "最后" : "第"}一个`);
      } else {
        let row = this.tableData[index];
        this.tableClick(row, index);
      }
    },

    handleDetails(row) {
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.detailsRef.getDetails({
          pcsjid: this.$route.query.id,
          id: row.id,
        });
      });
    },

    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 = item.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["lzb"], item["bzb"]],
          zoom: 16.5,
          duration: 2000, // 动画持续时间，单位毫秒
        });

        window.map["mapCon1"].addLayer(this.itemObj);
        window.map["mapCon2"].addLayer(this.itemObj);
      }
    },
    flyto(item) {
      window.map["mapDiv"].getView().animate({
        center: [item.lzb, item.bzb],
        zoom: 16.5,
        duration: 2000, // 动画持续时间，单位毫秒
      });
    },
    //创建监测图斑列表实体
    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 + 0 //(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]);
      }
    },
    returnto() {
      this.dialogVisible = false;
      // this.$router.back();
    },
    returnlist() {
      this.$router.back();
    },
  },
};
</script>
<style lang="scss" scoped>
.btn {
  .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);
  }
}
.bottons {
  position: absolute;
  top: 0;
  left: 60px;
  z-index: 40;

  .divbtn {
    width: 65px;
    height: 65px;
    border: 1px solid rgba(73, 73, 73, 0.168627451);
    border-radius: 5px;
    margin: 10px;
    border-color: #409eff;
    color: #409eff;
    text-align: center;
    font-size: 14px;
    cursor: pointer;
    .divicon {
      width: 28px;
      height: 28px;
      margin: 5px auto;
    }
    .point {
      background: url("@/assets/images/point.png") no-repeat;
      background-size: 100% 100%;
    }
    .qh {
      background: url("@/assets/images/qh.png") no-repeat;
      background-size: 100% 100%;
    }
  }
  .divbtn:hover {
    border-color: #409eff;
  }
}

.jctbCon {
  position: absolute;
  right: 20px;
  top: 0px;
  width: 28vw;
  padding: 20px;
  height: 100%;
  .tbTitle {
    display: flex;
    justify-content: space-around;
    justify-content: flex-start;
    flex-wrap: wrap;
  }
}
.returnlist {
  width: 32px;
  height: 32px;
  margin-left: auto;
  background: url("@/assets/images/returnlist.png") no-repeat center;
  background-size: 100% 100%;
  cursor: pointer;
}
</style>
<style scoped>
#mapApp {
  width: 100%;
  height: 100%;
}
</style>