import Overlay from 'ol/Overlay'
import KBaseObject from './KBaseObject';
import * as proj from 'ol/proj'
class Popup extends KBaseObject{
  constructor(lng,lat,url,offsetX,offsetY,width,height,mapInstance = null){
    super(mapInstance)
    const vm = this;
    vm.position = [lng,lat];
    vm.initPopup(lng,lat,url,offsetX,offsetY,width,height);

  }
  initPopup(lng,lat,url,offsetX,offsetY,width,height){
    //创建popup的容器
    const vm = this;
    vm.popupContainer = document.createElement("div");
    vm.popupContainer.style.position = "absolute";
    vm.popupContainer.style.width = width + "px";
    vm.popupContainer.style.height = height + "px";
    vm.popupContainer.style.top = "0px";
    vm.popupContainer.style.left = "0px";
    vm.popupContainer.style.zIndex = 1;
    // vm.popupContainer.style.display = "none";
    vm.popupContainer.style.background = "url(" + url + ") no-repeat";
    vm.popupContainer.style.backgroundSize = "100% 100%";
    // vm.popupContainer.innerHTML = "点击查看";
    //创建popup 
    vm.popup = new Overlay({
      element: vm.popupContainer,
      positioning: 'center-center',
      stopEvent: false,
      position: proj.fromLonLat([lng,lat]),
      offset: [offsetX,offsetY]
    });
    vm.mapInstance.map.addOverlay(vm.popup);    
  }
  setPostionAnimate(lng,lat,duration = 1000){
    const vm = this;
    let curLng = vm.position[0];
    let curLat = vm.position[1];
    let nextLng  = lng;
    let nextLat  = lat;
    // 计算经纬度的中间值差距
    let latDiff = (nextLng - curLng) / 100;
    let lngDiff = (nextLat - curLat) / 100;
    let j = 0;
    // 在当前坐标和下一个坐标之间插入 100 个中间值的经纬度
    let timer = setInterval(function (){
        let x = curLng + j * latDiff;
        let y = curLat + j * lngDiff;
        vm.popup.setPosition(proj.fromLonLat([x,y]));
        j++;
        if(j == 100){
          clearInterval(timer)
        }
    }, duration / 100)

  }
  setPosition(x,y){
    this.popup.setPosition(proj.fromLonLat([x,y]));
  }

  insertMiddleValues(coordinates) {
    // 初始化一个新的数组
    let result = [];

    // 循环遍历所有的坐标
    for (let i = 0; i < coordinates.length - 1; i++) {
      // 获取当前坐标和下一个坐标
      let current = coordinates[i];
      let next = coordinates[i + 1];

      // 计算经纬度的中间值差距
      let latDiff = (next[0] - current[0]) / 200;
      let lngDiff = (next[1] - current[1]) / 200;

      // 将当前坐标添加到结果数组
      result.push(current);

      // 在当前坐标和下一个坐标之间插入 200 个中间值的经纬度
      for (let j = 1; j < 200; j++) {
        let lat = current[0] + j * latDiff;
        let lng = current[1] + j * lngDiff;
        result.push([lat, lng]);
      }
    }
    // 添加最后一个坐标到结果数组
    result.push(coordinates[coordinates.length - 1]);

    return result;
  }

  remove(){
    const vm = this;
    if(vm.popup){
      vm.mapInstance.map.removeOverlay(vm.popup);
      vm.popup = null;
    }
  }
}

export default Popup;