import { bannerApi } from "@/api";
import { FormPageFooter, MemoSpinLoding } from "@/components";
import {
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
} from "@dage/pc-components";
import { dayjs, formatDate } from "@dage/utils";
import { DatePicker, Form, FormInstance } from "antd";
import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function BannerCreateOrEditPage() {
  const formRef = useRef<FormInstance>(null);
  const navigate = useNavigate();
  const params = useParams();
  const [loading, setLoading] = useState(false);

  const getDetail = useCallback(async () => {
    setLoading(true);
    try {
      const data = await bannerApi.getDetail(params.id as string);
      formRef.current?.setFieldsValue({
        publishDate: dayjs(data.publishDate),
        fileIds: [
          {
            uid: data.id,
            url: `${process.env.REACT_APP_API_URL}${process.env.REACT_APP_IMG_PUBLIC}${data.filePath}`,
            name: data.filePath,
          },
        ],
      });
    } finally {
      setLoading(false);
    }
  }, [params.id]);

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

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

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

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

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

    await bannerApi.save({
      ...rest,
      publishDate: formatDate(publishDate),
      filePath: fileIds[0].response
        ? fileIds[0].response.filePath
        : fileIds[0].name,
    });

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

  return (
    <div style={{ position: "relative" }}>
      {loading && <MemoSpinLoding />}
      <DageUploadProvider>
        <DageUploadConsumer>
          {(data) => (
            <>
              <Form
                ref={formRef}
                labelCol={{ span: 2 }}
                initialValues={{
                  publishDate: dayjs(),
                }}
              >
                <Form.Item
                  label="海报"
                  name="fileIds"
                  rules={[{ required: true, message: "请上传海报" }]}
                >
                  <DageUpload
                    tips="支持png、jpg和jpeg格式；最多1张，最大20M"
                    action={
                      process.env.REACT_APP_API_URL + "/api/cms/poster/upload"
                    }
                    maxSize={20}
                    maxCount={1}
                  />
                </Form.Item>

                <Form.Item
                  label="发布日期"
                  name="publishDate"
                  rules={[{ required: true, message: "请选择日期" }]}
                >
                  <DatePicker className="w220" format="YYYY-MM-DD" />
                </Form.Item>
              </Form>

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