import config from "@/api/config.js";
import * as KMap from "@/utils/ol-map/KMap";
import * as util from "@/common/ol_common.js";
import Point from "ol/geom/Point.js";
import Feature from "ol/Feature";
import VectorLayer from "ol/layer/Vector.js";
import WKT from "ol/format/WKT.js";
import ScaleLine from "ol/control/ScaleLine";
import { useRouter } from "vue-router";
import { unByKey } from "ol/Observable";
import Style from "ol/style/Style";
import Icon from "ol/style/Icon";
import { Cluster, Vector as VectorSource } from "ol/source";
import { Fill, Circle, Stroke } from "ol/style";
import { newPoint } from "@/utils/map";
import eventBus from "@/api/eventBus";
import Overlay from 'ol/Overlay'

/**
 * @description 地图层对象
 */
class SamplePointLayer {
  constructor(map, organId, regionId) {
    let that = this;
    this.farmId = organId
    this.regionId = regionId
    let vectorStyle = new KMap.VectorStyle();
    this.vectorStyle = vectorStyle;
    this.clusterSource = new Cluster({
      distance: 10,
      minDistance: 10,
    });
    this.mapRef = map

    this.curPoint = null
    this.curArea = null
    this.isUpdatePoint = null
    this.isUpdateArea = null

    this.treeClusterLayer = new KMap.VectorLayer("tree-cluster", 999, {
      minZoom: 15,
      source: this.clusterSource,
      style: (f) => this.getStyle(f)
    })
    // map.addLayer(this.treeClusterLayer.layer)

    this.addMapSingerClick(map.map);

    // 对比
    this.isCompare = false
    this.comparePointArr = []
    eventBus.off("compareTree")
    eventBus.on("compareTree", (val) => {
      that.isCompare = val
      if (val === false) {
        that.comparePointArr.map(fs => {
          fs.set("activeCompare", false)
        });
      }
    })

    this.figghtStatusStyle = vectorStyle.getPointSimpleStyle(5,"#eebd0a", "#f5efef", 1)
    eventBus.on('farmFightTask:changeShowStatus',function(list){
      if(that.features && that.features.length > 0){
        that.features.forEach(item => {
          let index =list.findIndex((geohash)=> geohash === item.get('geoHashSample'))
          if(index!== -1){
            item.set("showFightStatus", 1)
          }
        })
        that.treeClusterLayer.layer.changed()
      }
    })

    // 果园档案
    that.fileLegend = []
    eventBus.off("change:mapPoint")
    eventBus.on("change:mapPoint", async (field) => {
      if (!this.fileLegend.length) {
       await VE_API.farm.fetchLegendList().then(({data}) => {
          this.fileLegend = data
        })
      }
      const colorObj = that.fileLegend.find(item => item.code === field)
      that.togglePointType(null, colorObj, true)
      colorObj.list = colorObj.items
      eventBus.emit("changePointLegend", {colorObj})
    })
    that.blueRegionLayer = null
    that.pointType = ""
    that.pointArr = []
    that.features = []


    // 切换点位图标
    eventBus.off("changePointType")
    eventBus.on("changePointType", ({ legend, colorObj }) => {
      that.togglePointType(legend, colorObj)
    })

  }

  clearComparePoints() {
    try {
      // Reset visual state on previously selected features
      if (this.comparePointArr && this.comparePointArr.length) {
        this.comparePointArr.forEach((feature) => {
          feature && feature.set && feature.set("activeCompare", false);
        });
      }
      // Clear internal array and emit update to hide compare button upstream
      this.comparePointArr = [];
      eventBus.emit("clickToCompare:point", this.comparePointArr);
    } catch (e) {
      // no-op
    }
  }

