import { defineComponent, ref, onMounted, watch, computed, Teleport } from "vue";
import { message, Switch } from "ant-design-vue";

import useEnterpriseReportStore from "@/store/enterpriseReport";
import useGlobalState from "@/store/global";
import { useStore } from "@/hook/useStore";

import HPaaSL7 from "@/modules/hpaas-core/HPaaSL7";
import LineBySegmentsOverlay from "@/modules/hpaas-core/visual/lines/LineBySegmentsOverlay";
import style from "@/assets/style/Report/map.module.less";
import OverlayFactory from "@/modules/hpaas-core/visual/OverlayFactory";
import { OverlayEventKeys } from "@/modules/hpaas-core/visual/Overlay";
import {
  AreaOverlayDataWithName,
  IOverlayFilter,
  ICommonOverlayDataOption,
} from "@/modules/hpaas-core/visual/overlay.types";
import ClusterPointsOverlay from "@/modules/hpaas-core/visual/points/PointsClusterOverlay";
import CommonTooltip from "./tooltips/CommonTooltip";
import PointsImageOverlay from "@/modules/hpaas-core/visual/points/PointsImageOverlay";
import { HpaasEventKey } from "@/modules/hpaas-core/types";
import { loadAreaInfos } from "./map/mapData";

import Timeline from "./map/Timeline";
import AreaPicker from "./map/picker/Picker";
import AreaOverlay from "@/modules/hpaas-core/visual/polygons/AreaOverlay";
import LineODBySegmentsOverlay from "@/modules/hpaas-core/visual/lines/LineODBySegmentsOverlay";
import AddLayer from "./AddLayer";
import { queryAllUserDefineLayer } from "@/http/api_graphql_layer";
import roadApi from "@/http/api_road_network";
import HPaaSMap from "@/modules/hpaas-core/hpaas";
import "@/utils/logtime";

