import { weaponApi } from "@/api";
import { FormPageFooter, MemoSpinLoding } from "@/components";
import {
  DageFileCheckbox,
  DageFileCheckboxMethods,
  DageFileResponseType,
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
} from "@dage/web-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 dageFileCheckboxRef = useRef<DageFileCheckboxMethods>(null);
  const [loading, setLoading] = useState(false);
  const [dictList, setDictList] = useState<HistoryDictItem[]>([]);
  const [fileList, setFileList] = useState<DageFileResponseType[]>([]);

  const getDetail = useCallback(async () => {
    setLoading(true);
    try {
      const {
        data: {
          entity: { thumb, ...rest },
          file,
        },
      } = await weaponApi.getDetail(params.id as string);
      if (thumb) {
        rest.thumb = [
          {
            uid: thumb,
            url: `${process.env.REACT_APP_BACKEND_URL}${thumb}`,
            name: thumb,
            status: "done",
          },
        ];
      }
      formRef.current?.setFieldsValue({
        ...rest,
      });
      dageFileCheckboxRef.current?.setFileList(
        file.map((i: any) => ({
          uid: i.id + "",
          url: `${process.env.REACT_APP_BACKEND_URL}${i.filePath}`,
          thumbUrl: `${process.env.REACT_APP_BACKEND_URL}${i.filePath}`,
          name: i.fileName,
          dType: i.type,
          status: "done",
        }))
      );
    } finally {
      setLoading(false);
    }
  }, [params.id]);

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

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

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

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

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

    await weaponApi.add({
      ...rest,
      thumb: thumb
        .map((i: any) => (!!i.response ? i.response.data.filePath : i.uid))
        .join(),
      fileIds: fileList
        .map((i) => (!!i.response ? i.response.id : i.uid))
        .join(),
    });

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

  const handleFileChange = useCallback((list: DageFileResponseType[]) => {
    setFileList(list);
  }, []);

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

  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="vocation">
                  <Input
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={30}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="类型" name="type">
                  <Input
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={30}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="生产厂家" name="company">
                  <Input
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={30}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="年份" name="year">
                  <Input
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={30}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="尺寸" name="size">
                  <Input
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={30}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item label="重量" name="weight">
                  <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="reason">
                  <Input.TextArea
                    className="w450"
                    placeholder="请输入内容"
                    maxLength={200}
                    rows={4}
                    showCount
                    readOnly={readonly.current}
                  />
                </Form.Item>
                <Form.Item
                  label="封面图"
                  name="thumb"
                  rules={[{ required: true, message: "请输入" }]}
                >
                  <DageUpload
                    maxCount={1}
                    disabled={readonly.current}
                    tips="支持png、jpg和jpeg格式；最大20M，最多1张"
                    action="/api/cms/goods/upload"
                  />
                </Form.Item>
                <Form.Item
                  label="文件类型"
                  name="fileTypes"
                  rules={[
                    { required: true, message: "请选择" },
                    { validator: dageFileCheckboxRef.current?.validate! },
                  ]}
                >
                  <DageFileCheckbox
                    ref={dageFileCheckboxRef}
                    disabled={readonly.current}
                    action="/api/cms/goods/upload"
                    onFileChange={handleFileChange}
                  />
                </Form.Item>
              </Form>

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