  getIconStyle(feature) {
    const showFightStatus = feature.get('showFightStatus')
    if(showFightStatus){
      return this.figghtStatusStyle
    }
    const color = feature.get("color")
    const noImg = feature.get("noImg")
    const activeCompare = feature.get('activeCompare')
    let style = new Style({
      image: new Icon({
        src: activeCompare ? '/src/assets/images/map/active-icon-small.png' : feature.get('icon'),
        // src: `/src/assets/images/map/${feature.get('iconName')}-icon.png`,
        scale: activeCompare ? 0.5 : feature.get('scale'),
      })
    });

    let style2 = new Style({
      image: new Circle({
        radius: 6,                             // 半径
        stroke: new Stroke({           // 边界样式
          color: noImg ? 'transparent' : '#fff',                    // 边界颜色
          width: 2                            // 边界宽度
        }),
        fill: new Fill({               // 填充样式
          color                    // 填充颜色
        })
      })
    });
    return color ? (activeCompare ? style : style2) : style
  }
  //多点的过滤方法
  manyFeatureFilter(features) {
    let res = features[0]
    if (features.length == 1) {
      return res
    }
    for (let item of features) {
      res = res.get('status') > item.get('status') && item.get('noImg') === 0 && item.get('wys') === 1 ? res : item
    }
    return res;
  }
  //得到点样式
  getStyle(feature) {
    feature = this.manyFeatureFilter(feature.get('features'))
    return this.getIconStyle(feature)
  }

  initData(farmId, regionId,isInit = false,matchedData = []) {
    let that = this
    let selectAll = undefined
    if (regionId === 0) {
      selectAll = 1
    }
    const areaId = selectAll ? undefined : regionId
    VE_API.variety.pointList({ farmId, regionId: areaId, selectAll }).then(({ data }) => {
      this.pointArr = data
      let features = []
      for (let item of data) {
        item.iconName = 'defalut'
        that.getIcon(item)
        let point = newPoint(item);
        features.push(point)
      }
      const source = new VectorSource({
        features: features,
      });
      that.clusterSource.setSource(source)

      
      const layers = that.mapRef.map.getLayers().getArray();
      const exists = layers.includes(that.treeClusterLayer.layer);

      if (!exists) {
        that.mapRef.addLayer(that.treeClusterLayer.layer);
      }
      setTimeout(() => {
        that.mapRef.fit(that.clusterSource.source.getExtent(), { padding: [100, 100, 100, 100] })
      }, 100)

      if (isInit) {
        that.updatePointColors(matchedData)
      }
    })
  }

  togglePointType(sampleData, colorObj, isFile) {
    let that = this
    that.clearCluster()
    if (!sampleData) {
      let features = []
      for (let item of this.pointArr) {
        item.iconName = 'defalut'
        that.getIcon(item)
        if (isFile && colorObj) {
          const fieldVal = Number(item[colorObj.code])
          const legendItem = colorObj.items.find((colorItem) => {
            return fieldVal >= colorItem.range[0] && fieldVal <= colorItem.range[1];
          })
          const color = legendItem ? legendItem.color : null;
          item.color = color
        } else {
          item.color = null
        }
        let point = newPoint(item);
        features.push(point)
      }
      const source = new VectorSource({
        features: features,
      });
      that.clusterSource.setSource(source)
      setTimeout(() => {
        that.mapRef.fit(that.clusterSource.source.getExtent(), { padding: [100, 100, 100, 100] })
      }, 100)
      return
    }
    eventBus.emit("resetFileActive", colorObj.key || colorObj.name)


    // 创建一个映射表：geoHashSample -> color
    const geoHashToColorMap = {};

    colorObj.list.forEach(legendItem => {
      const geoHashes = sampleData.obj[legendItem.val] || [];
      geoHashes.forEach(geoHash => {
        geoHashToColorMap[geoHash] = legendItem.color;
      });
    });

      // 3. 更新pointArr中的颜色
      let features = []
      this.pointArr.map(point => {
        if (point.geoHashSample in geoHashToColorMap) {
            point.iconName = 'defalut'
            point.color = geoHashToColorMap[point.geoHashSample]
            that.getIcon(point)
            let pointRes = newPoint(point);
            features.push(pointRes)
        } else {
          point.iconName = 'defalut'
          point.color = "#DDDDDD"
          that.getIcon(point)
          let pointRes = newPoint(point);
          features.push(pointRes)
        }
      })

        const source = new VectorSource({
          features: features,
        });
        that.clusterSource.setSource(source)

  }

