<script lang="jsx">
import { defineComponent, onMounted, onUpdated, onUnmounted } from "vue";
import { mapState } from "vuex";
import ResizeObserver from "resize-observer-polyfill";
import debounce from "lodash/debounce";
import { getMapConfig } from "@/api/gis";
import { getLonLatByAllRoads, getTrackDriving } from "@/api/curingManage";
import { useStore } from "vuex";
import markerbg from '@/assets/images/roadtitbg.png'

const defaultBounds = [72.675311, 17.022993, 136.308124, 53.986993];
export default defineComponent({
  components: {},
  provide() {
    return {
      mapVM: this,
      getMap: this.getMap,
    };
  },
  props: {
    config: {
      type: Object,
      default: null,
    },
    center: {
      type: [Array, Object],
      default: null,
    },
    zoom: {
      type: Number,
      default: 8,
    },
    minZoom: {
      type: Number,
      default: 0,
    },
    maxZoom: {
      type: Number,
      default: 17,
    },
    bounds: {
      type: Array,
      default: null,
    },
    maxBounds: {
      type: Array,
      default: null,
    },
    fitBoundsOptions: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      loaded: false,
      layers: [],
      videoPonit: null, //摄像头聚合点
      selectLevel: '',
      allRoadsLonglat: [], //包含经纬度的所有路段
      selectLineLayer: [], //已选择（已展示）的线路的id
      trafficInfo:{
        visibility: 'none',
        closedTrafficMileage: 0, // 0 禁止通行长度
        heavyCongestionMileage: 0, // 4重度拥堵长度
        moderateCongestionMileage: 0, // 3重度拥堵长度
        mildCongestionMileage: 0, //2轻度拥堵长度
        patencyMileage: 0, // 1通畅
      },
      markerList: {},
      markerDomListID: [],
      allRoadslanglat: [],//所有路段经纬度
      allRoadsIds: [], //所有路段的id
    };
  },
  computed: {
    watchViewProps() {
      return [this.center, this.zoom, this.bounds, this.fitBoundsOptions];
    },
    selectRoad() {
      return this.$store.state.road.selectRoadId
    },
    allRoads() {
      // 所有组织机构/路段
      return this.$store.state.road.allRoads
    },
    // 路况路段的长度和显示隐藏
    getTrafficMileage() {
      return this.$store.state.trafficMileage
    }
  },
  watch: {
    config() {
      this.init();
    },
    watchViewProps() {
      this.fitView();
    },
    selectRoad(newVal, oldVal) {
      // this.getThatRows(newVal[this.$store.state.road.selectLevel - 1], this.$store.state.road.selectLevel)
      // this.getRoadsLngLat(newVal[2])
    },
    getTrafficMileage(newVal, oldVal) {
      this.trafficInfo.visibility = newVal.visibility
    }
  },
  mounted() {
    this.getAllRoadsLangLat()
    this.init();
  },
  methods: {
    // 加载地图
    init() {
      const { config, _initPromise } = this;
      if (!config || !config.key || _initPromise) {
        return;
      }
      const {
        key,
        domainUrl,
        dataDomainUrl,
        spriteUrl,
        serviceUrl,
        solution,
        style,
      } = config;
      const _that = this
      this._initPromise = new Promise((resolve, reject) => {
        this.loadMinemapAPI()
          .then(() => {
            minemap.domainUrl = "https://map.hope.cmet1965.com:58000";
      minemap.dataDomainUrl = "https://map.hope.cmet1965.com:58000";
      minemap.serverDomainUrl = "https://map.hope.cmet1965.com:58000";
      minemap.serviceUrl = "https://map.hope.cmet1965.com:58000/service/";
      minemap.spriteUrl = "https://map.hope.cmet1965.com:58000/minemapapi/zsxz/zsxz";
            minemap.appKey = key;
            minemap.solution = solution;

            const options = this.getOptions();
            console.log(options);
            options.style = style;

            const map = new minemap.Map(options);
            map.on("load", () => {
              this._initPromise = null;
              this.loaded = true;
              map.repaint = true;
              this.$emit("load", { map, getMap: this.getMap });
              this.map = map;
              //隐藏地图上已有的线路(这个线路是做地图那边的人加上的，不是前端加的，所以先隐藏)
              // map.setLayoutProperty('466cb84ab4cacabe16ba0d1c269c0606', "visibility", "none");
              this.fitView();
              this.initEvent();
              this.observeResize();
              this.getThatRows('CQ', 1)
              resolve();
            });
          })
          .catch((err) => {
            reject("初始化地图失败", err);
          });
      });
    },
    async getAllRoadsLangLat() {
       const data = await getLonLatByAllRoads()
       this.allRoadslanglat = data.msgContent
       //获取所有id
       this.allRoadsIds = []
       this.allRoadslanglat.forEach(ele => {
         this.allRoadsIds.push(ele.sectionId)
       });
       console.log('所有路段')
       console.log(this.allRoads)
    },
    initEvent() {
      const { map, $attrs } = this;
      const { ...attrs } = $attrs;
      if (!map) {
        return;
      }
      for (const evtKey in attrs) {
        if (evtKey !== "onLoad") {
          // map.on("click", id, (evt) => {
          //   this.$emit("click", { ...evt });
          // });\
           map.on("click", (evt) => {
            this.$emit("click", { ...evt });
          });
        }
      }

      // for (const evtKey in $listeners) {
      //   if (
      //     evtKey !== "load" &&
      //     Object.hasOwnProperty.call($listeners, evtKey)
      //   ) {
      //     map.on(evtKey, (evt) => {
      //       this.$emit(evtKey, { ...evt });
      //     });
      //   }
      // }
    },
    observeResize() {
      if (!ResizeObserver || !this.$refs.mapEl) {
        return;
      }
      const debouncedResize = debounce(() => {
        this.map.resize();
      }, 100);
      const observer = new ResizeObserver(debouncedResize);
      observer.observe(this.$refs.mapEl);
    },
    getOptions() {
      const options = {
        container: this.$refs.mapEl,
        logoControl: false,
        bounds: defaultBounds,
        maxBounds: defaultBounds,
        maxZoom: 17,
        minZoom: 3,
      };
      ["center", "zoom", "pitch", "maxZoom", "minZoom"].forEach((key) => {
        const opt = this[key];
        if (opt !== null && opt !== undefined) {
          options[key] = opt;
        }
      });

      return options;
    },
    watchMapOptions() {
      ["pitch", "maxZoom", "minZoom"].forEach((key) => {
        this.$watch(key, (newVal, oldVal) => {
          const { map } = this;
          if (!map) {
            return;
          }
          const fnName = `set${key.charAt(0).toUpperCase() + key.slice(1)}`;
          if (!map[fnName]) {
            return;
          }
          map[fnName](newVal);
        });
      });
    },
    fitView() {
      let { map, center, zoom, bounds, fitBoundsOptions } = this;
      if (!map) {
        return;
      }
      fitBoundsOptions = fitBoundsOptions || {};
      if (!fitBoundsOptions.padding) {
        fitBoundsOptions.padding = 40;
      }
      // if (center && center.length) {
      //   map.setZoom(zoom);
      //   map.setCenter(center);
      //   return;
      // }
      return;

      if (bounds) {
        map.fitBounds(bounds, fitBoundsOptions);
      }
    },
    getMap() {
      if (this.map) {
        return Promise.resolve(this.map);
      }
      if (this._initPromise) {
        return this._initPromise.then(() => this.map);
      }
      return Promise.reject("地图未初始化");
    },
    loadMinemapAPI() {
      if (window.minemap) {
        return Promise.resolve();
      }
      if (window.loadMinemapAPIPromise) {
        return window.loadMinemapAPIPromise;
      }
      window.loadMinemapAPIPromise = Promise.all([
        this.loadScript(),
        // this.loadStyle(),
      ])
        .then((r) => {
          console.log("Minemap 资源加载成功", r);
          window.loadMinemapAPIPromise = null;
        })
        .catch((err) => {
          console.error("Minemap 资源加载错误:", err);
          window.loadMinemapAPIPromise = null;
        });
      return window.loadMinemapAPIPromise;
    },
    loadScript() {
      return new Promise((resolve, reject) => {
        const script = document.createElement("script");
        script.type = "text/javascript";
        script.async = true;
        script.defer = true;
        script.src = "https://map.hope.cmet1965.com:58000/minemapapi/v2.1.0/minemap.js";
        script.onload = () => {
          console.log("Minemap JS加载成功");
          resolve();
        };
        script.onerror = (err) => {
          console.error("Minemap JS加载错误:", err);
          reject();
        };
        document.body.appendChild(script);
      });
    },
    loadStyle() {
      return new Promise((resolve, reject) => {
        let link = document.createElement("link");
        link.rel = "stylesheet";
        link.type = "text/css";
        link.href = "https://map.hope.cmet1965.com:58000/minemapapi/v2.1.0/minemap-dark.css";
        link.onload = () => {
          console.log("Minemap CSS加载成功");
          resolve();
        };
        link.onerror = (err) => {
          console.error("Minemap CSS加载错误:", err);
          reject();
        };
        document.querySelector("head").appendChild(link);
      });
    },
    getThatRows(val, level) {
      if(!this.map) return
      this.selectLevel = level
      //获取当前选择的组织结构下的所有路段id / 当前选择的路段id
      let ids = []
      this.allRoads.forEach(ele => {
        if(level == 1 && ele.level == '3' && ele.provinceId == val) {
          ids.push(ele.organizationId)
        }
        if(level == 2 && ele.level == '3' && ele.pnode == val) {
          ids.push(ele.organizationId)
        }
      });
      if(level == 3) {
        ids.push(val)
      }
      //清除已有的线路的图层和路况
      if(this.selectLineLayer.length > 0) {
        for (let index = 0; index < this.selectLineLayer.length; index++) {
          const sid = this.selectLineLayer[index]
          this.map.getSource('linesource' + sid + '1') && this.map.removeSource('linesource' + sid + '1');
          this.map.getSource('linesource' + sid + '2') && this.map.removeSource('linesource' + sid + '2');
          this.map.getLayer('linelayer' + sid + '1') && this.map.removeLayer('linelayer' + sid + '1');
          this.map.getLayer('linelayer' + sid + '2') && this.map.removeLayer('linelayer' + sid + '2');
          this.map.getLayer('linesymbollayer' + sid + '1') && this.map.removeLayer('linesymbollayer' + sid + '1');
          this.map.getLayer('linesymbollayer' + sid + '2') && this.map.removeLayer('linesymbollayer' + sid + '2');
        }
      }
      this.markerDomListID = []
      //重置路况长度
      this.trafficInfo.closedTrafficMileage = 0
      this.trafficInfo.heavyCongestionMileage = 0
      this.trafficInfo.moderateCongestionMileage = 0
      this.trafficInfo.mildCongestionMileage = 0
      this.trafficInfo.patencyMileage = 0

      this.selectLineLayer = []

      // 需要绘制的线路
      let needDrawRoadList = []
      if(ids.length > 0) {
        for (let i = 0; i < ids.length; i++) {
          this.getRoadsLngLat(ids[i])
        }
      }
    },
    // 获取单条路段的经纬度
    async getRoadsLngLat(id, leng, idx) {

      if(!id) return
      const data = await getLonLatByAllRoads({sectionId: id, direction: 1})  // 1上行
      const data1 = await getLonLatByAllRoads({sectionId: id, direction: 2}) //2下行
      if(data.msgContent[0] && data1.msgContent[0]){
        this.selectLineLayer.push(id)
        //上行
        let arr = ''
        let msgContent = data.msgContent[0]
        data.msgContent.forEach((ele, index) => {
          let dou = ''
          if (index > 0) {
            dou = ','
          }
          arr =  arr + dou + ele.linePoints
        });
        msgContent.linePoints = arr

        //下行
        let arr1 = ''
        let msgContent1 = data1.msgContent[0]
        data1.msgContent.forEach((ele, index) => {
          let dou = ''
          if (index > 0) {
            dou = ','
          }
          arr1 =  ele.linePoints + dou + arr1
        });
        msgContent1.linePoints = arr1
        this.getAddLineLayer(msgContent)
        this.getAddLineLayer(msgContent1)
      }
    },
    //线路图层
    getAddLineLayer(item) {
      let linePoints = `[${item.linePoints}]`
      linePoints = JSON.parse(linePoints)
      let { map } = this
      //       linesource/linelayer/symbolLayerId(数据源/线路/线路上的文字) + 路段id + dir（1是上行 2是下行）
      const sourceId = 'linesource' + item.sectionId + item.dir
      const layeyId = 'linelayer' + item.sectionId + item.dir
      const symbolLayerId = 'linesymbollayer' + item.sectionId + item.dir
      var jsonData = {
        "type": "FeatureCollection",
        "features": [
          {
            "type": "Feature",
            "geometry": {
             "type": "LineString",
              "coordinates": linePoints
            },
            "properties": {
              "title": item.sectionName,
              "kind": item.sectionId
            },
          }
        ]
      };
      !this.map.getSource(sourceId) && map.addSource(sourceId, {
          "type": "geojson",
          "data": jsonData
        });

        let beforeIdtext = ''
        let beforeIdline = ''
        if (map.getLayer("point-outer-cluster-0")) {
          // point-outer-cluster-0 是视频监控的聚合图层
          beforeIdtext = 'point-outer-cluster-0'
          beforeIdline = 'point-outer-cluster-0'
        }
      //  设置addLayer的第二个参数beforeId，表示这个图层显示在beforeId的图层下面
      if(item.dir == 2) {
        beforeIdline = `linesymbollayer${item.sectionId}1`
      }
      // 线路图层
      !this.map.getLayer(layeyId) && map.addLayer({
        "id": layeyId,
        "type": "line",
        "source": sourceId,
        "layout": {
            "line-join": "round",
            "line-cap": "round",
            "border-visibility":"visible"  //是否开启线边框
          },
          
        "paint": {
            "line-width": 6,
            "line-color": {
              "type": "categorical",
              "property": "kind",
              "stops": [[1, "#7FAFFD"], [2, "#7FAFFD"]], 
              "default": "#7FAFFD" //4DBCFA
              },
                "line-border-width":1,  //设置线边框宽度
                "line-border-opacity":0.5, //设置线边框透明度
                "line-border-color":'#fff' //设置线边框颜色
          },
        },beforeIdline);
        //文字（高速路名称）图层
        !this.map.getLayer(symbolLayerId) && map.addLayer({
            "id": symbolLayerId,
            "type": "symbol",
            "source": sourceId,
            "layout": {
                "text-field": "{title}",
                "text-size": 14,
                "symbol-placement":"line",
            },
            "paint": {
                "text-color": "#ffffff",
                "text-halo-color": "#ffffff",
                "text-halo-width": 0.3,
            },
        }, beforeIdtext);
        if(this.selectLevel == 3) {
          const centerNum = Math.ceil(linePoints.length/2);
          let centerPoint = linePoints[centerNum]
          // 跳转至该线路
          map.flyTo({
            center: centerPoint,
            zoom: 9,
          })
        } 
        const qmz = JSON.parse(localStorage.getItem('mapCLkmz'))
        // this.map.moveLayer(layeyId, 'b5ebe9f4b52d23fb83170b4936b56429') //千米桩
        this.map.moveLayer(layeyId, qmz.MILESTONE_KM) //千米桩
        this.map.moveLayer(layeyId, qmz.MILESTONE_HM) //百米桩
    },
    fontLengthTowidth() {
      const obj = {
        
      }
    }
  },
  render() {
    const { loaded, $slots } = this;
    return (
      <div class="cm-map">
        <div ref="mapEl" class="cm-map__wrap">
          {!loaded ? (
            <div class="cm-map__loading">Loading...</div>
          ) : (
            $slots.default && $slots.default()
          )}
        </div>
      </div>
    );
  },
});
</script>

<style lang="scss">
@import "./style/map.scss";
.cm-map {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
}
.cm-map__wrap {
  position: relative;
  width: 100%;
  height: 100%;
}
.cm-map__loading {
  position: absolute;
  top: 50%;
  left: 50%;
  max-width: 40%;
  font-size: 32px;
  color: #0f2a3f;
  transform: translate(-50%, -50%);
}
.cm-map__loading img {
  width: 100%;
}
</style>
