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

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

function A4add({ addId, closeFu, addTableFu, editTableFu }: Props) {
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A4_APIgetInfo(id);
    if (res.code === 0) {
      const data = res.data;

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

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

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

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

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);

  // 没有通过校验
  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 qrCodeTemp = ZupOneRef2.current?.fileComFileResFu();

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

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

  return (
    <div className={styles.A4add}>
      <div className="A4Amain">
        <Form
          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={50} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item label="分类" name="type">
            <Select
              allowClear
              placeholder="请选择"
              style={{ width: 200 }}
              options={[
                { value: "回顾云展", label: "回顾云展" },
                { value: "展厅云展", label: "展厅云展" },
                { value: "馆藏系列云展", label: "馆藏系列云展" },
              ]}
            />
          </Form.Item>

          <Form.Item label="简介" name="description">
            <TextArea placeholder="请输入内容" showCount maxLength={1000} />
          </Form.Item>

          <Form.Item
            label="场景链接"
            name="link"
            rules={[{ required: true, message: "请输入场景链接!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <TextArea
              className="A4link"
              placeholder="请输入内容"
              showCount
              maxLength={200}
            />
          </Form.Item>

          {/* 封面 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              封面图：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef1}
                isLook={false}
                fileCheck={fileCheck}
                size={5}
                dirCode="tab4Exhibit"
                myUrl="cms/exhibition/upload"
                format={["image/jpeg", "image/png"]}
                formatTxt="png、jpg和jpeg"
                checkTxt="请上传封面图"
                upTxt="最多1张。建议封面图比例 16 : 9"
                myType="thumb"
              />
            </div>
          </div>

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

          {/* 二维码 */}
          <div className="formRow">
            <div className="formLeft">二维码：</div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef2}
                isLook={false}
                fileCheck={false}
                size={5}
                dirCode="tab4ExhibitCode"
                myUrl="cms/exhibition/upload"
                format={["image/jpeg", "image/png"]}
                formatTxt="png、jpg和jpeg"
                checkTxt="请上传二维码"
                upTxt="最多1张"
                myType="thumb"
              />
            </div>
          </div>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK="取消" onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

const MemoA4add = React.memo(A4add);

export default MemoA4add;