  toggleFilePoint(arr) {
    let that = this
    // 清除旧的 blueRegionLayer 图层
    // that.clearCluster()
    if (that.blueRegionLayer) {
      that.blueRegionLayer.source.clear();
    }
    if (arr && arr.length > 0) {
      let features = []
      for (let item of arr) {
        item.iconName = 'defalut'
        that.getIcon(item)
        let point = newPoint(item);
        features.push(point)
      }
      const source = new VectorSource({
        features: features,
      });
      that.clusterSource.setSource(source)
      setTimeout(() => {
        that.mapRef.fit(that.clusterSource.source.getExtent(), { padding: [100, 100, 100, 100] })
      }, 100)
    }
  };

  addMapSingerClick(kmap) {
    let that = this
    // 创建弹窗图层
    this.popup = new Overlay({
      element: document.getElementById('popup-file'),
      positioning: 'right-center',
      offset: [0, 0],
    });
    kmap.addOverlay(this.popup);
    // 点击地图弹窗的关闭-销毁dom
    // eventBus.on("map:destroyPopup", () => {
    //   that.popup.setPosition(undefined)
    // })
    kmap.on("singleclick", (evt) => {
      let hasFeature = false
      kmap.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
        if (layer instanceof VectorLayer && layer.get("name") === "tree-cluster") {
          hasFeature = true
          if (that.curPoint) {
            that.curPoint.set("iconName", "defalut");
          }
          const featureArr = feature.get("features")
          let fs = featureArr[0]
          for (let item of featureArr) {
            fs = fs.get('status') > item.get('status') ? fs : item
          }
          that.curPoint = fs
          if (that.isUpdatePoint) {
            fs.set("iconName", "active");
          }
          if (!that.isCompare) {
            const noImg = fs.get("noImg")
            if (noImg === 1) {
              // 尝试多种可能的字段作为sampleId
              const possibleSampleIds = [
                fs.get('sampleId'),
                fs.get('id'),
                fs.get('treeId'),
                fs.get('workCode'),
                fs.get('sampleCode'),
                fs.get('geoHashSample')
              ].filter(id => id !== undefined && id !== null);
              
              
              const sampleId = possibleSampleIds[0];
              if (!sampleId) {
                return;
              }
              
              VE_API.home.getSampleFilesWithParams({ sampleId }).then(({data, code}) => {
                if (code === 0) {
                  // 保存当前sampleId供后续使用
                  that.currentSampleId = sampleId
                  // 处理数据并渲染到DOM
                  that.renderFileDataToDom(data, fs.get("nonghu") == 1, sampleId)
                  that.popup.setPosition(evt.coordinate)
                }
              }).catch(() => {})
            } else {
              eventBus.emit("click:point", { farmId: fs.get("farmId"), sampleId: fs.get("sampleId"), data: fs.getProperties() })
            }
          } else {
            // fs.set("iconName", "active")
            fs.set("activeCompare", fs.get("activeCompare") ? false : true);
            if (fs.get("activeCompare")) {
              that.comparePointArr.push(fs)
            } else {
              that.comparePointArr = that.comparePointArr.filter(item => item.get("id") !== fs.get("id"))
            }

            if (that.comparePointArr.length > 2) {
              that.comparePointArr[0].set("activeCompare", false);
              that.comparePointArr.shift();
            }
            // fs.set("icon", require('@/assets/images/map/active-icon-small.png'));
            eventBus.emit("clickToCompare:point", that.comparePointArr)
          }
        }
      })
      if (!hasFeature) {
        kmap.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
          if (layer instanceof VectorLayer && layer.get("name") === "regionLayer") {
            hasFeature = false
            if (that.curArea) {
              that.curArea.set("bgName", "defalut");
            }
            that.curArea = feature
            if (that.isUpdateArea) {
              feature.set("bgName", "active");
              eventBus.emit("click:updateArea", { name: feature.get("id"), value: feature.get("blueZone") })
            } else {
              eventBus.emit("click:area", { name: feature.get("id"), value: feature.get("highYield") })
            }
          }
        })
        if (that.isCompare) {
          eventBus.emit("quitCompare")
          eventBus.emit("compareTree", false)
        }
        if (that.popup) {
          that.popup.setPosition(undefined)
        }
      }
    })
  }

  resetPoint() {
    this.isUpdatePoint = null
    if (this.curPoint) {
      // this.curPoint.set("iconName", "defalut");
      this.curPoint.set("activeCompare", false);
    }
  }

  updatePointStatus(e) {
    this.isUpdatePoint = e
  }

  updateAreaStatus(e) {
    this.isUpdateArea = e
  }

  // 切换点位数据

  getIcon(item) {
    // let imgSrc = require(`@/assets/images/map/${item.iconName}-icon.png`)
    let imgSrc = '/src/assets/images/map/status/status-zc.png'
    let scale = 0.8
    if (item.status == 1) {
      imgSrc = '/src/assets/images/map/status/status-szyc.png'
    }
    if (item.status == 2) {
      imgSrc = '/src/assets/images/map/status/status-bh.png'
    }
    if (item.status == 3) {
      imgSrc = '/src/assets/images/map/status/status-ch.png'
    }

    if (item.wys === '1') {
      scale = 0.3
      imgSrc = '/src/assets/images/map/status/wns.png'
    }

    // if (item.farmId === 90263) {
    // }
    if (item.noImg === 1) {
      imgSrc = '/src/assets/images/map/status/defalut-icon.png'
      scale = 0.3
    }
    if (item.nonghu === 1) {
      imgSrc = '/src/assets/images/map/status/nonghu-icon.png'
      scale = 0.3
    }

    item["icon"] = imgSrc
    item["scale"] = scale
  }

  reset(farm, region) {
    this.clearCluster()
    this.initData(farm.id, region.id)
  }

  // 根据matchedData更新点位颜色
  updatePointColors(matchedData) {
    let that = this;
    
    if (!this.pointArr || this.pointArr.length === 0) {
      // pointArr is empty, skip
      return;
    }
    
    if (!matchedData || matchedData.length === 0) {
      // matchedData is empty, skip
      return;
    }
    
    // 创建匹配数据的映射表，尝试多种可能的匹配字段
    const matchedDataMap = new Map();
    matchedData.forEach(item => {
      // 尝试多种可能的匹配字段
      const possibleKeys = [
        item.geoHashSample,
        item.sampleId, 
        item.id,
        item.workCode,
        item.sampleCode
      ].filter(key => key !== undefined && key !== null);
      
      possibleKeys.forEach(key => {
        matchedDataMap.set(String(key), item);
      });
    });
    
    // 更新pointArr中的颜色
    let features = [];
    let matchedCount = 0;
    
    this.pointArr.forEach(point => {
      // 尝试多种可能的匹配字段
      const possibleKeys = [
        point.geoHashSample,
        point.sampleId,
        point.id,
        point.workCode,
        point.sampleCode
      ].filter(key => key !== undefined && key !== null);
      
      let matchedItem = null;
      for (const key of possibleKeys) {
        matchedItem = matchedDataMap.get(String(key));
        if (matchedItem) {
          matchedCount++;
          break;
        }
      }
      
      if (matchedItem) {
        // 找到匹配的数据，使用其颜色
        point.iconName = 'defalut';
        point.color = matchedItem.color;
        that.getIcon(point);
        let pointRes = newPoint(point);
        features.push(pointRes);
      } else {
        // 没有匹配的数据，使用默认颜色
        point.iconName = 'defalut';
        point.color = "#DDDDDD";
        that.getIcon(point);
        let pointRes = newPoint(point);
        features.push(pointRes);
      }
    });
    
    // 更新图层
    const source = new VectorSource({
      features: features,
    });
    that.clusterSource.setSource(source);
    
    // 更新features引用
    that.features = features;
    
  }

  // 渲染文件数据到DOM
  renderFileDataToDom(data, isNonghu, sampleId) {
    let that = this;
    
    // 清空之前的数据
    const fileTextEl = document.getElementById('file-text');
    const fileOverviewEl = document.getElementById('file-overview');
    const fileOutputEl = document.getElementById('file-output');
    const fileQualityEl = document.getElementById('file-quality');
    
    if (fileTextEl) fileTextEl.innerHTML = '';
    if (fileOverviewEl) fileOverviewEl.innerHTML = '';
    if (fileOutputEl) fileOutputEl.innerHTML = '';
    if (fileQualityEl) fileQualityEl.innerHTML = '';
    
    // 重置标题为默认值
    eventBus.emit('update:fileTitles', { type: 'firstTitle', value: '总体档案' });
    eventBus.emit('update:fileTitles', { type: 'secondTitle', value: '产量信息' });
    eventBus.emit('update:fileTitles', { type: 'thirdTitle', value: '生态评估' });
    

    // 处理数据块
    data.forEach((item, index) => {
      if (item.name && item.indicators && item.indicators.length > 0) {
        // 处理所有数值，整数不保留小数，小数保留两位
        const processedIndicators = item.indicators.map((indicator) => {
          if (
            indicator.val !== "--" &&
            indicator.val !== null &&
            indicator.val !== undefined &&
            !isNaN(parseFloat(indicator.val))
          ) {
            const num = parseFloat(indicator.val);
            // 判断是否为整数
            const isInteger = Number.isInteger(num);
            return {
              ...indicator,
              val: isInteger ? num.toString() : num.toFixed(2),
            };
          }
          return indicator;
        });

        // 总体档案（第一个数据块）
        if (index === 0) {
          // 更新第一个数据块的标题
          const firstTitleEl = document.querySelector('#popup-file .overview-file:first-child .box-title');
          if (firstTitleEl) {
            firstTitleEl.textContent = item.name;
          }
          // 通过事件总线更新Vue组件中的标题
          eventBus.emit('update:fileTitles', { type: 'firstTitle', value: item.name });
          
          // 渲染基础数据
          const baseDataHtml = processedIndicators.map(indicator => `
            <div class="base-item">
              <span class="label">${indicator.name}</span>
              <div class="value">${indicator.val || "--"}${indicator.unit || ""}</div>
            </div>
          `).join('');
          if (fileOverviewEl) {
            fileOverviewEl.innerHTML = baseDataHtml;
          }
        } else {
          // 其他数据块渲染为指标数据
          const indicatorsHtml = processedIndicators.map(indicator => `
            <div class="box-item">
              <div class="item-name">${indicator.name}</div>
              <div class="item-val">${indicator.val || "--"}${indicator.unit || ""}</div>
            </div>
          `).join('');


          // 按顺序分配标题和数据容器
          if (index === 1) {
            // 第二个数据块 -> 第二个标题容器
            const outputTitleEl = document.querySelector('#popup-file .overview-file:nth-child(2) .box-title');
            if (outputTitleEl) {
              outputTitleEl.textContent = item.name;
            }
            // 通过事件总线更新Vue组件中的标题
            eventBus.emit('update:fileTitles', { type: 'secondTitle', value: item.name });
            if (fileOutputEl) {
              fileOutputEl.innerHTML = indicatorsHtml;
            }
          } else if (index === 2) {
            // 第三个数据块 -> 第三个标题容器
            const qualityTitleEl = document.querySelector('#popup-file .overview-file:nth-child(3) .box-title');
            if (qualityTitleEl) {
              qualityTitleEl.textContent = item.name;
            }
            // 通过事件总线更新Vue组件中的标题
            eventBus.emit('update:fileTitles', { type: 'thirdTitle', value: item.name });
            if (fileQualityEl) {
              fileQualityEl.innerHTML = indicatorsHtml;
            }
          }
          // 如果有更多数据块，可以继续扩展
        }
      }
    });

    // 获取语音信息数据
    VE_API.home.getSpeakInfo({ sampleId }).then(({ data, code }) => {
      if (code === 0) {
        const photoList = data || [];
        const listHtml = photoList.map(item => `
          <div class="list-item">
            <div class="list-name">
              <img src="${require('@/assets/images/common/title-icon.png')}" alt="" />
              ${item.speakTitleName || "--"}
            </div>
            ${item.content?.renderedContent || "--"}
          </div>
        `).join('');
        if (fileTextEl) {
          fileTextEl.innerHTML = listHtml;
        }
      }
    }).catch(() => {});

    // 显示小农户标签
    const tagNhEl = document.getElementById('tag-nh');
    if (tagNhEl) {
      tagNhEl.style.display = isNonghu ? "inline-block" : 'none';
    }
  }

  // 清除聚合图层，解除绑定
  clearCluster() {
    if (this.treeClusterLayer && this.treeClusterLayer.layer.getSource() && this.treeClusterLayer.layer.getSource().getSource()) {
      this.treeClusterLayer.layer.getSource().getSource().clear()
    }
  }
}

export default SamplePointLayer;
