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

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

function A4edit({
  editId,
  goodsList,
  addTableFu,
  editTableFu,
  closeFu,
}: Props) {
  const [dirCode, setDirCode] = useState("");

  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);
  // 封面图的ref
  const ZupThumbRef = useRef<any>(null);
  // 文件 类型的ref
  const ZupFilesRef = useRef<any>(null);

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

      const entity = data.entity;
      const file = data.file;

      setDirCode(entity.dirCode);

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

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

      // 设置文件类型
      const sonInfo = {
        type: entity.fileTypes,
        fileList: file,
      };
      ZupFilesRef.current?.setFileComFileFu(sonInfo);
    }
  }, []);

  useEffect(() => {
    if (editId > 0) {
      getInfoFu(editId);
    } else {
      setDirCode(Date.now() + "");

      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;

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

      if (sonIsOk) return;

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

      const obj = {
        ...values,
        id: editId > 0 ? editId : null,
        publishDate,
        thumb: coverUrl1.filePath,
        fileTypes: sonType ? sonType.join(",") : null,
        fileIds: sonFileIds ? sonFileIds.join(",") : null,
      };

      const res = await A4_APIsave(obj);

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

  return (
    <div className={styles.A4edit}>
      <div className="A4eMain">
        <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="dictId"
            rules={[{ required: true, message: "请选择所属栏目!" }]}
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              options={goodsList.map((v) => ({ value: v.id, label: v.name }))}
            />
          </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={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="modelLink"
            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">
              <ZupTypes
                ref={ZupFilesRef}
                // 这个项目没有模型
                selecFlag="图片/音频/视频"
                isLook={false}
                fileCheck={fileCheck}
                dirCode={dirCode}
                myUrl="cms/goods/upload"
              />
            </div>
          </div>

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

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

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

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

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

const MemoA4edit = React.memo(A4edit);

export default MemoA4edit;
