import { forwardRef, useImperativeHandle, useRef, useState } from "react";
import { Col, Form, Input, Modal, Row, Select, Tabs, TabsProps } from "antd";
import LangInput from "@/components/LangInput";
import LangInputTextarea from "@/components/LangInputTextarea";
import { TableType } from "@/enum";
import { createTable } from "@/utils";
import { TableItemType } from "@/type";
import { useModel } from "umi";
import { validateTableCode, validateAliasName } from "@/utils/validator";

export default forwardRef(function AddTable(
  props: {
    onChange: (value: TableItemType) => void;
  },
  ref
) {
  const [open, setOpen] = useState(false);
  const tableItemRef = useRef<TableItemType>();
  const { project } = useModel("erModel");
  const [tabActiveKey, setTabActiveKey] = useState("1");
  useImperativeHandle(ref, () => ({
    open: () => {
      // 获取当前模型类型
      tableItemRef.current = createTable(project.type, project.id);
      setFormModel(tableItemRef.current.table);
      setOpen(true);
    },
    close: () => {
      setOpen(false);
    },
  }));

  const [form] = Form.useForm();
  const [formModel, setFormModel] = useState<TableItemType["table"]>();

  const items: TabsProps["items"] = [
    {
      key: "1",
      label: `新建`,
      children: (
        <div>
          <Form labelCol={{ span: 8 }} form={form}>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="编码"
                  name="schemaName"
                  rules={[
                    { required: true, message: "请输入编码" },
                    validateTableCode,
                  ]}
                  tooltip="包含字母、下划线、数字, 必须小写字母开头，且必须有下划线！ 如：user_info"
                >
                  <Input
                    placeholder="请输入"
                    value={formModel?.schemaName}
                    onChange={(e) => handleChange("schemaName", e.target.value)}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="表类型" name="type">
                  <Input
                    placeholder="请输入"
                    value={
                      formModel?.type == TableType.BusinessTable
                        ? "业务表"
                        : "视图表"
                    }
                    disabled
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  label="别名"
                  name="aliasName"
                  rules={[
                    { required: true, message: "请输入别名" },
                    validateAliasName,
                  ]}
                  tooltip="包含字母、数字, 必须小写字母开头！ 如：userinfo"
                >
                  <Input
                    placeholder="请输入"
                    value={formModel?.aliasName}
                    onChange={(e) => handleChange("aliasName", e.target.value)}
                  />
                </Form.Item>
              </Col>
              <Col span={12}>
                <Form.Item label="表名" name="langNameList">
                  <LangInput
                    value={formModel?.langNameList}
                    onChange={(lang) => handleChange("langNameList", lang)}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={24}>
                <Form.Item
                  label="描述"
                  labelCol={{ span: 4 }}
                  name="langDescriptionList"
                >
                  <LangInputTextarea
                    value={formModel?.langDescriptionList}
                    onChange={(lang) =>
                      handleChange("langDescriptionList", lang)
                    }
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </div>
      ),
    },
    {
      key: "2",
      label: `引入`,
      children: (
        <div>
          <Form.Item label="选择主表">
            <Select placeholder="请选择" />
          </Form.Item>
        </div>
      ),
    },
  ];

  const handleChange = (key: string, value: any) => {
    formModel &&
      setFormModel({
        ...formModel,
        [key]: value,
      });
  };
  const handleOk = () => {
    // 新建
    if (tabActiveKey === "1") {
      form.validateFields().then(() => {
        if (tableItemRef.current && formModel) {
          props.onChange({
            ...tableItemRef.current,
            table: formModel,
          });
        }
        setOpen(false);
      });
    }
    // 引入
  };

  return (
    <Modal
      open={open}
      title="添加表"
      okText="确定"
      cancelText="取消"
      onCancel={() => setOpen(false)}
      onOk={handleOk}
    >
      <Tabs items={items} activeKey={tabActiveKey} onChange={setTabActiveKey} />
    </Modal>
  );
});
