import { defHttp } from '/@/utils/http/axios';
import { omitBy, isNil, get } from 'lodash-es';
import { useMineDepartmentStore } from '/@/store/modules/mine';
import { StatusColorEnum } from '/@/enums/jeecgEnum';
// import { findNode } from '/@/utils/helper/treeHelper';

enum Api {
  list = '/province/mineData/getMineData',
  getGoafAlarmLevel = '/province/homeData/getGoafAlarmLevel',
}
/**
 * 列表接口
 * @param params
 */
export function getMarkers(params: any): Promise<any> {
  return defHttp.post({ url: Api.list, params: omitBy(params, isNil) }, { joinParamsToUrl: true });
}

export function getGoafAlarmLevel(params: any): Promise<any> {
  return defHttp.post({ url: Api.getGoafAlarmLevel, params: omitBy(params, isNil) }, { joinParamsToUrl: true });
}

export function getShanxiGeoJSON() {
  return fetch('/js/shanxi.geo.json').then((r) => r.json());
}

export function getMarkerCollection(params: any) {
  // const getFeatColor = (gb) => {
  //   const colorMap = {
  //     // 邮编前7位：颜色
  //     // '1566101': '#14baff',
  //     // '1566102': '#14baff',
  //     // '1566103': '#ffff12',
  //     // '1566104': '#ffff12',
  //     // '1566105': '#ffab12',
  //     // '1566106': '#ffab12',
  //     // '1566107': '#fe1414',
  //     // '1566108': '#fe1414',
  //     // '1566109': '#fe1414',
  //     // '1566111': '#fe1414',
  //     '1566101': StatusColorEnum.blue,
  //     '1566102': StatusColorEnum.yellow,
  //     '1566103': StatusColorEnum.gold,
  //     '1566104': StatusColorEnum.red,
  //     '1566105': StatusColorEnum.green,
  //     '1566106': StatusColorEnum.gray,
  //     '1566107': StatusColorEnum.orange,
  //     '1566108': StatusColorEnum.purple,
  //     '1566109': StatusColorEnum.black,
  //     '1566110': StatusColorEnum.blue,
  //   };
  //   return get(colorMap, gb.slice(0, -2), StatusColorEnum.blue);
  // };
  const getAlarmColor = (lv) => {
    const colorMap = {
      4: StatusColorEnum.red,
      3: StatusColorEnum.gold,
      2: StatusColorEnum.yellow,
      1: StatusColorEnum.blue,
      0: StatusColorEnum.blue,
    };

    return get(colorMap, lv, StatusColorEnum.blue);
  };

  const positionPresets = new Map([
    [
      '陕西局',
      {
        x: '35.83317',
        y: '109.425873',
      },
    ],
    [
      '地方监管',
      {
        x: '35.83317',
        y: '109.425873',
      },
    ],
    [
      '陕西省（集团）',
      {
        x: '35.83317',
        y: '109.425873',
      },
    ],
    [
      '执法一处',
      {
        x: '38.640448',
        y: '110.025366',
      },
    ],
    [
      '执法二处',
      {
        x: '39.195141',
        y: '110.844117',
      },
    ],
    [
      '执法三处',
      {
        x: '35.83317',
        y: '109.425873',
      },
    ],
    [
      '执法四处',
      {
        x: '35.184',
        y: '109.937609',
      },
    ],
    [
      '执法五处',
      {
        x: '33.812234',
        y: '108.337231',
      },
    ],
  ]);

  // const pointInPolygon = (point, polygon) => {
  //   const x = point[0],
  //     y = point[1];
  //   let inside = false;
  //   for (let i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
  //     const xi = polygon[i][0],
  //       yi = polygon[i][1];
  //     const xj = polygon[j][0],
  //       yj = polygon[j][1];
  //     const intersect = yi > y !== yj > y && x < ((xj - xi) * (y - yi)) / (yj - yi) + xi;
  //     if (intersect) inside = !inside;
  //   }
  //   return inside;
  // };

  // const pointInMultiPolygon = (point, multiPolygon) => {
  //   for (const polygon of multiPolygon.coordinates) {
  //     // 外环
  //     const outerRing = polygon[0];
  //     if (pointInPolygon(point, outerRing)) {
  //       // 检查内环（洞），如果点在任意一个内环内，则不算内部
  //       let insideHole = false;
  //       for (let i = 1; i < polygon.length; i++) {
  //         const hole = polygon[i];
  //         if (pointInPolygon(point, hole)) {
  //           insideHole = true;
  //           break;
  //         }
  //       }
  //       if (!insideHole) return true;
  //     }
  //   }
  //   return false;
  // };

  return getMarkers(params).then(({ records }) => {
    const mineStore = useMineDepartmentStore();

    const map = new Map<string, any>();

    // 根据树信息将煤矿信息分类并整合为一个数组
    for (const element of records) {
      // 为初始的数据赋值
      if (!element.dynamic) {
        element.id = element.deptId;
        // 子节点计数器
        element.count = 1;
        element.isLeaf = true;
        element.dynamic = false;
        element.alarmLevel = parseInt(element.alarmLevel) || 0;
        element.longitude = parseFloat(element.longitude);
        element.latitude = parseFloat(element.latitude);
        element.fillColor = getAlarmColor(element.alarmLevel);
        // 地图缩放等级
        element.zoom = 8;

        map.set(element.deptId, element);
      }

      if (map.has(element.parentId)) {
        const node = map.get(element.parentId);
        node.count += element.count;
        node.alarmLevel = Math.max(node.alarmLevel, element.alarmLevel);
        node.fillColor = getAlarmColor(node.alarmLevel);
        continue;
      }

      const ref = mineStore.findDepartById(element.parentId);
      if (!ref) continue;

      const node = {
        id: ref.id,
        deptId: ref.id,
        parentId: ref.parentId,
        name: ref.departName,
        count: element.count,
        isLeaf: false,
        dynamic: true,
        alarmLevel: element.alarmLevel,
        longitude: positionPresets.get(ref.departName)?.y || element.longitude,
        latitude: positionPresets.get(ref.departName)?.x || element.latitude,
        fillColor: getAlarmColor(element.alarmLevel),
        zoom: 5 + parseInt(ref.orgType),
      };
      map.set(element.parentId, node);
      records.push(node);
    }

    map.clear();

    // geojson.features.forEach(({ properties, geometry }) => {
    //   properties.fillColor = getFeatColor(properties.gb);
    //   // const temp = records.filter((item) => pointInMultiPolygon([item.longitude, item.latitude], geometry));
    //   const temp = reduceRight(
    //     records,
    //     (acc, item) => {
    //       acc.add(mineStore.getRootId!);
    //       // 从右边开始，因为父节点都在最后面
    //       if (pointInMultiPolygon([item.longitude, item.latitude], geometry)) {
    //         acc.add(item.id);
    //         acc.add(item.parentId);
    //       }
    //       return acc;
    //     },
    //     new Set()
    //   );
    //   properties.children = [...temp];
    // });

    const markers = {
      type: 'FeatureCollection',
      features: records.map((item) => ({
        type: 'Feature',
        id: item.deptId,
        geometry: {
          type: 'Point',
          coordinates: [item.longitude, item.latitude],
        },
        properties: item,
      })),
    };

    return [records, markers];
  });
}
