import { historyApi } from "@/api";
import {
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
} from "@dage/web-components";
import { MemoSpinLoding, FormPageFooter } from "@/components";
import { HistoryDictItem } from "@/types";
import { Form, FormInstance, Input, Select } 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 [dictList, setDictList] = useState<HistoryDictItem[]>([]);

  const getDetail = useCallback(async () => {
    setLoading(true);
    try {
      const {
        data: { entity, file },
      } = await historyApi.getDetail(params.id as string);
      formRef.current?.setFieldsValue({
        ...entity,
        fileIds: file.map((i) => ({
          uid: i.id + "",
          url: `${process.env.REACT_APP_BACKEND_URL}${i.filePath}`,
          name: i.fileName,
        })),
      });
    } finally {
      setLoading(false);
    }
  }, [params.id]);

  const getHistoryDictList = useCallback(async () => {
    const { data } = await historyApi.getHistoryDictList();
    setDictList(data);
  }, []);

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

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

    const { fileIds, ...rest } = formRef.current?.getFieldsValue();

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

    await historyApi.add({
      ...rest,
      fileIds: fileIds
        .map((i: any) => (!!i.response ? i.response.id : i.uid))
        .join(),
    });

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

  useEffect(() => {
    getHistoryDictList();
  }, [getHistoryDictList]);

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

  return (
    <div style={{ position: "relative" }}>
      {loading && <MemoSpinLoding />}
      <DageUploadProvider>
        <DageUploadConsumer>
          {(data) => (
            <>
              <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="stage"
                  rules={[{ required: true, message: "请选择" }]}
                >
                  <Select
                    style={{ width: 200 }}
                    placeholder="请选择"
                    options={dictList.map((i) => ({
                      value: i.name,
                      label: i.name,
                    }))}
                    disabled={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="企业" name="companyName">
                  <Input
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={30}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="简介" name="description">
                  <Input.TextArea
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={200}
                    rows={8}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="故事" name="story">
                  <Input.TextArea
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={200}
                    rows={8}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="图片" name="fileIds">
                  <DageUpload
                    disabled={readonly.current}
                    tips="支持png、jpg和jpeg格式；最多9张，最大5M"
                    action={
                      process.env.REACT_APP_BACKEND_URL +
                      "/api/cms/history/upload"
                    }
                  />
                </Form.Item>
              </Form>

              {!loading && (
                <FormPageFooter
                  showSubmit={!readonly.current}
                  disabled={data?.uploading}
                  onSubmit={handleSubmit}
                  onCancel={handleCancel}
                />
              )}
            </>
          )}
        </DageUploadConsumer>
      </DageUploadProvider>
    </div>
  );
}
