import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { A1EditInfoType } from "@/pages/A1event/data";
import {
  Button,
  DatePicker,
  Form,
  FormInstance,
  Input,
  InputNumber,
  Select,
} from "antd";
import { A3_APIgetInfo, A3_APIsave } from "@/store/action/A3holding";
import dayjs from "dayjs";
import { MessageFu } from "@/utils/message";
import classNames from "classnames";
import ZupAudio from "@/components/ZupAudio";
import ZRichTexts from "@/components/ZRichTexts";
import ZupTypes from "@/components/ZupTypes";
import MyPopconfirm from "@/components/MyPopconfirm";
import TextArea from "antd/es/input/TextArea";
import { A3Selct_1 } from "../data";

type Props = {
  editInfo: A1EditInfoType;
  selectAgeArr: { value: number | string; label: string }[];
  closeFu: () => void;
  editTableFu: () => void;
  addTableFu: () => void;
};

function A3add({
  editInfo,
  selectAgeArr,
  closeFu,
  editTableFu,
  addTableFu,
}: Props) {
  const [dirCode, setDirCode] = useState("");

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

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

  // 标题的音频
  const [nameAudio, setNameAudio] = useState({
    fileName: "",
    filePath: "",
  });
  // 多个图片的ref
  const ZupFilesRef2 = useRef<any>(null);

  // 编辑/查看 进入页面 获取信息
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A3_APIgetInfo(id);
    if (res.code === 0) {
      const data = res.data;

      setDirCode(data.dirCode);

      // 展示图片
      ZupFilesRef2.current?.setFileComFileFu({
        type: "img",
        fileList: data.files || [],
      });

      // 设置标题的 音频
      if (data.fileName && data.filePath) {
        setNameAudio({
          fileName: data.fileName,
          filePath: data.filePath,
        });
      }
      // 设置富文本
      ZRichTextRef.current?.ritxtShowFu(JSON.parse(data.rtf));

      const obj = {
        ...data,
        myTime: dayjs(data.datePublish),
      };

      FormBoxRef.current?.setFieldsValue(obj);
    }
  }, []);

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

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

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

      // 图片的校验
      const { sonFileIds: fileIds, coverUrl } =
        ZupFilesRef2.current?.fileComFileResFu();

      if (fileIds.length <= 0) {
        return MessageFu.warning("请最少上传一张图片!");
      }

      // 富文本校验不通过
      const rtf = ZRichTextRef.current?.fatherBtnOkFu() || { flag: true };

      if (rtf.flag) return MessageFu.warning("请输入完整正文!");

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

      const obj = {
        ...values,
        id: editInfo.id > 0 ? editInfo.id : null,
        datePublish,
        thumb: coverUrl,
        rtf: JSON.stringify(rtf.val || ""),
        fileName: nameAudio.fileName,
        filePath: nameAudio.filePath,
        fileIds: fileIds.join(","),
        dirCode,
      };
      const res = await A3_APIsave(obj);

      if (res.code === 0) {
        MessageFu.success(`${editInfo.txt}成功!`);
        editInfo.id > 0 ? editTableFu() : addTableFu();
        closeFu();
      }
    },
    [addTableFu, closeFu, dirCode, editInfo, editTableFu, nameAudio]
  );

  useEffect(() => {
    if (editInfo.id > 0) {
      getInfoFu(editInfo.id);
    } else {
      setDirCode(Date.now() + "");
      FormBoxRef.current?.setFieldsValue({
        myTime: dayjs(Date.now()),
        sort: 999,
        display: 1,
      });
    }
  }, [editInfo.id, getInfoFu]);

  return (
    <div className={styles.A3add}>
      <div
        className={classNames(
          "A3eMain",
          editInfo.txt === "查看" ? "A3eMainLook" : ""
        )}
      >
        <Form
          ref={FormBoxRef}
          name="basic"
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
          scrollToFirstError
        >
          <div className="A3fromRow">
            <Form.Item
              label="名称"
              name="name"
              rules={[{ required: true, message: "请输入名称!" }]}
              // getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
            >
              <TextArea
                readOnly={editInfo.txt === "查看"}
                style={{ width: "500px" }}
                maxLength={100}
                showCount
                placeholder="请输入内容"
              />
            </Form.Item>
            {/* 标题的无障碍音频 */}
            <div className="A3_1Frow">
              <ZupAudio
                fileInfo={nameAudio}
                upDataFu={(info) => setNameAudio(info)}
                delFu={() => setNameAudio({ fileName: "", filePath: "" })}
                dirCode={dirCode}
                myUrl="cms/collection/upload"
                isLook={editInfo.txt === "查看"}
              />
            </div>
          </div>

          {/* 图片 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              图片：
            </div>
            <div className="formRight">
              <ZupTypes
                ref={ZupFilesRef2}
                selecFlag="图片"
                fileCheck={fileCheck}
                dirCode={dirCode}
                myUrl="cms/collection/upload"
                isLook={editInfo.txt === "查看"}
                imgLength={50}
                isTypeShow={true}
                lastImgTxt="第一张将作为封面"
                oneIsCover={true}
              />
            </div>
          </div>

          <Form.Item
            label="类别"
            name="type"
            rules={[{ required: true, message: "请选择类别!" }]}
          >
            <Select
              placeholder="请选择类别"
              style={{ width: 200 }}
              options={A3Selct_1.filter((v) => v.label !== "全部")}
            />
          </Form.Item>

          <Form.Item
            label="年代"
            name="dictAgeId"
            rules={[{ required: true, message: "请选择年代!" }]}
          >
            <Select
              placeholder="请选择年代"
              style={{ width: 200 }}
              options={selectAgeArr.filter((v) => v.label !== "全部")}
            />
          </Form.Item>

          <Form.Item label="作者" name="author">
            <Input
              readOnly={editInfo.txt === "查看"}
              maxLength={50}
              showCount
              placeholder="请输入内容"
            />
          </Form.Item>

          <Form.Item label="尺寸" name="size">
            <Input
              readOnly={editInfo.txt === "查看"}
              maxLength={50}
              showCount
              placeholder="请输入内容"
            />
          </Form.Item>

          <Form.Item label="摘要" name="digest">
            <TextArea
              readOnly={editInfo.txt === "查看"}
              placeholder="请输入内容"
              maxLength={500}
              showCount
            />
          </Form.Item>

          {/* 简介 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              简介：
            </div>
            <div className="formRight">
              <ZRichTexts
                check={fileCheck}
                dirCode={dirCode}
                isLook={editInfo.txt === "查看"}
                ref={ZRichTextRef}
                myUrl="cms/collection/upload"
                isOne={true}
              />
            </div>
          </div>

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

          <div className="A3fromRow">
            <Form.Item
              label="排序值"
              name="sort"
              rules={[{ required: true, message: "请输入排序值!" }]}
            >
              <InputNumber
                min={1}
                max={999}
                precision={0}
                placeholder="请输入"
              />
            </Form.Item>
            <div className="A3_6Frow" hidden={editInfo.txt === "查看"}>
              请输入1~999的数字。数字越小，排序越靠前。数字相同时，更新发布的内容排在前面
            </div>
          </div>

          <Form.Item
            label="状态"
            name="display"
            rules={[{ required: true, message: "请选择状态!" }]}
          >
            <Select
              placeholder="请选择状态"
              style={{ width: 149 }}
              options={[
                { value: 1, label: "发布" },
                { value: 0, label: "不发布" },
              ]}
            />
          </Form.Item>

          {/* 确定和取消按钮 */}
          <Form.Item className="A3Ebtn">
            {editInfo.txt === "查看" ? (
              <Button onClick={closeFu}>返回</Button>
            ) : (
              <>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
                <br />
                <br />
                <MyPopconfirm txtK="取消" onConfirm={closeFu} />
              </>
            )}
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

const MemoA3add = React.memo(A3add);

export default MemoA3add;
