import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import {
  Button,
  DatePicker,
  Form,
  FormInstance,
  Input,
  InputNumber,
  Select,
} from "antd";
import MyPopconfirm from "@/components/MyPopconfirm";
import { MessageFu } from "@/utils/message";
import dayjs from "dayjs";
import { A4_APIgetInfo, A4_APIsave } from "@/store/action/A4store";
import ZupOne from "@/components/ZupOne";
import ZRichText from "@/components/ZRichText";

type Props = {
  editInfo: { id: number; type: "新增" | "编辑" };
  closeFu: () => void;
  upTableFu: () => void;
  addTableFu: () => void;
};

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


  // 封面图的ref
  const ZupOneRef1 = useRef<any>(null);
  // 富文本的ref
  const ZRichTextRef = useRef<any>(null);

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

      ZRichTextRef.current?.ritxtShowFu(data.rtf);


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

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

  useEffect(() => {
    if (editInfo.id > 0) {
      // 编辑
      getInfoFu(editInfo.id);
    } else {
      // 新增
      FormBoxRef.current?.setFieldsValue({
        myTime: dayjs(Date.now()),
        isEnabled: 1,
      });
    }
  }, [editInfo.id, getInfoFu]);

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

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setFileCheck(true);
  }, []);

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFileCheck(true);

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

      const rtf = ZRichTextRef.current?.fatherBtnOkFu();

      const obj = {
        ...values,
        id: editInfo.id > 0 ? editInfo.id : null,
        releaseDate,
        thumb: coverUrl1.filePath,
        rtf: rtf.val,
      };
      const res = await A4_APIsave(obj);
      if (res.code === 0) {
        MessageFu.success(editInfo.id > 0 ? "编辑成功!" : "新增成功!");
        editInfo.id > 0 ? upTableFu() : addTableFu();
        closeFu();
      }
    },
    [addTableFu, closeFu, editInfo.id, upTableFu]
  );

  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={20} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="所需爱心币"
            name="score"
            rules={[{ required: true, message: "请输入所需爱心币!" }]}
          >
            <InputNumber
              min={1}
              max={99999}
              precision={0}
              placeholder="请输入数字，1~99999"
            />
          </Form.Item>

          <Form.Item
            label="库存"
            name="stock"
            rules={[{ required: true, message: "请输入库存!" }]}
          >
            <InputNumber
              min={1}
              max={99999}
              precision={0}
              placeholder="请输入数字，1~99999"
            />
          </Form.Item>

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

          <Form.Item
            label="上架状态"
            name="isEnabled"
            rules={[{ required: true, message: "请选择上架状态!" }]}
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              options={[
                { value: 1, label: "上架" },
                { value: 0, label: "下架" },
              ]}
            />
          </Form.Item>
          {/* 封面 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              封面图：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef1}
                isLook={false}
                fileCheck={fileCheck}
                size={2}
                dirCode='storeThumb'
                myUrl="cms/prize/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">
              <ZRichText
                check={false}
                dirCode='storeText'
                isLook={false}
                ref={ZRichTextRef}
                myUrl="cms/prize/upload"
              />
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <Form.Item className="A4Ebtn">
            <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;
