<template>
  <div class="style_container content_search" v-if="contentIsShow && resultList.length > 0">
    <div class="container result_part">
      <div class="result_list">
        <ul>
          <li v-for="(item, index) in resultList" :key="index" @click="location(item)">
            <span>{{ item.title }}</span>
          </li>
        </ul>
      </div>
      <el-pagination
        small
        layout="prev, pager, next"
        @current-change="changePage"
        :page-size="pageSize"
        :total="total"
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import api from "@/api/contentlist";
import api2 from "@/api/menu";
import { transform } from "ol/proj";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Feature from "ol/Feature";
import Point from "ol/geom/Point";
import { Icon, Style } from "ol/style";

import marker from "../assets/images/poi/marker-icon.png";
import focusMaker from "../assets/images/poi/focus_maker.png";

export default {
  props: {
    contentIsShow: {
      type: Boolean,
      default: false,
    },
    keyword: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      pageSize: 20,
      pageNum: 0,
      resultList: [],
      total: 0,
      markerLayer: null,
      source: null,
    };
  },
  mounted() { },
  methods: {
    search() {
      let that = this;
      // 目录开启搜索，强制关闭目录
      if (!this.keyword) {
        that.$message({
          type: "warning",
          message: "请输入关键字",
        });
        return;
      }
      if (this.markerLayer == null) {
        this.addLayerToMap();
        this.addFocusLayerToMap();
      } else {
        this.clearSource();
        this.clearFocusSource();
      }
      let param = {
        title: this.keyword,
        page: this.pageNum,
        pageSize: this.pageSize,
      };
      api
        .getContentForTitle(param)
        .then((result) => {
          if (result.code == 200) {
            that.resultList = result.content;
            that.total = result.total;
            let poiArr = that.resultList.map(function (item) {
              return that.setPoi([item.centerLon, item.centerLat], item);
            });
            that.source.addFeatures(poiArr);
            globalVariable.map.getView().fit(that.source.getExtent());
          } else {
            that.$message({
              type: "warning",
              message: result.message,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    changePage(currentPage) {
      this.pageNum = currentPage - 1;
      this.search();
    },
    addLayerToMap() {
      this.markerLayer = new VectorLayer({
        source: null,
        style: null,
        zIndex: 1000,
      });
      this.source = new VectorSource(); // 创建矢量图
      this.markerLayer.setSource(this.source); //设置图源
      globalVariable.map.addLayer(this.markerLayer);
    },
    addFocusLayerToMap() {
      this.focusLayer = new VectorLayer({
        source: null,
        style: null,
        zIndex: 1000,
      });
      this.focusSource = new VectorSource(); // 创建矢量图
      this.focusLayer.setSource(this.focusSource); //设置图源
      globalVariable.map.addLayer(this.focusLayer);
    },
    clearSource() {
      if (!this.source) return;
      let features = this.source.getFeatures();
      for (let i = 0; i < features.length; i++) {
        this.source.removeFeature(features[i]);
      }
    },
    clearFocusSource() {
      if (!this.focusSource) return;
      let features = this.focusSource.getFeatures();
      for (let i = 0; i < features.length; i++) {
        this.focusSource.removeFeature(features[i]);
      }
    },
    location(item) {
      let that = this;
      this.$root.popup.setPosition(undefined);
      let view = globalVariable.map.getView();
      view.animate({
        center: transform(
          [item.centerLon, item.centerLat],
          "EPSG:4326",
          "EPSG:3857"
        ),
        zoom: 17,
        duration: 2000,
      });
      this.clearFocusSource();
      this.focusFeature = new Feature({
        geometry: new Point(
          transform([item.centerLon, item.centerLat], "EPSG:4326", "EPSG:3857")
        ),
        callback: function (feature, selectSingleClickFeatures) {
          let properties = feature.values_.properties;
          that.setPopup(properties, feature.getGeometry().getCoordinates());
        },
        properties: item,
      });
      this.focusFeature.setStyle(
        new Style({
          image: new Icon({
            anchor: [0.5, 1],
            crossOrigin: "anonymous",
            src: focusMaker,
          }),
        })
      );
      this.focusSource.addFeature(this.focusFeature);
    },

    // 设置 popup
    setPopup(properties, position) {
      let that = this;
      that.$root.popup_content.html(
        `<div>名称：${properties.title}</div>
         <div>描述：${properties.content}</div>
        `
      );
      that.getMoreDetail(properties,position);
      // that.$root.popup_setPositionAndRelocation(position);
    },

    setPoi(lonlat, properties) {
      let that = this;
      var point = new Point(transform(lonlat, "EPSG:4326", "EPSG:3857"));
      var pointFeature = new Feature({
        geometry: point,
        properties: properties,
        callback(feature, selectSingleClickFeatures) {
          let properties = feature.values_.properties;
          that.setPopup(properties, feature.getGeometry().getCoordinates());
        },
      });
      pointFeature.setStyle(
        new Style({
          image: new Icon({
            anchor: [0.5, 1],
            crossOrigin: "anonymous",
            src: marker,
          }),
        })
      );
      return pointFeature;
    },

        // 展开更多详情
    getMoreDetail(properties, position) {
      let that = this;
      api2
        .getPointDetailByID({
          id: properties.id,
          modelId: properties.modelId,
        })
        .then((result) => {
          if (result.code == 200) {
            if (result.content.jsonStr)
              JSON.parse(result.content.jsonStr).forEach(function (item) {
                $(
                  `<div>${item.name}：${item.value}${item.unit}</div>`
                ).appendTo(that.$root.popup_content);
              });
            // if (properties.modelId == 9) {
            //   $(
            //     `<div><p class='moreInfo'><a onclick="openVideo()">视频监控</a>&nbsp;&nbsp;&nbsp;&nbsp;<a>更多信息</a></p></div>`
            //   ).appendTo(that.$root.popup_content);
            // } else {
            // $(`<div><p class='moreInfo'><a>更多信息</a></p></div>`).appendTo(
            //   that.$root.popup_content
            // );
            // }
            // that.$root.popup_setPositionAndRelocation(position);
          } else {
            that.$message({
              type: "error",
              message: result.message,
            });
          }
          that.$root.popup_setPositionAndRelocation(position);
        })
        .catch((err) => {
          that.$message({
            type: "error",
            message: "获取详情失败，请稍后重试。",
          });
        });
    },
    close() {
      // TODO
      this.resultList = [];
      this.pageNum = 0;
      this.clearSource();
      this.clearFocusSource();
      this.$root.popup.setPosition(undefined);
    },
  },
  watch: {
    keyword: function (newVal) {
      if (newVal == "") {
        this.close();
      }
    },
    contentIsShow(newVal) {
      if (!newVal) {
        this.close();
      }
    },
  },
};
</script>

<style lang="less" scoped>
.content_search {
  position: absolute;
  width: 100%;
  margin-top: 10px;
  left: -5px;
  .result_part {
    width: 100%;
    margin-top: 5px;
    .result_list {
      max-height: 300px;
      overflow: hidden;
      overflow-y: auto;
      li {
        height: 40px;
        line-height: 40px;
        font-size: 18px;
        text-indent: 10px;
        cursor: pointer;
        border-bottom: 1px solid #eeeeee;
      }
    }
    .el-pagination {
      text-align: center;
      /deep/ button:disabled {
        background-color: transparent !important;
      }
      /deep/ .el-pager li {
        background-color: transparent !important;
      }
    }
  }
}
</style>