import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { Button, DatePicker, Form, FormInstance, Input } from "antd";
import dayjs from "dayjs";
import { A3_APIgetInfo, A3_APIsave } from "@/store/action/A3culture";
import { MessageFu } from "@/utils/message";
import ZupOne from "@/components/ZupOne";
import TextArea from "antd/es/input/TextArea";
import MyPopconfirm from "@/components/MyPopconfirm";

type Props = {
  editId: number;
  addTableFu: () => void;
  editTableFu: () => void;
  closeFu: () => void;
};

function A3edit({ editId, addTableFu, editTableFu, closeFu }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);

  // 封面图的ref
  const ZupThumbRef = useRef<any>(null);

  const getInfoFu = useCallback(async (id: number) => {
    const res = await A3_APIgetInfo(id);
    if (res.code === 0) {
      const data = res.data;
      FormBoxRef.current?.setFieldsValue({
        ...data,
        myTime: dayjs(data.publishDate),
      });

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

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

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

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setFileCheck(true);
  }, []);
  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFileCheck(true);

      const coverUrl1 = ZupThumbRef.current?.fileComFileResFu();
      // 没有传 封面图
      if (!coverUrl1.filePath) return;
      // 发布日期
      const publishDate = dayjs(values.myTime).format("YYYY-MM-DD");

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

      const res = await A3_APIsave(obj);

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

  return (
    <div className={styles.A3edit}>
      <div className="A3eMain">
        <Form
          ref={FormBoxRef}
          name="basic"
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          scrollToFirstError
        >
          <Form.Item
            label="标题"
            name="name"
            rules={[{ required: true, message: "请输入标题!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={30} showCount placeholder="请输入内容" />
          </Form.Item>

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

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

          <Form.Item
            label="跳转链接"
            name="link"
            rules={[{ required: true, message: "请输入跳转链接!" }]}
          >
            <TextArea maxLength={200} showCount placeholder="请输入内容" />
          </Form.Item>

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

const MemoA3edit = React.memo(A3edit);

export default MemoA3edit;
