//这个是基于ceisum的二开，所以有些api不大相同
// 区域划分的颜色配置
import regionResult from './regionTreeResult.json'

const CooGL = window.CooGL;

// 调试开关
const DEBUG = false;

// API基础URL配置
const API_BASE_URLS = {
  // 直接地址
  DIRECT: {
    REGION_API: 'https://10.1.174.34:13600/kelan/api',
    GRID_RANGE_API: 'https://10.1.174.34:13600/grid-range'
  },
  // 相对地址（代理）
  PROXY: {
    REGION_API: '/region/coogl/api',
    GRID_RANGE_API: '/grid-range'
  }
};

// 是否使用直接地址（true: 使用直接地址, false: 使用代理地址）
const USE_DIRECT_URL = false;

// 获取当前使用的API基础URL
const getApiBaseUrl = (type) => {
  return USE_DIRECT_URL ? API_BASE_URLS.DIRECT[type] : API_BASE_URLS.PROXY[type];
};

// 调试日志函数
const logInfo = (...args) => {
  if (DEBUG) {
    console.log(...args);
  }
};
const logError = (...args) => {
  if (DEBUG) {
    console.error(...args);
  }
};

export class CooglLoadArea {
  params = {
    regionCode: '',
    gridType: '',
    startTime: '',
    endTime: '',
    dataCode: '',
    hasChildren: 1,
  }
  constructor(viewer, token) {
    
    console.log('====> 初始化 CooglLoadArea', viewer, token);
    this.viewer = viewer
    //区域图标标注
    this.imageGraphicList = []
    this.polygonGraphicList = []
    //社区、村的标注
    this.imageGraphicListOfCommunity = []
    this.pickHandler = null
    this.regionResult = regionResult.data
    this.token = token ?? CooGL.CooServer.defaultAccessToken
    logInfo('====> CooglLoadArea 初始化完成，token:', this.token);
    // this.mapInit()
  }

  async mapInit() {
    console.log('====> 开始初始化地图');
    if (this.pickHandler) {
      logInfo('====> 清除已有的 pickHandler');
      this.pickHandler()
      this.pickHandler = null
    }

    //清除画布
    this.clear()
    //默认加载一次市级的标注上图
    logInfo('====> 设置 pickHandler');
    this.pickHandler = this.viewer.event.pick(e => {
      logInfo('====> 触发 pick 事件:', e);
      const regionCode = e?.primitive?.description?.code
      this.params.regionCode = regionCode
      logInfo('====> 获取到区域编码:', regionCode);
      if (!regionCode) return
      //在这里判断 如果是社区、村的级别执行 setPoints
      //示例 判断条件根据实际情况而定
      //4 6 9 12
      const isLevel4 = regionCode?.length === 12
      logInfo('====> 是否为社区/村级别:', isLevel4);
      if (isLevel4) {
        this.setPoints(false)
      } else {
        this.addArea(false)
      }
    })
    logInfo('====> 开始添加初始区域');
    await this.addArea(true)
    logInfo('====> 地图初始化完成');
  }

  /**
   * 添加区域
   * @param {string} regionCode - 区域编码
   * @param {string} gridtype - 网格类型
   *                           01：城市部件
   *                           02：事件
   *                           03：资源
   *                           04：单元网格
   *                           05：责任网格
   *                           06：任意网格
   *                           07：资源网格
   *                           08：感知设备
   * @param {string} startTime - 开始时间 格式：yyyy-MM-DD HH:mm:ss 可选
   * @param {string} endTime - 结束时间 格式：yyyy-MM-DD HH:mm:ss 可选
   */

