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

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

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

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

      setDirCode(data.dirCode);

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

      // 设置二维码
      if (data.qrCode) {
        ZupOneRefCode.current?.setFileComFileFu({
          fileName: "",
          filePath: data.qrCode,
        });
      }

      const file = res.data.file;

      // 传给 附件 组件的
      const sonInfo = {
        type: data.fileType,
        fileList: file,
      };
      ZupOneRef2.current?.setFileComFileFu(sonInfo);
    }
  }, []);

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

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

  // 文件的code码
  const [dirCode, setDirCode] = useState("");

  // 表单的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");

      // 附件组件的 type 数组 和 附件id数组
      const { sonType, sonFileIds } = ZupOneRef2.current?.fileComFileResFu();

      //  底部附件组件为必传信息
      //  if(sonInfo.sonIsOk) return

      const qrCodeTemp = ZupOneRefCode.current?.fileComFileResFu();

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

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

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

          <Form.Item
            label="类别"
            name="type"
            rules={[{ required: true, message: "请选择类别!" }]}
          >
            <Radio.Group>
              <Radio value="3D">三维文物</Radio>
              <Radio value="2D">二维文物</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 封面 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              封面图：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef1}
                isLook={false}
                fileCheck={fileCheck}
                size={5}
                dirCode={dirCode}
                myUrl="cms/goods/upload"
                format={["image/jpeg", "image/png"]}
                formatTxt="png、jpg和jpeg"
                checkTxt="请上传封面图"
                upTxt="最多1张"
                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={ZupOneRefCode}
                isLook={false}
                fileCheck={false}
                size={5}
                dirCode={dirCode + "Code"}
                myUrl="cms/goods/upload"
                format={["image/jpeg", "image/png"]}
                formatTxt="png、jpg和jpeg"
                checkTxt="请上传二维码"
                upTxt="最多1张"
                myType="thumb"
              />
            </div>
          </div>

          <Form.Item
            label="分类"
            name="dictType"
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={20} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="时代"
            name="dictAge"
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={10} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="质地"
            name="dictTexture"
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={10} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item label="级别" name="dictLevel">
            <Select
              placeholder="请选择"
              style={{ width: 400 }}
              options={[
                { value: "一级", label: "一级" },
                { value: "二级", label: "二级" },
                { value: "三级", label: "三级" },
              ]}
            />
          </Form.Item>

          <Form.Item
            label="尺寸"
            name="dictSize"
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={50} showCount placeholder="请输入内容" />
          </Form.Item>

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

          <Form.Item
            label="模型链接"
            name="modelLink"
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <TextArea
              className="A5link"
              placeholder="请输入内容"
              showCount
              maxLength={200}
            />
          </Form.Item>

          {/* 文件类型 */}
          <div className="formRow">
            <div className="formLeft">文件类型：</div>
            <div className="formRight">
              <ZupTypes
                ref={ZupOneRef2}
                // 这个项目没有模型
                selecFlag="图片/音频/视频"
                isLook={false}
                fileCheck={false}
                dirCode={dirCode}
                myUrl="cms/goods/upload"
                // 音频大小
                audioSize={50}
                // 视频上传的提示语
                videoTit="建议视频尺寸比例 16 : 9"
              />
            </div>
          </div>

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

const MemoA5add = React.memo(A5add);

export default MemoA5add;
