import { industrialMetaApi } from "@/api";
import { FormPageFooter, MemoSpinLoding } from "@/components";
import { Form, FormInstance, Input } from "antd";
import { useCallback, useEffect, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom";

export default function HistoryCreateOrEdit() {
  const navigate = useNavigate();
  const params = useParams();
  const location = useLocation();
  const readonly = useRef(location.pathname.indexOf("view") > -1);
  const formRef = useRef<FormInstance>(null);
  const [loading, setLoading] = useState(false);

  const getDetail = useCallback(async () => {
    setLoading(true);
    try {
      const { data } = await industrialMetaApi.getDetail(params.id as string);
      formRef.current?.setFieldsValue(data);
    } finally {
      setLoading(false);
    }
  }, [params.id]);

  const handleCancel = useCallback(() => {
    navigate(-1);
  }, [navigate]);

  const handleSubmit = useCallback(async () => {
    if (!(await formRef.current?.validateFields())) return;

    const value = formRef.current?.getFieldsValue();

    if (params.id) {
      value.id = params.id;
    }

    await industrialMetaApi.edit(value);

    handleCancel();
  }, [handleCancel, params.id]);

  useEffect(() => {
    !!params.id && getDetail();
  }, [getDetail, params.id]);

  return (
    <div style={{ position: "relative" }}>
      {loading && <MemoSpinLoding />}
      <Form ref={formRef} labelCol={{ span: 3 }}>
        <Form.Item
          label="名称"
          name="name"
          rules={[{ required: true, message: "请输入" }]}
        >
          <Input
            className="w450"
            placeholder="请输入内容"
            maxLength={20}
            showCount
            readOnly={readonly.current}
          />
        </Form.Item>
        <Form.Item label="简介" name="description">
          <Input.TextArea
            className="w450"
            placeholder="请输入内容"
            maxLength={200}
            rows={12}
            showCount
            readOnly={readonly.current}
          />
        </Form.Item>
      </Form>

      {!loading && (
        <FormPageFooter
          showSubmit={!readonly.current}
          onSubmit={handleSubmit}
          onCancel={handleCancel}
        />
      )}
    </div>
  );
}
