import { FormPageFooter, MemoSpinLoding } from "@/components";
import {
  DageUpload,
  DageUploadConsumer,
  DageUploadProvider,
  DageUploadType,
} from "@dage/pc-components";
import { DatePicker, Form, FormInstance, Input, Radio } from "antd";
import { useCallback, useEffect, useRef, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import RichText from "@/components/Z_RichText";
import { dayjs, formatDate } from "@dage/utils";
import { informationApi } from "@/api";
import { TYPE_LIST } from "../constants";

export default function InformationCreateOrEditPage() {
  const formRef = useRef<FormInstance>(null);
  const navigate = useNavigate();
  const params = useParams();
  const [loading, setLoading] = useState(false);
  const richTxtRef = useRef<any>(null);
  // 文件的code码
  const [dirCode, setDirCode] = useState("");

  const getDetail = useCallback(async () => {
    setLoading(true);
    try {
      setDirCode(params.id as string);

      const { thumb, video, publishDate, richText, ...rest } =
        await informationApi.getDetail(params.id as string);

      formRef.current?.setFieldsValue({
        publishDate: dayjs(publishDate),
        fileIds: [
          {
            uid: thumb,
            url: `${process.env.REACT_APP_API_URL}${process.env.REACT_APP_IMG_PUBLIC}${thumb}`,
            name: thumb,
          },
        ],
        videoFileIds: video
          ? [
              {
                uid: video,
                url: `${process.env.REACT_APP_API_URL}${process.env.REACT_APP_IMG_PUBLIC}${video}`,
                name: video,
              },
            ]
          : [],
        ...rest,
      });

      richTxtRef.current.ritxtShowFu(richText);
    } 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 { val, flag } = richTxtRef.current.fatherBtnOkFu();
    const {
      fileIds = [],
      videoFileIds = [],
      publishDate,
      richText,
      ...rest
    } = formRef.current?.getFieldsValue();

    if (flag) return;

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

    if (videoFileIds[0]) {
      rest.video = videoFileIds[0].response
        ? videoFileIds[0].response.filePath
        : videoFileIds[0].name;
    }

    await informationApi.save({
      ...rest,
      publishDate: formatDate(publishDate),
      richText: val,
      thumb: 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="name"
                  rules={[{ required: true, message: "请输入内容" }]}
                >
                  <Input
                    className="w220"
                    placeholder="请输入内容，最多20字"
                    maxLength={20}
                    showCount
                  />
                </Form.Item>
                <Form.Item
                  label="类型"
                  name="type"
                  rules={[{ required: true, message: "请选择" }]}
                >
                  <Radio.Group>
                    {TYPE_LIST.map((item) => (
                      <Radio.Button key={item.value} value={item.value}>
                        {item.label}
                      </Radio.Button>
                    ))}
                  </Radio.Group>
                </Form.Item>
                <Form.Item
                  label="正文"
                  name="richText"
                  rules={[{ required: true, message: "请输入正文" }]}
                >
                  <RichText
                    myUrl="/api/cms/news/upload"
                    ref={richTxtRef}
                    dirCode={dirCode}
                    isLook={false}
                  />
                </Form.Item>
                <Form.Item
                  label="发布日期"
                  name="publishDate"
                  rules={[{ required: true, message: "请选择发布日期" }]}
                >
                  <DatePicker className="w220" format="YYYY-MM-DD" />
                </Form.Item>
                <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/news/upload"
                    }
                    maxSize={20}
                    maxCount={1}
                  />
                </Form.Item>
                <Form.Item label="视频" name="videoFileIds">
                  <DageUpload
                    dType={DageUploadType.VIDEO}
                    tips="支持avi,mp4,mkv,wmv等格式；最大200M，最多1个"
                    action={
                      process.env.REACT_APP_API_URL + "/api/cms/news/upload"
                    }
                    maxSize={200}
                    maxCount={1}
                  />
                </Form.Item>
              </Form>

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