import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { Button, DatePicker, Form, FormInstance, Input, Modal } from "antd";
import MyPopconfirm from "@/components/MyPopconfirm";
import ZupOne from "@/components/ZupOne";
import { MessageFu } from "@/utils/message";
import { A7_APIgetInfoBook, A7_APIsaveBook } from "@/store/action/A7school";
import dayjs from "dayjs";

type Props = {
  fId: number;
  closeFu: () => void;
  addTableFu: () => void;
  upTableFu: () => void;
};

function A7tab2M({ fId, closeFu, addTableFu, upTableFu }: Props) {
  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<FormInstance>(null);

  const getInfoFu = useCallback(async (id: number) => {
    const res = await A7_APIgetInfoBook(id);
    if (res.code === 0) {
      const data = res.data;

      FormBoxRef.current?.setFieldsValue({
        ...data,
        myTime: dayjs(data.publishDate),
      });

      // 设置封面图
      ZupOneRef1.current?.setFileComFileFu({
        fileName: "",
        filePath: data.thumb,
      });
      // 设置附件
      ZupOneRef2.current?.setFileComFileFu({
        fileName: data.fileName,
        filePath: data.filePath,
      });
    }
  }, []);

  useEffect(() => {
    if (fId > 0) getInfoFu(fId);
    else {
      FormBoxRef.current?.setFieldsValue({
        myTime: dayjs(Date.now()),
      });
    }
  }, [fId, getInfoFu]);

  // 附件的ref
  const ZupOneRef1 = useRef<any>(null);
  const ZupOneRef2 = useRef<any>(null);

  // 附件 是否 已经点击过确定
  const [fileCheck, setFileCheck] = useState(false);

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setFileCheck(true);
  }, []);
  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFileCheck(true);
      // 没有传 封面图 或者 附件
      const coverUrl1 = ZupOneRef1.current?.fileComFileResFu();
      const coverUrl2 = ZupOneRef2.current?.fileComFileResFu();

      if (!coverUrl1.filePath || !coverUrl2.filePath) return;

      // 发布日期
      const publishDate = dayjs(values.myTime).format("YYYY-MM-DD");

      const obj = {
        ...values,
        id: fId > 0 ? fId : null,
        fileName: coverUrl2.fileName,
        filePath: coverUrl2.filePath,
        thumb: coverUrl1.filePath,
        publishDate,
      };

      const res = await A7_APIsaveBook(obj);

      if (res.code === 0) {
        MessageFu.success(fId > 0 ? "编辑成功!" : "新增成功!");
        fId > 0 ? addTableFu() : upTableFu();
        closeFu();
      }
    },
    [addTableFu, closeFu, fId, upTableFu]
  );

  return (
    <Modal
      // 和 A7tab1M 共用样式
      wrapClassName={styles.A7tab1M}
      open={true}
      title={`${fId > 0 ? "编辑" : "新增"}刊物`}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A7mMaiin">
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name="basic"
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="刊物标题"
            name="name"
            rules={[{ required: true, message: "请输入刊物标题!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={10} showCount placeholder="请输入内容" />
          </Form.Item>

          {/* 刊物封面 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              刊物封面：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef1}
                isLook={false}
                fileCheck={fileCheck}
                size={2}
                dirCode="schoolThumb2"
                myUrl="cms/periodical/upload"
                format={["image/jpeg", "image/png"]}
                formatTxt="png、jpg和jpeg"
                checkTxt="请上传刊物封面!"
                upTxt="最多1张"
                myType="thumb"
              />
            </div>
          </div>

          {/* 刊物附件  */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              刊物附件：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef2}
                isLook={false}
                fileCheck={fileCheck}
                size={5}
                dirCode="schoolPdf"
                myUrl="cms/periodical/upload"
                format={["application/pdf"]}
                formatTxt="pdf"
                checkTxt="请上传刊物附件!"
                upTxt="最多1个"
                myType="pdf"
              />
            </div>
          </div>

          <Form.Item
            label="发布日期"
            name="myTime"
            rules={[{ required: true, message: "请选择发布日期!" }]}
          >
            <DatePicker />
          </Form.Item>

          {/* 确定和取消按钮 */}
          <Form.Item className="A7mbtn">
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            <br />
            <br />
            <MyPopconfirm txtK="取消" onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
}

const MemoA7tab2M = React.memo(A7tab2M);

export default MemoA7tab2M;
