import useEnterpriseReportStore from "@/store/enterpriseReport";
import { defineComponent, onMounted, ref, watch } from "vue";
import style from "@/assets/style/Report/map.module.less";
import { Radio, Button, Switch, Select, Menu, message, Modal, Input, Checkbox, Dropdown } from "ant-design-vue";
const { Option } = Select;
import { DownOutlined, CloseOutlined, FilterOutlined, AlignCenterOutlined } from "@ant-design/icons-vue";
import { useStore } from "@/hook/useStore";
import {
  addUserDefineArea,
  queryAllUserDefineArea,
  removeUserDefineArea,
  updateUserDefineArea,
} from "@/http/api_graphql";

import { shallowRef } from "vue";

import { useHpaasDrawer } from "./useHpaasDrawer";
import { useHpaasSelector } from "./useHpaasSelector";
import { useHpaasSplitter, useHpaasEditor } from "./useHpaasEditor";
import { feature, multiPolygon, getCoords } from "@turf/turf";

const AreaPicker = defineComponent({
  setup() {
    const { enterpriseData, activeTooltipUid, mapShowData, filters, map } = useStore(useEnterpriseReportStore);

    const { isDrawing, currentDrawingType, changeDrawType, cancelDraw, getDrawResult } = useHpaasDrawer(map);

    const { isSelecting, selectMode, selectPolygon, selectRoad, selectRoadSegment, clearSelect } =
      useHpaasSelector(map);

    const { isSplitting, beginSplitByLine, splitResult } = useHpaasSplitter(map);

    const { isEditing, beginEditPolygon, beginEditSinglePolygon, cancelEdit, getPolygonEditResult } =
      useHpaasEditor(map);

    const saveModalVisible = ref<boolean>(false);
    const areas = new Map<number, any>();
    const saveAreaName = ref<string>("");
    const saveAreaColor = ref<string>("");

    const saveArea = () => {
      saveModalVisible.value = true;
    };

    const handlesaveOk = async () => {
      if (!saveAreaColor.value || !saveAreaName.value) {
        message.error("请填写完整");
        return;
      }
      saveModalVisible.value = false;
      if (saveAreaName.value) {
        const feature = getDrawResult();
        if (feature) {
          await addUserDefineArea(saveAreaName.value, saveAreaColor.value, feature.geometry);
          loadAreaFromServer();
          cancelDraw();
          map.value?.toolsCenter.actions.drawer.reset();
          message.success("保存成功");
        } else {
          message.error("获取图形失败");
        }
      }
    };

    const checkboxOptions = shallowRef<any[]>([]);
    const loadAreaFromServer = async () => {
      const result: {
        color: string;
        geometry: any;
        id: number;
        name: string;
        user_id: string;
      }[] = await queryAllUserDefineArea();
      const list: any[] = [];
      const nowCheckedIds = checkboxOptions.value
        .filter((v) => {
          return v.checked;
        })
        .map((v) => {
          return v.value;
        });
      result.forEach((r) => {
        const _feature = feature(r.geometry, {
          color: r.color,
          name: r.name,
          id: r.id,
        });
        areas.set(r.id, _feature);
        list.push({
          label: r.name,
          value: r.id,
          checked: nowCheckedIds.indexOf(r.id) !== -1 ? true : false,
        });
      });

      checkboxOptions.value = list;
      loadFilterArea();
    };

    const areaChecked = ref<boolean>(true);

    const checkboxChange = async (e: any) => {
      const checked = e.target.checked;
      areaChecked.value = checked;
      loadFilterArea();
    };
    const loadFilterArea = async () => {
      const features = [];
      if (areaChecked.value) {
        for (let i = 0; i < checkboxOptions.value.length; i++) {
          const feature = areas.get(checkboxOptions.value[i].value);
          feature && features.push(feature);
        }
      }
      map.value?.polygonDrawLayer?.setData(features);
    };

    const delArea = async (id: number) => {
      await removeUserDefineArea(id);
      loadAreaFromServer();
    };

    /**打断保存 */
    watch(
      () => splitResult.value,
      async () => {
        const loading = message.loading("结果保存中");
        const features = splitResult.value;
        if (!features) return;
        for (let key = 0; key < features.length; key++) {
          const feature = features[key];
          const id = feature.properties?.id;
          const name = feature.properties?.name;
          const color = feature.properties?.color;
          const coords = getCoords(feature);

          if (coords.length > 1) {
            for (let i = 0; i < coords.length; i++) {
              const coord = coords[i];
              const newFeature = multiPolygon([coord]);
              await addUserDefineArea(name + "-" + (i + 1), color, newFeature.geometry);
            }
            await delArea(id);
          }
          loadAreaFromServer();
          loading();
        }
      }
    );

    onMounted(() => {
      loadAreaFromServer();
    });

    const saveEditResult = async () => {
      const features = getPolygonEditResult();
      const loading = message.loading("结果保存中");
      if (!features) return;
      const promises = features.map((feat) => {
        const id = +feat.properties?.id;
        return updateUserDefineArea(id, feat.geometry);
      });
      isEditing.value = false;
      await Promise.all(promises);
      loadAreaFromServer();
      loading();
      // cancelSelect();
      cancelEdit();
    };

    /* ---UI--- */

    const DrawerDropdownButton = () => (
      <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>
    );

    const EditDropdownButton = () => (
      <Dropdown.Button
        style="margin-right:5px;"
        overlay={() => {
          return (
            <Menu>
              <Menu.Item onClick={beginEditSinglePolygon}>普通调整: 面</Menu.Item>
              <Menu.Item onClick={beginEditPolygon}>拓扑调整: 面</Menu.Item>
              <Menu.Item onClick={beginSplitByLine}>拆分面</Menu.Item>
              <Menu.Item disabled>沿路拆分面</Menu.Item>
              <Menu.Item disabled>合并面</Menu.Item>
            </Menu>
          );
        }}
      >
        编辑
      </Dropdown.Button>
    );

    const SelectDropdownButton = () => (
      <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>
    );

    const SaveAreaModal = () => (
      <Modal
        visible={saveModalVisible.value}
        title="给区域命名"
        onOk={handlesaveOk}
        onCancel={() => {
          saveModalVisible.value = false;
        }}
      >
        <Input
          onChange={(e) => {
            saveAreaName.value = e.target.value;
          }}
          placeholder={"请为此区域命名"}
          style="width:250px;margin-right:20px;"
        />
        <Select
          placeholder={"请选择颜色"}
          onChange={(e) => {
            saveAreaColor.value = e;
          }}
          style="width:160px;"
          value={saveAreaColor.value}
        >
          {["#5181FF", "#E75151", "#A36FF8", "#F9A629", "#73BFE7", "#5E6AB0", "#48BE0B"].map((color) => {
            return (
              <Option key={color} value={color}>
                <div style={"padding:2px 10px;background:" + color}>{color}</div>
              </Option>
            );
          })}
        </Select>
      </Modal>
    );

    const CheckboxArea = () => (
      <div class={style.userAreaList}>
        <div style="lin-height:30px;padding:10px 0 10px 10px;">
          <Checkbox
            onChange={(e) => {
              checkboxChange(e);
            }}
            checked={areaChecked.value}
          >
            自定义区域
          </Checkbox>
        </div>
        {checkboxOptions.value.map((option) => {
          return (
            <div class={style.userAreaListItem}>
              <span class={style.userAreaListItemLabel}>{option.label}</span>
              <CloseOutlined class={style.userAreaListItemIcon} onClick={() => delArea(option.value)} />
            </div>
          );
        })}
      </div>
    );

    const SaveDrawButtonGroup = () => (
      <div style="text-align:left;margin-top:10px;">
        <Button class={style.savetoArea} onClick={saveArea} type={"primary"}>
          保存为自定义区域
        </Button>
        <Button class={style.savetoAreaCancel} onClick={cancelDraw}>
          取消
        </Button>
      </div>
    );

    const SaveEditButtonGroup = () => (
      <div style="text-align:left;margin-top:10px;">
        <Button class={style.savetoArea} onClick={saveEditResult} type={"primary"}>
          保存修改
        </Button>
        <Button class={style.savetoAreaCancel} onClick={cancelEdit}>
          取消
        </Button>
      </div>
    );

    return () => (
      <div style="position:absolute;left:20px;top:20px;height:40px;">
        <div class={style.areaPickContainer}>
          <div class={style.areaDraw}>
            <DrawerDropdownButton />
            <EditDropdownButton />
            <SelectDropdownButton />
          </div>
          <SaveDrawButtonGroup v-show={isDrawing.value} />
          <SaveEditButtonGroup v-show={isEditing.value} />
        </div>
        <CheckboxArea />

        <SaveAreaModal />
      </div>
    );
  },
});

export default AreaPicker;
