import { computed, defineComponent, onMounted, ComputedRef, ref, watch } from "vue";
import Picker from "./Picker";
import { useStore } from "@/hook/useStore";
import useGlobalState from "@/store/global";
import useRoadUnitStore from "@/store/roadUnit";
import { Radio, Button, Switch, Select, Menu, message, Modal, Input, Checkbox, Dropdown } from "ant-design-vue";
import style from "@/assets/style/RoadUnit/map.module.less";
import { HpaasEventKey } from "@/modules/hpaas-core/types";
import { Feature, featureCollection } from "@turf/helpers";
import HPaaSDeckGL from "@/modules/hpaas-core/HPaaSDeckGL";
// import "@/utils/logtime";
import { feature, MultiPolygon, Polygon } from "@turf/turf";
import { PolygonFeatureType } from "@/modules/hpaas-core/tools/data/PolygonStore";
import { queryAllUserDefineArea } from "@/http/api_graphql";
export default defineComponent({
  setup() {
    /**
     * 深圳市区域列表
     */
    const { areaList, getAreaListInShenZhen } = useStore(useGlobalState);

    /**
     * 模式
     * 区域名称
     * 选中道路名称
     * 区域通行车辆、车次、车速分日表
     */
    const { mode, area: areaName, road: roadName, areaInfoByDate } = useStore(useRoadUnitStore);

    /**
     * 区域uid
     */
    const areaUid: ComputedRef<string> = computed(() => {
      return (
        areaList.value.find((area) => {
          return area.name === areaName.value;
        })?.uid || ""
      );
    });

    /**
     * Dom挂载之后，渲染地图
     */
    const hpaasMap = ref<HTMLDivElement>();
    const segmentDataDone = ref<number>(0);
    const spinning = ref<boolean>(true);
    let map: HPaaSDeckGL;
    const loadAreaFromServer = async () => {
      const result: {
        color: string;
        geometry: any;
        id: number;
        name: string;
        user_id: string;
      }[] = await queryAllUserDefineArea();
      const list: any[] = [];
      const features: Feature<MultiPolygon>[] = [];
      result.forEach((r) => {
        const _feature = feature(r.geometry, {
          color: r.color,
          name: r.name,
          id: r.id,
        });
        features.push(_feature);
      });

      return featureCollection(features);
    };
    const initMap = async () => {
      const container = hpaasMap.value;
      if (container) {
        if (!map)
          map = new HPaaSDeckGL(container, {
            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.fitToArea(areaUid.value);

        map.events.on(HpaasEventKey.SEGMENT_DATA_LOADED, () => {
          segmentDataDone.value += 1;
        });
        map.toolsCenter.options.pinBaseUnit = false;
        const featureCollection = await loadAreaFromServer();
        map.polygonDrawLayer?.setData(featureCollection.features as PolygonFeatureType[]);
        // map.toolsCenter.actions.drawer.begin("polygon", features);
      }
    };
    watch(
      () => areaUid.value,
      async () => {
        map.fitToArea(areaUid.value);
      }
    );
    onMounted(() => {
      getAreaListInShenZhen();
      initMap();
    });

    /**

    /**
     * 选中某一条道路，可视化
     * 监听选中道路名称-roadName
     * 监听绘制区域内车次/速度可视化是否准备完成-mapOccOrSpeed（选中道路依赖于此）
     */
    // const checkRoad = () => {
    //   if (roadName.value) {
    //     if (mapOccOrSpeed.value) {
    //       mapOccOrSpeed.value.checkedLayer || mapOccOrSpeed.value.initCheckLines();
    //       mapOccOrSpeed.value.checkLines(roadName.value);
    //     }
    //   } else {
    //     if (mapOccOrSpeed.value) {
    //       mapOccOrSpeed.value.clearCheck();
    //     }
    //   }
    // };
    // watch([roadName, mapOccOrSpeed], () => {
    //   checkRoad();
    // });
    function changeDrawType(type: "circle" | "polygon" | "rect" | "polygonbyroad" | "quickpolygon") {
      map.toolsCenter.actions.drawer.clearAll();
      map.toolsCenter.actions.drawer.begin(type);
    }
    function selectPolygon(type: "single" | "multi") {
      map.polygonDrawLayer && map.toolsCenter.actions.selector.beginSelectPolygon(map.polygonDrawLayer, type);
    }
    function selectRoad() {
      map.toolsCenter.actions.selector.beginSelectRoad();
      map.toolsCenter.selector.road?.on("ROAD_PICK", (feature) => {
        console.log("ROAD_PICK", feature);
      });
      map.toolsCenter.selector.road?.on("SEGMENT_PICK", (feature) => {
        console.log("SEGMENT_PICK", feature);
      });
    }

    /**
     * 选择路片段
     */
    function selectRoadSegment() {
      map.toolsCenter.actions.selector.beginSelectSegment();
      map.toolsCenter.selector.road?.on("ROAD_PICK", (feature) => {
        console.log("ROAD_PICK", feature);
      });
      map.toolsCenter.selector.road?.on("SEGMENT_PICK", (feature) => {
        console.log("SEGMENT_PICK", feature);
      });
    }
    return () => (
      <div class={style.container}>
        <div class={style.map} ref={hpaasMap}></div>
        <div style="position:absolute;left:20px;top:20px;height:40px;">
          <div class={style.areaPickContainer}>
            <div class={style.areaDraw}>
              <Dropdown.Button
                style="margin-right:5px;"
                overlay={() => {
                  return (
                    <Menu>
                      <Menu.Item
                        onClick={() => {
                          changeDrawType("rect");
                        }}
                      >
                        矩形
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          changeDrawType("circle");
                        }}
                      >
                        圆形
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          changeDrawType("polygon");
                        }}
                      >
                        多边形:点击
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          changeDrawType("quickpolygon");
                        }}
                      >
                        多边形:快速
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          changeDrawType("polygonbyroad");
                        }}
                      >
                        多边形:沿路
                      </Menu.Item>
                    </Menu>
                  );
                }}
              >
                创建
              </Dropdown.Button>
              <Dropdown.Button
                onClick={() => {
                  // toggleSelect();
                }}
                overlay={() => {
                  return (
                    <Menu>
                      <Menu.Item
                        onClick={() => {
                          selectPolygon("single");
                        }}
                      >
                        单选:面
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          selectPolygon("multi");
                        }}
                      >
                        多选: 面
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          selectRoad();
                        }}
                      >
                        单选: 路
                      </Menu.Item>
                      <Menu.Item
                        onClick={() => {
                          selectRoadSegment();
                        }}
                      >
                        单选:路段
                      </Menu.Item>
                      <Menu.Item onClick={() => {}} disabled>
                        圈选（多选）
                      </Menu.Item>
                    </Menu>
                  );
                }}
              >
                选择
              </Dropdown.Button>
            </div>
          </div>
          <div style="margin-top:10px;text-align:left;background:#fff;padding:10px;border-radius:5px; ">
            <Switch
              onChange={(checked) => {
                if (checked) {
                  map.setDisplayMode("dark");
                } else {
                  map.setDisplayMode("grey");
                }
              }}
            />
            <span style="margin-left:5px;">暗色模式</span>
          </div>
          <div style="margin-top:10px;text-align:left;background:#fff;padding:10px;border-radius:5px; ">
            <Switch
              onChange={(checked) => {
                if (checked) {
                  map.toolsCenter.options.pinBaseUnit = true;
                } else {
                  map.toolsCenter.options.pinBaseUnit = false;
                }
              }}
            />
            <span style="margin-left:5px;">吸附到路</span>
          </div>
          <div style="margin-top:10px;text-align:left;background:#fff;padding:10px;border-radius:5px; ">
            <Switch
              onChange={(checked) => {
                if (checked) {
                  map.toolsCenter.options.pinFeature = true;
                } else {
                  map.toolsCenter.options.pinFeature = false;
                }
              }}
            />
            <span style="margin-left:5px;">吸附到图形</span>
          </div>
        </div>
      </div>
    );
  },
});