message.config({
  top: "50px",
});
const Map = defineComponent({
  setup() {
    /**
     * 企业体检指标统计表
     * 地图中展示的统计数据
     */
    const { mapShowData, filters, map, filterAreaFeatures, allEnterprisesData } = useStore(useEnterpriseReportStore);

    /**
     * 深圳市区域列表
     */
    const { areaList, getAreaListInShenZhen } = useStore(useGlobalState);

    /**
     * 区域Uid
     */
    const areaUid = computed(() => {
      return areaList.value.find((item) => {
        return item.name == filters.value.areaName;
      })?.uid;
    });

    const hpaasMapContainer = ref<HTMLDivElement>();

    const segmentDataDone = ref<boolean>(false);

    let overlayFactory: OverlayFactory;

    let qujianDeviceLayer: PointsImageOverlay;
    let chuangjinDeviceLayer: PointsImageOverlay;
    let breakingLayer: ClusterPointsOverlay;
    let parkingLayer: ClusterPointsOverlay;
    let publicPoiLayer: PointsImageOverlay;
    // let filterAreaLayer: PolygonOverlay;
    let allAreaLayer: AreaOverlay;

    let segmentsPathOverlay: LineBySegmentsOverlay;
    let segmentsArc3dOverlay: LineODBySegmentsOverlay;

    const createLayers = () => {
      //   filterAreaLayer = overlayFactory.createOverlayByConfig(filterAreaLayerConfig);
      //   allAreaLayer = overlayFactory.createOverlayByConfig(allAreaLayerConfig);
      //   allAreaLayer.on(OverlayEventKeys.CLICK, (area: any) => {
      //     filters.value.areaCode = area.areaCode;
      //     filters.value.areaName = area.name;
      //   });
    };
    const initMap = () => {
      console.log("initMap", areaUid.value);
      if (!map.value) {
        if (hpaasMapContainer.value) {
          map.value = new HPaaSMap(hpaasMapContainer.value, {
            mode: "grey",
            initPitch: 0,
            mapType: "mapbox",
            wmsBaseUrl: "http://10.0.10.174:9999/geoserver/hpaas/wms",
            wfsBaseUrl: "http://10.0.10.174:9999/geoserver/hpaas/wfs",
            show100meters: false,
            showBaseUnit: true,
          });
          map.value.events.on(HpaasEventKey.SEGMENT_PICK, (e) => {});
          // 这里写 overlay 实际上就是将这个类交给外部去控制了
          overlayFactory = new OverlayFactory(map.value);
          createLayers();
          //   map.value.events.$on(HpaasEventKey.ROAD_PICK, (roadModel: RoadModel) => {
          //     message.success(`开始筛选 ${roadModel.name} 的数据`, 1);
          //     filters.value.segmentUids = roadModel.lines.map((l) => {
          //       return l.id;
          //     });
          //   });
          //   map.value.events.$on(HpaasEventKey.ROAD_PICK_NONAME, (roadModel: RoadModel) => {
          //     message.success(`无名路`, 1);
          //   });
        }
      } else if (areaUid.value) {
        map.value.fitToArea(areaUid.value);
        // const hide = message.loading("地图信息加载中，请完成后再操作", 0);
        // // 路段基础数据准备完成
        // map.value.events.on(HpaasEventKey.SEGMENT_DATA_LOADED, () => {
        //   setTimeout(() => {
        //     segmentDataDone.value = true;
        //     hide();
        //   }, 100);
        // });
      }
    };

    onMounted(async () => {
      console.log("on mounted");
      map.value = undefined;
      initMap();
      getAreaListInShenZhen();
      loadAreaInfoData();
      loadAllLayerConfig();
    });

    let allAreaData: AreaOverlayDataWithName[];

    watch(
      () => areaUid.value,
      async () => {
        initMap();
      }
    );

    // watch(filterAreaFeatures, () => {
    //   console.log("change", filterAreaFeatures.value);
    //   const areas = filterAreaFeatures.value.map((f) => {
    //     return {
    //       polygon: f,
    //       name: f.properties ? f.properties.name : "",
    //       color: f.properties ? f.properties.color : "",
    //     };
    //   });
    //   filterAreaLayer.renderData(areas);
    //   const features = filterAreaFeatures.value;

    //   overlayFactory.overlays.forEach((overlay) => {
    //     overlay.filterByFeature(features);
    //   });
    // });

    const allLayerConfigs = ref<any>();
    const loadAllLayerConfig = async () => {
      console.log("loadAllLayerConfig");
      allLayerConfigs.value = await queryAllUserDefineLayer();
      allLayerConfigs.value.forEach(async (c: any) => {
        const _c = c.config_json as ICommonOverlayDataOption;
        if (_c.tableUid) {
          const layer = overlayFactory.createOverlayByConfig(_c);
          layer.on(
            OverlayEventKeys.SHOW_TOOLTIP,
            (dataOption: ICommonOverlayDataOption, dataList: any[], filter: IOverlayFilter) => {
              console.log("SHOW_TOOLTIP");
              activeTooltipKey.value = dataOption.key;
              activePointDataList.value = dataList;
              activePointDataFilter.value = filter;
              activeTooltipName.value = dataOption.name + "-" + filter.name;
              // activeTooltipUid.value = "#tooltip_" + dataOptionKey;
            }
          );
          layer.on(OverlayEventKeys.HIDE_TOOLTIP, () => {
            activeTooltipKey.value = "";
          });
        }
      });
      loadAllLayersData();
    };
    const loadAllLayersData = async () => {
      console.log("loadAllLayersData");
      overlayFactory.overlays.forEach(async (l) => {
        if (l.dataOption.tableUid) {
          const data = await roadApi.table.getCommonTable(
            l.dataOption.tableUid,
            {
              filterTimeKey: l.dataOption.filterTimeKey,
              filterTime: filters.value.date,
              filterAreaCodeKey: l.dataOption.filterAreaCodeKey,
              filterAreaCode: filters.value.areaCode,
              filterAreaNameKey: l.dataOption.filterAreaNameKey,
              filterAreaName: filters.value.areaName,
            },
            {
              enterprise_name: filters.value.enterpriseName,
              plate: filters.value.plate,
            }
          );
          l.renderCommonData(data);
        }
      });
    };
    watch(
      [
        () => filters.value.date,
        () => filters.value.areaCode,
        () => filters.value.enterpriseName,
        () => filters.value.plate,
      ],
      () => {
        if (overlayFactory.overlays.length) {
          loadAllLayersData();
        }
      }
    );

    const loadAreaInfoData = async () => {
      const result = await loadAreaInfos();
      allAreaData = [];
      for (const key in result) {
        const areaName = key;
        const areaCode = result[key].areaCode;
        const plateCount = result[key].plate_count;
        const enterpriseCount = result[key].enterprise_count;
        allAreaData.push({
          name: areaName,
          areaCode,
          extends: {
            plateCount,
            enterpriseCount,
          },
        });
      }

      // allAreaLayer.renderData(allAreaData);
      // console.log(allAreaLayer);
    };

    /**
     * 为 tooltip 准备
     */
    const activePointDataList = ref<any>([]);
    const activeTooltipKey = ref<string>("");
    const activeTooltipName = ref<string>("");
    const activePointDataFilter = ref<IOverlayFilter>({
      name: "-",
      value: "",
      color: "",
      checked: false,
      totalCount: 0,
    });

    return () => (
      <div class={style.container}>
        {/* <Spin spinning={spinning.value} /> */}
        <div class={style.mapBox}>
          <div class={style.map} ref={hpaasMapContainer}></div>
          <Timeline />
        </div>
        <AreaPicker />
        <div style="position:absolute;left:330px;top:22px;text-align:left;background:#fff;padding:10px;border-radius:5px;">
          <Switch
            onChange={(checked) => {
              if (checked) {
                map.value?.setDisplayMode("dark");
              } else {
                map.value?.setDisplayMode("grey");
              }
            }}
          />
          <span style="margin-left:5px;">暗色模式</span>
          <div style="margin-top:5px;">
            <Switch
              onChange={(checked) => {
                if (checked) {
                  map.value && (map.value.toolsCenter.options.pinBaseUnit = true);
                } else {
                  map.value && (map.value.toolsCenter.options.pinBaseUnit = false);
                }
              }}
            />
            <span style="margin-left:5px;margin-right:10px;">吸附到路</span>
          </div>
          <div style="margin-top:5px;">
            {" "}
            <Switch
              disabled
              onChange={(checked) => {
                if (checked) {
                  map.value && (map.value.toolsCenter.options.pinFeature = true);
                } else {
                  map.value && (map.value.toolsCenter.options.pinFeature = false);
                }
              }}
            />
            <span style="margin-left:5px;">吸附到图形</span>
          </div>
          <div style="margin-top:5px;">
            <a
              onClick={() => {
                window.open("/#/ol");
              }}
            >
              OpenLayers测试
            </a>
            <br />
            <a
              onClick={() => {
                window.open("/#/deckgl");
              }}
              style="  "
            >
              deck.gl测试
            </a>
          </div>
        </div>
        {activeTooltipKey.value ? (
          <div style="position:absolute;right:10px;top:10px;width:400px;height:400px;">
            <CommonTooltip
              dataSource={activePointDataList.value}
              dataName={activeTooltipName.value}
              onClose={() => {
                activeTooltipKey.value = "";
              }}
            />
          </div>
        ) : null}
        <AddLayer />
      </div>
    );
  },
});

export default Map;
