import { FC, Key, useEffect, useState } from "react";
import { Form, Input, Tree } from "antd";
import { useNavigate, useParams } from "react-router-dom";
import { FormPageFooter, PageContainer } from "@/components";
import {
  getAssIndexTreeApi,
  getAssTemplateDetailApi,
  saveAssTemplateApi,
} from "@/api";
import { AssIndexTreeItemType, IAssTemplateDetail } from "@/types";
import { isString } from "lodash";
import { DageLoading } from "@dage/pc-components";

const { TextArea } = Input;

const CreateOrEditTemplate: FC = () => {
  const navigate = useNavigate();
  const params = useParams();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<AssIndexTreeItemType[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<Key[]>([]);
  const [detail, setDetail] = useState<null | IAssTemplateDetail>(null);
  const isEdit = isString(params.id);

  const handleSubmit = async () => {
    if (!(await form.validateFields())) return;

    await saveAssTemplateApi({
      ...form.getFieldsValue(),
      normIds: checkedKeys.join(","),
      type: params.type,
      id: detail?.id,
    });
    navigate(-1);
  };

  const getAssIndexTree = async () => {
    const data = await getAssIndexTreeApi();
    setList(data);
  };

  const getDetail = async () => {
    const data = await getAssTemplateDetailApi(params.id!);
    form.setFieldsValue({
      name: data.name,
      remark: data.remark,
    });
    setCheckedKeys(data.normIds.split(",").map((i) => Number(i)));
    setDetail(data);
  };

  useEffect(() => {
    setLoading(true);
    Promise.all(
      isEdit ? [getDetail(), getAssIndexTree()] : [getAssIndexTree()]
    ).finally(() => {
      setLoading(false);
    });
  }, []);

  return (
    <PageContainer title={isEdit ? "编辑模板" : "新增模板"}>
      <Form labelCol={{ span: 4 }} form={form} onFinish={handleSubmit}>
        <Form.Item
          label="模板名称"
          required
          name="name"
          rules={[{ required: true, message: "请输入模板名称" }]}
        >
          <Input
            className="mw650"
            placeholder="请输入内容，最多20字"
            showCount
            maxLength={20}
          />
        </Form.Item>
        <Form.Item label="模板说明" name="remark">
          <TextArea
            className="mw650"
            showCount
            maxLength={500}
            placeholder="请输入内容，最多500字"
            style={{ height: 120, resize: "none" }}
          />
        </Form.Item>
        <Form.Item label="采用指标">
          <Tree
            checkable
            checkedKeys={checkedKeys}
            defaultExpandAll
            treeData={list}
            fieldNames={{ title: "name", key: "id" }}
            onCheck={(keys) => setCheckedKeys(keys as Key[])}
          />
        </Form.Item>

        <FormPageFooter onSubmit={handleSubmit} onCancel={() => navigate(-1)} />
      </Form>

      {loading && <DageLoading />}
    </PageContainer>
  );
};

export default CreateOrEditTemplate;
