import { defineComponent, onMounted, ref, computed, PropType, watch, onUnmounted } from "vue";
import {
  Button,
  Tag,
  Form,
  Row,
  Col,
  Input,
  Select,
  Modal,
  Steps,
  Table,
  Radio,
  Checkbox,
  Divider,
  InputNumber,
} from "ant-design-vue";
import { DownOutlined, PlusSquareOutlined } from "@ant-design/icons-vue";
import style from "@/assets/style/Report/report.module.less";
import useEnterpriseReportStore from "@/store/enterpriseReport";
import useGlobalState from "@/store/global";
import { useStore } from "@/hook/useStore";
import {
  IAreaOverlayDataOption,
  IImagePointOverlayDataOption,
  IODSegmentOverlayDataOption,
  IOverlayFilter,
  IPointOverlayDataOption,
  ISegmentOverlayDataOption,
  OverlayTypesDic,
} from "@/modules/hpaas-core/visual/overlay.types";
import { ColorPicker } from "vue-color-kit";
import "vue-color-kit/dist/vue-color-kit.css";
import roadApi, {
  TableFieldDataType,
  TableFieldFunctionType,
  tableFieldServer,
  tableServer,
} from "@/http/api_road_network";
import { addUserDefineLayer } from "@/http/api_graphql_layer";
const AddLayer = defineComponent({
  setup() {
    const { Step } = Steps;
    const { addLayerModalVisible, mapConfig, mapConfigFilters } = useStore(useEnterpriseReportStore);
    const handleOk = () => {};
    const handleCancel = () => {
      addLayerModalVisible.value = false;
    };
    const currentStep = ref<number>(0);
    const stepChange = (current: number) => {
      currentStep.value = current;
    };

    return () => (
      <div style="position:absolute;left:520px;bottom:65px;height:40px;">
        <Button
          onClick={() => {
            addLayerModalVisible.value = true;
            currentStep.value = 0;
          }}
          type="primary"
        >
          添加新图层
        </Button>
        <Modal
          title="添加新图层"
          visible={addLayerModalVisible.value}
          onOk={handleOk}
          onCancel={handleCancel}
          width="1000px"
          okText="下一步"
          footer={false}
        >
          <div class={style.addLayer}>
            <Steps current={currentStep.value}>
              <Step title="选择图层类型" />
              {/* <Step title="对图层进行配置" /> */}
              <Step title="选择关联的数据源" />
              <Step title="配置并保存" />
            </Steps>
            <div style="margin-top:30px;">
              {currentStep.value == 0 && (
                <div>
                  <div style="text-align:left;">
                    请选择图层类型：
                    <Radio.Group
                      onChange={(e) => {
                        mapConfig.value.type = e.target.value;
                      }}
                    >
                      {Object.keys(OverlayTypesDic).map((k: string) => {
                        return (
                          <Radio.Button value={k} key={k}>
                            {OverlayTypesDic[k]}
                          </Radio.Button>
                        );
                      })}
                    </Radio.Group>
                  </div>
                  <div style="margin-top:30px;text-align:right;">
                    <Button
                      type="default"
                      style="margin-right:20px;"
                      onClick={() => {
                        addLayerModalVisible.value = false;
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      disabled={!mapConfig.value.type}
                      onClick={() => {
                        currentStep.value = 1;
                      }}
                    >
                      下一步
                    </Button>
                  </div>
                </div>
              )}
              {/* {currentStep.value == 1 && (
                <div>
                  <div style="text-align:left;line-height:25px;">请配置图层属性：</div>
                  <div></div>
                  <div style="margin-top:30px;text-align:right;">
                    <Button type="default" style="margin-right:20px;">
                      取消
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        currentStep.value = 2;
                      }}
                    >
                      下一步
                    </Button>
                  </div>
                </div>
              )} */}
              {currentStep.value == 1 && (
                <div>
                  <div style="text-align:left;line-height:25px;">请选择数据源</div>
                  <TableDIV />
                  <div style="margin-top:30px;text-align:right;">
                    <Button
                      type="default"
                      style="margin-right:20px;"
                      onClick={() => {
                        addLayerModalVisible.value = false;
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        currentStep.value = 2;
                      }}
                      disabled={!mapConfig.value.tableUid}
                    >
                      下一步
                    </Button>
                  </div>
                </div>
              )}
              {currentStep.value == 2 && (
                <div>
                  <div style="text-align:left;line-height:30px;font-size:16px;">图层设置</div>
                  <LayerConfig />
                  {/* <div style="text-align:left;line-height:30px;font-size:16px;">显示设置</div> */}
                  <div style="margin-top:30px;text-align:right;">
                    <Button
                      type="default"
                      style="margin-right:20px;"
                      onClick={() => {
                        addLayerModalVisible.value = false;
                      }}
                    >
                      取消
                    </Button>
                    <Button
                      type="primary"
                      onClick={() => {
                        console.log(mapConfigFilters.value);
                        mapConfig.value.filters = mapConfigFilters.value;
                        console.log(mapConfig.value);
                        addUserDefineLayer(
                          mapConfig.value.category,
                          mapConfig.value.key,
                          mapConfig.value.name,
                          mapConfig.value
                        );
                      }}
                    >
                      保存
                    </Button>
                  </div>
                </div>
              )}
            </div>
          </div>
        </Modal>
      </div>
    );
  },
});

const LayerConfig = defineComponent({
  setup() {
    const { mapConfigFilters, mapConfig, activeTableFieldList } = useStore(useEnterpriseReportStore);
    const colors: { [key: string]: string[] } = {
      "1": ["#ffaaa7", "#d5ecc2", "#98ddca"],
      "2": ["#5181FF", "#E75151", "#A36FF8", "#F9A629", "#73BFE7", "#5E6AB0", "#48BE0B"],
    };

    const filters = mapConfigFilters;
    const colorPickerShow = ref<boolean>(false);
    // const toggleColorPicker = () => {
    //   colorPickerShow.value = !colorPickerShow;
    // };
    document.body.addEventListener("click", () => {
      filters.value.forEach((f) => {
        f.showPicker = false;
      });
    });
    const tableFieldList = ref<tableFieldServer[]>([]);
    const loadFieldList = async (tableUid: string) => {
      const result = await roadApi.table.loadFieldsByTableUid(tableUid);
      tableFieldList.value = result;
    };
    onMounted(() => {
      mapConfig.value.tableUid && loadFieldList(mapConfig.value.tableUid);
    });

    return () => (
      <div style="">
        <Form layout={"vertical"} style="display:flex;flex-wrap: wrap;justify-content: space-between;">
          <Form.Item
            label="图层名"
            style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
          >
            <Input
              placeholder="输入图层名"
              style="width:250px;"
              onChange={(e) => {
                mapConfig.value.name = e.target.value;
                mapConfig.value.key = e.target.value;
              }}
            />
          </Form.Item>
          <Form.Item
            label="业务分类"
            style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
          >
            <Input
              placeholder="输入业务分类"
              style="width:250px;"
              onChange={(e) => {
                mapConfig.value.category = e.target.value;
              }}
            />
          </Form.Item>
          {mapConfig.value.type && ["area"].indexOf(mapConfig.value.type) != -1 ? (
            <Form.Item
              label="色板"
              style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
            >
              <Radio.Group
                onChange={(e) => {
                  mapConfig.value.colors = colors[e.target.value];
                }}
              >
                {Object.keys(colors).map((key: string) => {
                  const cs = colors[key];
                  return (
                    <div>
                      <Radio value={key}>
                        {cs.map((c) => {
                          return (
                            <span
                              style={
                                "vertical-align:-4px;width:15px;height:15px;display:inline-block;background:" + c + ";"
                              }
                            ></span>
                          );
                        })}
                      </Radio>
                    </div>
                  );
                })}
              </Radio.Group>
            </Form.Item>
          ) : null}

          <Form.Item
            label="显示设置"
            style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
          >
            <InputNumber
              min={1}
              value={5}
              placeholder="大小或粗细"
              onChange={(e) => {
                mapConfig.value.size = e;
              }}
            />
          </Form.Item>
          {mapConfig.value.type && ["point-cluster", "image-point", "point"].indexOf(mapConfig.value.type) != -1 ? (
            <Form.Item
              label="经纬度的列"
              style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
            >
              <Select
                placeholder="选择经度字段"
                style="width:200px;margin-right:20px;"
                onChange={(e) => {
                  (mapConfig.value as IPointOverlayDataOption | IImagePointOverlayDataOption).lngKey = e;
                }}
              >
                {tableFieldList.value.map((t) => {
                  return (
                    <Select.Option key={t.fieldName} value={t.fieldName}>
                      {t.fieldAlias}
                    </Select.Option>
                  );
                })}
              </Select>
              <Select
                placeholder="选择维度字段"
                style="width:200px;"
                onChange={(e) => {
                  (mapConfig.value as IPointOverlayDataOption | IImagePointOverlayDataOption).latKey = e;
                }}
              >
                {tableFieldList.value.map((t) => {
                  return (
                    <Select.Option key={t.fieldName} value={t.fieldName}>
                      {t.fieldAlias}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
          ) : null}
          {mapConfig.value.type && ["segment-path", "segment-od"].indexOf(mapConfig.value.type) != -1 ? (
            <Form.Item
              label="路网路段uid的列"
              style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
            >
              <Select
                placeholder="路网路段uid的列"
                style="width:200px;margin-right:20px;"
                onChange={(e) => {
                  (mapConfig.value as ISegmentOverlayDataOption | IODSegmentOverlayDataOption).segmentUidKey = e;
                }}
              >
                {tableFieldList.value.map((t) => {
                  return (
                    <Select.Option key={t.fieldName} value={t.fieldName}>
                      {t.fieldAlias}
                    </Select.Option>
                  );
                })}
              </Select>
              {mapConfig.value.type && ["segment-path"].indexOf(mapConfig.value.type) != -1 ? (
                <Checkbox
                  onChange={(e) => {
                    mapConfig.value.segmentUidFlat = e.target.checked;
                  }}
                  style="width:200px;"
                >
                  数据是否折叠（逗号分隔）
                </Checkbox>
              ) : null}
            </Form.Item>
          ) : null}
          {mapConfig.value.type && ["area"].indexOf(mapConfig.value.type) != -1 ? (
            <Form.Item
              label="行政区划code的列"
              style="width:49%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
            >
              <Select
                placeholder="请选择行政区划code的列"
                style="width:250px;margin-right:20px;"
                onChange={(e) => {
                  (mapConfig.value as IAreaOverlayDataOption).areaCodeKey = e;
                }}
              >
                {tableFieldList.value.map((t) => {
                  return (
                    <Select.Option key={t.fieldName} value={t.fieldName}>
                      {t.fieldAlias}
                    </Select.Option>
                  );
                })}
              </Select>
            </Form.Item>
          ) : null}

          <Form.Item
            label="数据筛选配置"
            style="width:100%;background:#f3f3f3;border-radius:10px;padding:10px;margin:10px 0px;"
          >
            <Select
              placeholder="请先选择用来过滤数据的列"
              style="width:250px;margin-right:20px;"
              onChange={(e) => {
                mapConfig.value.filterKey = e;
              }}
            >
              {tableFieldList.value.map((t) => {
                return (
                  <Select.Option key={t.fieldName} value={t.fieldName}>
                    {t.fieldAlias}
                  </Select.Option>
                );
              })}
            </Select>
            <Select
              placeholder="请选择时间列"
              style="width:250px;margin-right:20px;"
              onChange={(e) => {
                mapConfig.value.filterTimeKey = e;
              }}
            >
              {tableFieldList.value.map((t) => {
                return (
                  <Select.Option key={t.fieldName} value={t.fieldName}>
                    {t.fieldAlias}
                  </Select.Option>
                );
              })}
            </Select>
            <Select
              placeholder="请选择区域列（行政编码）"
              style="width:250px;margin-right:20px;"
              onChange={(e) => {
                mapConfig.value.filterAreaCodeKey = e;
              }}
            >
              {tableFieldList.value.map((t) => {
                return (
                  <Select.Option key={t.fieldName} value={t.fieldName}>
                    {t.fieldAlias}
                  </Select.Option>
                );
              })}
            </Select>
            <div style="line-height:20px;margin-top:10px;">设定可能的值</div>
            <Row gutter={[10, 10]} justify="start" style="margin-top:5px;">
              {filters.value.map((f, i) => {
                return (
                  <Col span={6}>
                    <div style=" background:#fff;border-radius:10px;padding:15px;">
                      <Input
                        placeholder="值的名字"
                        style="margin-bottom:10px;"
                        value={f.name}
                        onChange={(e) => {
                          f.name = e.target.value;
                        }}
                      ></Input>
                      <Input
                        placeholder="值"
                        style="margin-bottom:10px;"
                        value={String(f.value)}
                        onChange={(e) => {
                          f.value = e.target.value;
                        }}
                      ></Input>
                      <Checkbox style="margin-bottom:10px;" checked={f.checked}>
                        默认是否选中
                      </Checkbox>
                      <div
                        onClick={(e) => {
                          e.stopPropagation();
                          setTimeout(() => {
                            f.showPicker = true;
                          }, 100);
                        }}
                      >
                        <Input
                          placeholder="颜色"
                          value={f.color}
                          style={{ color: f.color }}
                          onChange={(e) => {
                            f.color = e.target.value;
                          }}
                        ></Input>
                      </div>
                      <Input
                        placeholder="图标地址"
                        style="margin-bottom:10px;"
                        value={f.imgUrl}
                        onChange={(e) => {
                          f.imgUrl = e.target.value;
                        }}
                      ></Input>
                      <InputNumber min={1} placeholder="图标大小" />
                      {f.showPicker ? (
                        <ColorPicker
                          theme="light"
                          style="position:fixed;width:220px;"
                          onChangeColor={(color: any) => {
                            f.color = color.hex;
                          }}
                          onClick={(e: any) => {
                            e.stopPropagation();
                          }}
                        />
                      ) : null}
                    </div>
                  </Col>
                );
              })}
              <Col span={6}>
                <div
                  style=" background:#fff;border-radius:10px;padding:15px;height:100%;cursor:pointer"
                  onClick={() => {
                    filters.value.push({
                      color: "",
                      name: "",
                      value: "",
                      checked: true,
                      totalCount: 0,
                      showPicker: false,
                    });
                  }}
                >
                  <div style="margin:auto auto;width:100px;text-align:center;margin-top:55px;color:#999;">
                    <PlusSquareOutlined />
                    <div>添加一个值</div>
                  </div>
                </div>
              </Col>
            </Row>
          </Form.Item>
        </Form>
      </div>
    );
  },
});

const TableDIV = defineComponent({
  setup() {
    const { allMetaTables, activeTableFieldList, mapConfig } = useStore(useEnterpriseReportStore);
    const fieldsColumns = ref<any[]>([
      {
        title: "字段名",
        dataIndex: "fieldAlias",
        key: "fieldAlias",
      },
      {
        title: "原始字段名",
        dataIndex: "fieldName",
        key: "fieldName",
      },
      {
        title: "字段功能类型",
        dataIndex: "functionType",
        key: "functionType",
        customRender: (e: any) => {
          return <span>{TableFieldFunctionType[e.text] || ""} </span>;
        },
      },
      {
        title: "字段数据类型",
        dataIndex: "dataType",
        key: "dataType",
        customRender: (e: any) => {
          return <span>{TableFieldDataType[e.text] || ""} </span>;
        },
      },
      {
        title: "字段最大长度",
        dataIndex: "maxLength",
        key: "maxLength",
      },
      {
        title: "备注",
        dataIndex: "remark",
        key: "remark",
      },
    ]);

    const loadTables = async () => {
      allMetaTables.value = await roadApi.table.queryByCondition();
    };

    const selectTable = async (tableUid: string) => {
      mapConfig.value.tableUid = tableUid;
      const result = await roadApi.table.loadFieldsByTableUid(tableUid);
      activeTableFieldList.value = [];
      result.forEach((r) => {
        activeTableFieldList.value.push(r);
      });
    };
    onMounted(() => {
      loadTables();
    });
    return () => (
      <div>
        <div style="margin:10px 0;">
          {allMetaTables.value.map((t) => {
            return (
              <Tag
                onClick={() => {
                  selectTable(t.uid);
                }}
                color={mapConfig.value.tableUid == t.uid ? "#2db7f5" : ""}
                style="margin-bottom:5px;cursor:pointer;"
              >
                {t.tableAlias}
              </Tag>
            );
          })}
        </div>
        <Table dataSource={activeTableFieldList.value} columns={fieldsColumns.value} size="middle"></Table>
      </div>
    );
  },
});
export default AddLayer;