  async addArea(clearData = false) {
    logInfo('====> 开始添加区域, clearData:', clearData, '当前参数:', this.params);
    const params = { ...this.params }
    if (clearData) {
      logInfo('====> 清除所有数据');
      this.clear()
    } else {
      logInfo('====> 清除当前区域数据');
      this.clearCurrentAreaData()
    }
    const list = this.findRegionByCode(params.regionCode, true)
    logInfo('====> 找到子区域:', list?.length, list);
    
    logInfo('====> 开始获取区域详情');
    try {
      const resList = await Promise.all([
        this.getRigionDetailByCode(params.regionCode),
        ...list.map(({ id }) => this.getRigionDetailByCode(id)),
      ]);
      logInfo('====> 获取到区域详情列表:', resList);
      
      if (!resList[0] || !resList[0].features || !resList[0].features[0]) {
        logError('====> 错误: 无法获取区域详情或数据格式不正确');
        return;
      }
      
      let positions = resList[0].features[0].geometry.coordinates.flat(Infinity)
      logInfo('====> 解析坐标数据, 原始坐标:', positions);
      
      // 将扁平化的坐标数组重新组装成对象数组
      const positionObjects = []
      for (let i = 0; i < positions.length; i += 2) {
        positionObjects.push({
          x: positions[i],
          y: positions[i + 1],
          z: 0,
        })
      }
      positions = positionObjects
      logInfo('====> 坐标解析完成:', positions);
      
      // 添加多边形图层
      logInfo('====> 移动视角到多边形');
      this.moveViewToPolygon(positions)
      const sons = resList.slice(1)
      logInfo('====> 添加子区域多边形, 子区域数量:', sons.length);
      for (const res of sons) {
        this.addPolygon(res)
      }
      
      logInfo('====> 开始获取分析数据');
      const apiUrl = `${getApiBaseUrl('REGION_API')}/es/v1.0/bigdata_search_analysis`;
      logInfo('====> 分析数据请求URL:', apiUrl);
      fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          token: this.token,
        },
        body: JSON.stringify(params),
      })
        .then(res => {
          logInfo('====> 获取分析数据响应:', res);
          return res.json();
        })
        .then(res => {
          logInfo('====> 获取到分析数据:', res);
          const obj = res.data
          delete obj[params.regionCode]
          logInfo('====> 处理分析数据, 子区域数据:', obj);
          Object.entries(obj).map(([key, value]) => {
            logInfo('====> 处理区域:', key, value);
            const detailItem = sons.find(item => item.features[0].id === key)
            if (!detailItem) {
              logInfo('====> 未找到对应的子区域详情:', key);
              return;
            }
            const { _center, _name } = detailItem.features[0].properties
            const center = _center.split(',')
            const position = {
              x: center[0],
              y: center[1],
              z: 0,
            }
            const item = {
              num: value[0].num,
              code: key,
              position,
              name: _name,
            }
            logInfo('====> 添加图标:', item);
            this.addImage(item)
          })
        })
        .catch(error => {
          logError('====> 获取分析数据出错:', error);
        });
    } catch (error) {
      logError('====> 添加区域出错:', error);
    }
  }

  //获取指定regionCode的区域的经纬度以及中心点和下级区域的所有经纬度
  //FIXME: 这个接口需要自己实现
  async getRigionDetailByCode(regionCode) {
    if (!regionCode) return Promise.reject('regionCode is required')
    //参考已有代码
    // 获取geojson格式的区域边界数据
    // 获取txt格式的区域边界数据
    logInfo('====> 获取区域详情:', regionCode);
    
    try {
      const apiUrl = `${getApiBaseUrl('GRID_RANGE_API')}/unit/${regionCode}`;
      logInfo('====> 请求URL:', apiUrl);
      const response = await fetch(apiUrl);
      logInfo('====> 区域详情响应:', response);
      
      if (!response.ok) {
        logError('====> 获取区域详情失败:', response.status, response.statusText);
        throw new Error(`获取区域详情失败: ${response.status} ${response.statusText}`);
      }
      
      const data = await response.json()
      logInfo('====> 获取到区域详情数据:', data);
      
      return data;
    } catch (error) {
      logError('====> 获取区域详情出错:', error);
      // 返回一个备用数据结构
      return {
        features: [
          {
            id: regionCode,
            geometry: {
              coordinates: [[[103.8, 30.5], [104.1, 30.5], [104.1, 30.8], [103.8, 30.8], [103.8, 30.5]]],
              type: 'Polygon'
            },
            properties: {
              _center: '103.95,30.65',
              _name: `区域 ${regionCode}`
            }
          }
        ]
      };
    }
  }

  addImage({ num, code, position, name }) {
    logInfo('====> 添加图标, code:', code, 'position:', position, 'name:', name);
    this.viewer
      .addLayer(
        CooGL.Layer.fromImageTextLabel({
          id: code,
          description: {
            code,
            name,
          },
          image:
            'data:image/png;base64, ',
          position,
          textContent: num,
          font: '30px simsum',
          pixelOffset: { x: 10, y: -92 },
          fillColor: '#fff',
          style: CooGL.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 4,
          outlineColor: '#000',
        }),
      )
      .then(res => {
        logInfo('====> 图标添加成功:', code);
        this.imageGraphicList.push(res)
      })
      .catch(error => {
        logError('====> 添加图标失败:', code, error);
      });
  }
  addCommunityImage(obj) {
    logInfo('====> 添加社区图标:', obj);
    this.viewer
      .addLayer(
        CooGL.Layer.fromImageTextLabel({
          id: obj.id,
          description: {
            isCommunityImage: true,
            detail: obj,
          },
          image:
            'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAACACAYAAABNyOryAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAnLSURBVHgB7Vt5TBzXGf8CLAwsywLLGh8cAQwEEg7HqQ0+2tiOiiI1VZpY7iXb6h+x0qbNP7HVWOmlNFaaWq2qHpYaV1VTV4qaWyqt66bYrl0b46MGbONy3+ey7CywyyzL0fcb76xnNhwzLDCNND/pefa9fTP7/d53vO99Yx6g5UEcayWspbNmC1xjA+MSnIHWHWhNgX5YeICWDgi3h7W8QFsKelj7J4VBZikEJMF3k3KFw8Vl1ipJ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W9sm4V/pEI4JAsHtOgotYecuMENN+DkCp0uprdC/2Yo/P0ogJpAZOJv92mKAIrzsT4sSrpm7fPUCf9n4FVJeSlRbxLEM1JbpfBUgW0cO6GQl26AkXfkMp1pfRBTkChhZMfUhfb9TSdmFYCPNt5UbGWDaFSHXTm0MgAZmIChoh09DdUj7BKOgHCv8xkkJXbnSRbfWCu2HyH7tWITKwmOXWnjVw7HyV7VCSFlblqBWL+q7+n281dwWIuLOQNUlHcxQSUPcQa6dAI+UHisQJKjo1ZnQo1hP/Bm1Qf8urpd6y1h86db3eU6vBi7QUkrt8lJztQp6w0CZjN4V9SrWzlAdj9hbnmL1SXkcKWSALmdPY6DSZbKQK1SloBINr8+CQ1Dt5/JwBA+Mr57lHzkg+mdJBkL/lQ/D2yn3LZZqepijEfsEmxvacrJM+Bzb/DWvVC92p5zfoSkbJqh7c3e1kpsjiXbJxG04Kds5cXg5fqyBkiOAATPkHL9JpVDrw/eGquL1B4Lc0nK3sJaEV5hh2MOIkUhEXrdpBn2EUChG5oJU/I20hA2osqSSWW8l8NbAES5bR8kAQPZgNqEc5/9gARZLBIAtNpaUAWjGChWXAJ4RCQQyIDIqh0p5DSXyAcwqKYwweudbREoVcds7OzP6QVwqqmBysBg4DeMAjoDYOA3jAI6A2DgN4wCOgNg4DeMAjoDYOA3jAI6A2DgN4wCOgNg4DeMAjoDYOA3jAI6A2DgN4wCOgNg4DeMAjoDYOA3jAI6A2DgN4wCOgNg4DeMAjoDYOA3jAI6A2DgN4wCOgNg4DeMAjoDYOA3jAI6A2DgN4wCOgNg8BimJ2dxR9Nl7HrwcDnTxeY0B/O3sc5WmYs11+zzgtIrfhBBlpGrIYPnJd9/oiWGauhAdj9wUD3LaYAnpYR/wM3D4Q4csAAcAAAAABJRU5ErkJggg==',
          position: { x: obj.longitude, y: obj.latitude, z: 0 },
          textContent: obj.name,
          font: '22px simsum',
          pixelOffset: { x: 0, y: -150 },
          fillColor: '#fff',
          style: CooGL.LabelStyle.FILL_AND_OUTLINE,
          outlineWidth: 4,
          distanceDisplayCondition: new CooGL.DistanceDisplayCondition(
            0,
            10000,
          ),
          outlineColor: '#000',
        }),
      )
      .then(res => {
        logInfo('====> 社区图标添加成功:', obj.id);
        this.imageGraphicListOfCommunity.push(res)
      })
      .catch(error => {
        logError('====> 添加社区图标失败:', obj.id, error);
      });
  }
  addPolygon(polygonData) {
    logInfo('====> 添加多边形, 数据:', polygonData.features[0].id);
    const id = polygonData.features[0].id + '-' + Math.random()
    this.viewer
      .addLayer(
        CooGL.Layer.fromGeoJsonGraphicResource({
          id,
          resource: polygonData,
          customPolygonLabelOptions: function (positions, properties) {
            const center = properties._center.split(',')
            const textPosition = { x: center[0], y: center[1], z: 0 }
            return {
              positions,
              material: '#0B304B',
              textPosition,
              outline: true,
              outlineColor: '#36A6F5',
              outlineWidth: 5,
              fillColor: '#fff',
              font: '32px simsum',
              textContent: properties._name,
            }
          },
        }),
      )
      .then(res => {
        logInfo('====> 多边形添加成功:', id);
        this.polygonGraphicList.push(res)
      })
      .catch(error => {
        logError('====> 添加多边形失败:', id, error);
      });
  }

  //获取村、社区下的特定网格类型点位并上图
  async setPoints(clearData = false) {
    logInfo('====> 开始设置点位, clearData:', clearData, '区域编码:', this.params.regionCode);
    if (clearData) {
      logInfo('====> 清除所有数据');
      this.clear()
    }
    try {
      const res = await this.getRigionDetailByCode(this.params.regionCode)
      logInfo('====> 获取到区域详情:', res);
      
      if (!res || !res.features || !res.features[0] || !res.features[0].geometry || !res.features[0].geometry.coordinates) {
        logError('====> 区域详情数据格式不正确');
        return;
      }
      
      const coordinates = res.features[0].geometry.coordinates[0]
        .map(([x, y]) => `${x},${y}`)
        .join(';')
      logInfo('====> 生成坐标字符串:', coordinates);
      
      // 构造请求参数
      const params = {
        regionCode: this.params.regionCode,
        dataCode: this.params.dataCode,
        gridtype: this.params.gridType,
        startTime: this.params.startTime,
        endTime: this.params.endTime,
        coordinates,
      }
      logInfo('====> 请求参数:', params);
      
      // 发送POST请求获取点位数据
      logInfo('====> 开始获取点位数据');
      const apiUrl = `${getApiBaseUrl('REGION_API')}/es/v1.0/search`;
      logInfo('====> 点位数据请求URL:', apiUrl);
      const response = await fetch(apiUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          token: this.token,
        },
        body: JSON.stringify(params),
      })
      logInfo('====> 点位数据响应:', response);
      
      // 解析响应数据
      // const res1 = await response.json()
      const { data: pointData } = await response.json()
      logInfo('====> 获取到点位数据:', pointData);
      const { component, event, resource } = pointData.data
      for (const v of component) {
        this.addCommunityImage(v)
      }
          
      // 遍历点位数据添加标注
      pointData.forEach(async point => {
        const position = {
          x: point.longitude,
          y: point.latitude,
          z: point.altitude || 35,
        }

        const item = await this.addImage(point.num, point.code, position)
        this.imageGraphicList.push(item)
      })

      // 移动视角到点位区域
      if (pointData.length > 0) {
        const positions = pointData
          .map(point => [point.longitude, point.latitude])
          .flat()
        this.moveViewToPolygon(positions)
      }
      
      // const { component, event, resource } = res1.data
      logInfo('====> 处理组件数据, 组件数量:', component?.length);
      // for (const v of component) {
      //   this.addCommunityImage(v)
      // }
    } catch (error) {
      logError('====> 设置点位出错:', error);
    }
  }
  //计算多边形的包围盒，并将视角移动到包围盒的中心
  moveViewToPolygon(positions) {
    logInfo('====> 移动视角到多边形, 坐标数量:', positions.length);
    try {
      const bs = CooGL.BoundingSphere.fromPoints(
        CooGL.Vector3.degreesArray2cartesian(positions),
      )
      logInfo('====> 计算包围球, 中心:', bs.center, '半径:', bs.radius);
      
      // 定位到包围盒中心
      this.viewer.camera.flyToBoundingSphere(
        CooGL.Vector3.cartesian2degrees(bs.center), // 包围盒中心
        bs.radius, // 包围盒半径
        {
          offset: new CooGL.HeadingPitchRange(0, -Math.PI / 2, 0),
        },
      )
      logInfo('====> 视角移动完成');
    } catch (error) {
      logError('====> 移动视角出错:', error);
    }
  }

  /**
   * 根据区域编码查找对应的区域信息及其子区域
   * @param {string} code - 区域编码(4/6/9/12位)
   * @returns {object|null} 返回找到的区域信息对象，未找到返回null
   */
  findRegionByCode(code, findSon = false) {
    logInfo('====> 查找区域信息, code:', code, 'findSon:', findSon);
    if (!code) {
      logInfo('====> 区域编码为空');
      return [];
    }
    // 递归查找函数
    const findInTree = nodes => {
      if (!nodes || !Array.isArray(nodes)) return null

      for (const node of nodes) {
        // 匹配当前节点
        if (node.id == code) {
          logInfo('====> 找到匹配节点:', node);
          if (findSon) {
            if (!node.children || !Array.isArray(node.children)) {
              logInfo('====> 节点没有子节点');
              return [];
            }
            const children = node.children.map(item => ({ ...item, children: null }));
            logInfo('====> 返回子节点列表, 数量:', children.length);
            return children;
          }
          return node
        }

        // 递归查找子节点
        if (node.children) {
          const found = findInTree(node.children)
          if (found) return found
        }
      }
      return null
    }
    
    const result = findInTree(this.regionResult);
    if (!result) {
      logInfo('====> 未找到匹配的区域信息');
    }
    return result || [];
  }

  flyToArea([x, y], code) {
    logInfo('====> 飞行到区域, 坐标:', [x, y], 'code:', code);
    const z = this.levelHeight ? this.levelHeight[code.length] : 200000;
    this.viewer.camera.flyTo({
      duration: 2,
      destination: {
        x,
        y,
        z,
      },
      orientation: {
        heading: 6.283185302776594,
        pitch: -1.5707963267948966,
        roll: 0,
      },
    })
    logInfo('====> 飞行命令已发送');
  }

  //清除标注
  clearCommunity() {
    logInfo('====> 清除社区标注, 数量:', this.imageGraphicList.length);
    for (const item of this.imageGraphicList) {
      this.viewer.removeLayer(item)
    }
    this.imageGraphicList = []
    logInfo('====> 社区标注已清除');
  }
  //清除画布
  clear() {
    logInfo('====> 清除画布, 图标数量:', this.imageGraphicList.length, '多边形数量:', this.polygonGraphicList.length, '社区图标数量:', this.imageGraphicListOfCommunity.length);
    for (const item of this.imageGraphicList) {
      this.viewer.removeLayer(item)
    }
    for (const item of this.polygonGraphicList) {
      this.viewer.removeLayer(item)
    }
    for (const item of this.imageGraphicListOfCommunity) {
      this.viewer.removeLayer(item)
    }
    this.imageGraphicListOfCommunity = []
    this.imageGraphicList = []
    this.polygonGraphicList = []
    logInfo('====> 画布已清除');
  }

  clearCurrentAreaData() {
    logInfo('====> 清除当前区域数据, 区域编码:', this.params.regionCode);
    const id = 'layer-' + this.params.regionCode
    const layer = this.viewer.getById(id)
    logInfo('====> 查找到图层:', layer);
    const index = this.imageGraphicList.indexOf(layer)
    if (layer) {
      logInfo('====> 移除图层:', id);
      this.viewer.removeLayer(layer)
    }
    if (index > -1) {
      logInfo('====> 从列表中移除图层, 索引:', index);
      this.imageGraphicList.splice(index, 1)
    }
    logInfo('====> 当前区域数据已清除');
  }

  destory() {
    logInfo('====> 销毁实例');
    this.clear()
    this.clearCommunity()
    if (this.pickHandler) {
      logInfo('====> 移除 pickHandler');
      this.pickHandler()
      this.pickHandler = null
    }
    logInfo('====> 实例已销毁');
  }
}
