<template>
  <div>
    <div class="mapwrap" :title="title" :is-show.sync="isShow" :width="width" @resetform="resetPointArr">
      <div class="mapbtn">
        <el-card shadow="hover">
          <div style="width: 500px;">
            <el-row>
              <el-col :span="11">
                <el-input class="vm10" style="width: 93%" v-model="searchFields.keyword" placeholder="关键字搜索" />
              </el-col>
              <block v-if="moreSearch">
                <el-col :span="11">
                  <el-select class="vm10" filterable v-model="searchFields.area_id" placeholder="请选择所属片区">
                    <el-option v-for="item in selects.areasList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="11" >
                  <el-select class="vm10" filterable v-model="searchFields.maintain_id" placeholder="请选择所属养护单位">
                    <el-option v-for="item in selects.maintainList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="11">
                  <el-select class="vm10" filterable v-model="searchFields.status" placeholder="请选择状态">
                    <el-option v-for="item in selects.statusList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="11" >
                  <el-select class="vm10" filterable v-model="searchFields.unusual_type_id" placeholder="请选择异常类型">
                    <el-option v-for="item in selects.sunusualList" :key="item.id" :label="item.value" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="11">
                  <el-select class="vm10" filterable v-model="searchFields.type" placeholder="请选择类型">
                    <el-option v-for="item in selects.typeList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="11" >
                  <el-select class="vm10" filterable v-model="searchFields.end_type" placeholder="请选择结办类型">
                    <el-option v-for="item in selects.endTypeList" :key="item.id" :label="item.name" :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="11">
                  <el-select class="vm10" filterable v-model="searchFields.ask_content_id" placeholder="请选择巡查内容">
                    <el-option v-for="item in selects.sequiementList" :key="item.id" :label="item.value"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-col>
              </block>

              <el-col :span="11" >
                <el-select class="vm10" v-model="searchFields.road_id" filterable remote reserve-keyword clearable
                  @focus="remoteRoad" placeholder="请输入关键词查找道路" :remote-method="remoteMethod" :loading="roadloading">
                  <el-option v-for="item in roadsList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-col>
              <el-col :span="24">
                <el-date-picker class="vm10" v-model="mapdatesearch" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd">
                </el-date-picker>
                <el-button type="text" style="margin-left: 10px;" @click="moreSearch=true" v-if="!moreSearch">更多</el-button>
                <el-button type="text" style="margin-left: 10px;"  @click="moreSearch=false" v-if="moreSearch">隐藏</el-button>


              </el-col>

              <el-col :span="24">
                <Button type="primary" @click="loadMap(false)" style="margin-left: 10px">查询</Button>
                <Button type="primary" @click="resetSearch" style="margin-left: 10px">重置</Button>
              </el-col>
            </el-row>
          </div>


        </el-card>
      </div>
      <div>
        <div class="wrapper" v-if="showmap">
          <div class="chooseMap">
            <div>
              <el-radio-group v-model="showMap" @change="changeMap">
                <el-radio v-for="item in mapRadioList" :label="item.id">{{item.title}}</el-radio>
              </el-radio-group>
            </div>
            <div>
              <el-checkbox-group v-model="checkList" @change="changeCheck">
                <el-checkbox v-for="item in mapCheckList" :label="item.id">{{item.title}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <!-- 地图 -->
          <div class="map" id="olMap"></div>
          <!-- 弹框 -->
          <div ref="popup" class="popup" v-show="shopPopup">
            <div class="info">
              <div class="address">地址：{{nowAddress}}</div>
              <div class="showinfo" @click='showInfo(nowId,types)'>查看详情</div>
            </div>
          </div>
        </div>
      </div>

    </div>



    <showRainEquipmentInfo ref="showRainEquipmentInfo"></showRainEquipmentInfo>
    <showRainSiteInfo ref="showRainSiteInfo"></showRainSiteInfo>
  </div>

</template>
<script>
  import "ol/ol.css";
  import {
    Tile as TileLayer,
    Vector as VectorLayer
  } from "ol/layer";
  import XYZ from "ol/source/XYZ";
  import {
    TileArcGISRest
  } from "ol/source"
  import tilegrid from "ol/tilegrid/TileGrid"
  import {
    defaults as defaultControls
  } from "ol/control";
  import {
    get as getprojection
  } from "ol/proj"
  import {
    Projection,
    addProjection
  } from "ol/proj"
  import Map from "ol/Map.js";
  import View from "ol/View.js";

  // 标注点位
  import {
    Vector as VectorSource
  } from "ol/source";
  import * as olProj from "ol/proj";
  import {
    Feature,
    Overlay
  } from "ol"
  import {
    Point
  } from "ol/geom";
  import {
    Style,
    Fill,
    Stroke,
    Circle as sCircle
  } from "ol/style";

  import proj4 from 'proj4'

  import {
    CONFIGS,
    MAPCONFIGS
  } from '@/views/rain/inspection/components/config'

  import {
    listroad
  } from '../../../../api/basic/road.js'
  import showRainEquipmentInfo from '@/views/rain/inspection/components/showRainEquipmentInfo'
  import showRainSiteInfo from '@/views/rain/inspection/components/showRainSiteInfo'

  export default {
    components: {
      showRainEquipmentInfo,
      showRainSiteInfo,
      CONFIGS,
      MAPCONFIGS
    },
    data() {
      return {
        moreSearch: false,
        showSearch: true,
        title: "巡查点位",
        showmap: false,
        width: "100%",
        isShow: false,
        map: null,
        shopPopup: false,
        nowAddress: "",
        nowId: "",
        types: "",
        showMap: "M2",
        mapRadioList: [{
          id: "M2",
          title: "天地图"
        }, {
          id: "S1",
          title: "水利图"
        }, {
          id: "H1",
          title: "河道图"
        }],
        checkList: ['M11', 'L1'],
        mapCheckList: [{
          id: "M11",
          title: "高清影像精简"
        },{
          id: "L1",
          title: "路网"
        },{
          id: "M1",
          title: "高清影像"
        }],
        configs: CONFIGS,
        mapConfigs: MAPCONFIGS,
        projection: "EPSG:4490",
        featuresArr: [],
        flagLayer: "",
        pointArr: [],

        searchFields: {
          is_export: 0,
          is_auth: 1
        },
        roadsList: [],
        roaddisabled: false,
        roadloading: false,
        mapdatesearch: "",
        selects: {

        },
      };

    },
    created() {},
    mounted() {
      //  转换坐标系
      proj4.defs("EPSG:4490", '+proj=longlat +ellps=GRS80 +no_defs')
      this.projection = new Projection({
        code: this.mapConfigs.Map_Code,
        units: this.mapConfigs.Map_units,
        axisOrientation: this.mapConfigs.Map_axisOrientation,
        global: this.mapConfigs.Map_global
      });
      addProjection(this.projection);
      // this.initMap();
    },
    watch: {
      pointArr(newval, oldval) {
        if (newval) {
          // this.resetPointArr()
          this.pointArr = newval
          this.showmap = false
          this.$nextTick(function() {
            this.showmap = true
            this.showMap = 'M2'
            this.checkList = ['M11', 'L1']
            this.showMaps()
          })
        }
      },
      mapdatesearch(newVal, oldVal) {
        if (newVal) {
          this.searchFields.start_date = newVal[0]
          this.searchFields.end_date = newVal[1]
        } else {
          this.searchFields.start_date = ""
          this.searchFields.end_date = ""
        }

      }
    },
    methods: {
      showMaps() {
        this.$nextTick(function() {
          this.initMap();
        })
      },
      initMap() {
        let map = new Map({
          target: "olMap",
          view: new View({
            center: this.mapConfigs.MAP_center, //中心点经纬度
            zoom: this.mapConfigs.Map_Zooms[0], //图层缩放大小
            maxZoom: this.mapConfigs.Map_Zooms[1],
            minZoom: this.mapConfigs.Map_Zooms[2],
            projection: this.projection,
          }),
          layers: [],
          // interactions: defaultControls({
          //     doubleClickZoom: false,
          // }),
        });
        this.map = map;
        // 添加天地图
        let url = "http://t0.tianditu.gov.cn/DataServer?T=vec_w&x={x}&y={y}&l={z}";
        url = `${url}&T=vec_c&tk=82526d64e8504a0341f775c087863825`;
        let tdtLayer = new TileLayer({
          title: "天地图",
          id: "M2",
          type: "overlay",
          visible: true,
          layerType: "TD地图",
          opacity: 1,
          source: new XYZ({
            crossOrigin: 'anonymous',
            url: url,
            projection: "EPSG:4326"
          })
        });
        this.map.addLayer(tdtLayer);
        this.ShowLayers()
        this.setMarker()
        this.addOverlay()
        this.singleclick()

        // this.map.layer2.setVisible(false)
      },


      //加载图层
      ShowLayers() {
        for (var i = 0; i < this.configs.length; i++) {
          var result = this.configs[i];
          if (result.layerType == "GIS地图") {
            let projection = getprojection(result.projection);
            let origin = [-400.0, 399.9999999999998];
            let resolutions = [0.0027465820824835565, 0.0013732910412417782, 6.866455206208891E-4,
              3.4332276031044456E-4, 1.7166138015522228E-4, 8.583069007761114E-5, 4.291534503880557E-5,
              2.1457672519402785E-5, 1.0728836259701392E-5
            ];

            let fullExtent = [118.63622216442072, 30.12564516975147, 122.81217622965288, 32.74305227616479];

            let tileGrid = new tilegrid({
              tileSize: 256,
              origin: origin,
              extent: fullExtent,
              resolutions: resolutions
            });
            let layer = new TileLayer({
              title: result.title,
              id: result.id,
              type: result.type,
              visible: result.visible,
              layerType: result.layerType,
              opacity: result.opacity,
              source: new XYZ({
                tileGrid: tileGrid,
                url: result.url,
                projection: projection
              })
            })
            this.map.addLayer(layer);
          } else {
            let layer = new TileLayer({
              title: result.title,
              id: result.id,
              type: result.type,
              visible: result.visible,
              layerType: result.layerType,
              opacity: result.opacity,
              source: new TileArcGISRest({
                url: result.url,
                projection: result.projection
              }),
            });
            this.map.addLayer(layer);
          }
        }

      },


      // 设置巡查 点位
      setMarker() {
        // 设置图层
        this.flagLayer = new VectorLayer({
          source: new VectorSource()
        });
        // 添加图层
        this.map.addLayer(this.flagLayer);
        // 循环添加feature
        for (let i = 0; i < this.pointArr.length; i++) {
          // 创建feature，一个feature就是一个点坐标信息
          let feature = new Feature({
            geometry: new Point([this.pointArr[i][0], this.pointArr[i][1]])
          });
          // 设置展示 地址
          feature.set('address', this.pointArr[i][2])
          feature.set('types', this.pointArr[i][4])
          // 设置 巡查ID
          feature.setId(this.pointArr[i][3])
          feature.setStyle(
            new Style({
              image: new sCircle({
                fill: new Fill({
                  color: '#0f9b0f',
                }),
                radius: 6,
              }),
            })
          );
          this.featuresArr.push(feature);
        } // for 结束
        this.flagLayer.getSource().addFeatures(this.featuresArr);
      },

      addOverlay() {
        // 创建Overlay
        let elPopup = this.$refs.popup;
        this.popup = new Overlay({
          element: elPopup,
          positioning: "bottom-center",
          stopEvent: false,
          offset: [0, -20],
        });
        this.map.addOverlay(this.popup);
      },
      singleclick() {
        // 点击
        this.map.on("singleclick", (e) => {
          // 判断是否点击在点上
          let feature = this.map.forEachFeatureAtPixel(
            e.pixel,
            (feature) => feature
          );
          if (feature) {
            this.shopPopup = true;
            // 设置弹窗位置
            let coordinates = feature.getGeometry().getCoordinates();
            this.nowAddress = feature.get('address');
            this.nowId = feature.getId()
            this.types = feature.get('types');
            this.popup.setPosition(coordinates);
          } else {
            this.shopPopup = false;
          }
        });
      },

      showInfo(id, type) {
        // 日常雨水设施
        if (type == 1) {
          this.$refs.showRainEquipmentInfo.isShow = true
          this.$refs.showRainEquipmentInfo.getEquipmentInfo(id)
          this.$refs.showRainEquipmentInfo.infoId = id
          this.$refs.showRainEquipmentInfo.formType = 'showform'
        }
        // 工地
        if (type == 2) {
          this.$refs.showRainSiteInfo.isShow = true
          this.$refs.showRainSiteInfo.getSiteInfo(id)
          this.$refs.showRainSiteInfo.infoId = id
          this.$refs.showRainSiteInfo.formType = 'showform'
        }

      },
      changeMap(val) {
        for (var m of this.mapRadioList) {
          if (m.id == val) {
            this.checkLayers(val, true)
          } else {
            this.checkLayers(m.id, false)
          }
        }
      },
      changeCheck(val) {
        if (val.length == 0) {
          for (var m of this.mapCheckList) {
            this.checkLayers(m.id, false)
          }
        } else {
          for (var m of this.mapCheckList) {
            this.checkLayers(m.id, false)
          }
          for(var k of val){
            this.checkLayers(k, true)
          }
        }

      },

      // 切换地图
      checkLayers(id, bool) {
        let layers = this.map.getLayers().getArray();
        for (let i = 0; i < layers.length; i++) {
          if (layers[i].get("id") == id) {
            if (bool) {
              layers[i].setVisible(true);
            } else {
              layers[i].setVisible(false);
            }
          }
        }
      },
      loadMap() {
        this.$emit('loadMap', this.searchFields)
      },
      resetPointArr() {
        this.map = null
        let _that = this;
        this.flagLayer
          .getSource()
          .getFeatures()
          .forEach(function(feature) {
            _that.flagLayer.getSource().removeFeature(feature);
          });
        this.featuresArr = [];
        this.flagLayer.getSource().clear();
      },
      resetSearch() {
        this.searchFields = {}
        this.mapdatesearch = ['', '']
      },
      remoteRoad() {
        this.roadsList = []
      },
      remoteMethod(query) {
        if (query != '') {
          this.roadloading = true
          listroad({
            name: query
          }).then(res => {
            this.roadloading = false
            this.roadsList = res.data
          })
        } else {
          this.roadsList = []
        }
      }

    },
  };
</script>
<style lang="scss" scoped>
  .mapwrap {
    position: relative;

    .mapbtn {
      position: absolute;
      top: 10px;
      left: 50px;
      z-index: 999;
    }
  }

  .vm10 {
    margin-bottom: 10px
  }

  .chooseMap {
    position: absolute;
    margin: 15px 20px;
    // width: 350px;
    background-color: #fff;
    border-radius: 4px;
    border: 0.8px solid hsla(0, 0%, 60%, .2);
    z-index: 99;
    top: 0;
    right: 0;
    line-height: 40px;
    // text-align: center;
    padding: 0 40px 0 20px;
  }

  .map {
    width: 100vw;
    height: 100vh;
  }

  .popup {
    width: 200px;
    background-color: white;
    padding: 18px;
    border-radius: 10px;
    box-shadow: 0 0 15px rgb(177, 177, 177);

    .info {
      font-size: 14px;
      text-align: left;

      ul {
        padding-left: 0;
      }

      .showinfo {
        color: red;
        cursor: pointer;
      }
    }
  }

  .common-dialog {
    margin: 0 !important;

    .el-dialog__header {
      padding-top: 0;

      button {
        height: 28px;
        padding: 0 20px;
        line-height: 28px;
        margin-left: 10px;
      }
    }
  }
</style>
