import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import {
  Button,
  Form,
  FormInstance,
  Input,
  InputNumber,
  Modal,
  Select,
} from "antd";
import {
  A7_APIgetInfo,
  A7_APIgetListByTheme,
  A7_APIsave,
} from "@/store/action/A7school";
import { ListType } from "./A7theme";
import MyPopconfirm from "@/components/MyPopconfirm";
import TextArea from "antd/es/input/TextArea";
import ZupOne from "@/components/ZupOne";
import { MessageFu } from "@/utils/message";

type Props = {
  fId: number;
  closeFu: () => void;
  addTableFu: () => void;
  upTableFu: () => void;
};

function A7tab1M({ fId, closeFu, addTableFu, upTableFu }: Props) {
  // 设置表单初始数据（区分编辑和新增）
  const FormBoxRef = useRef<FormInstance>(null);

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

      FormBoxRef.current?.setFieldsValue(data);

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

  const [selList, setSelList] = useState<ListType[]>([]);

  const getSelList = useCallback(async () => {
    const res = await A7_APIgetListByTheme();
    if (res.code === 0) setSelList(res.data);
  }, []);

  useEffect(() => {
    getSelList();
    if (fId > 0) getInfoFu(fId);
  }, [fId, getInfoFu, getSelList]);

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

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

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setFileCheck(true);
  }, []);
  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFileCheck(true);
      // 没有传 封面图 或者视频
      const coverUrl1 = ZupOneRef1.current?.fileComFileResFu();
      const coverUrl2 = ZupOneRef2.current?.fileComFileResFu();

      if (!coverUrl1.filePath || !coverUrl2.filePath) return;

      const obj = {
        ...values,
        id: fId > 0 ? fId : null,
        fileName: coverUrl2.fileName,
        filePath: coverUrl2.filePath,
        thumb: coverUrl1.filePath,
      };

      const res = await A7_APIsave(obj);

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

  return (
    <Modal
      wrapClassName={styles.A7tab1M}
      open={true}
      title={`${fId > 0 ? "编辑" : "新增"}口述史`}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A7mMaiin">
        <Form
          scrollToFirstError={true}
          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={10} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="人物简介"
            name="description"
            rules={[{ required: true, message: "请输入人物简介!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <TextArea maxLength={200} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="排序值"
            name="sort"
            rules={[{ required: true, message: "请输入排序值!" }]}
          >
            <InputNumber
              min={1}
              max={999}
              precision={0}
              placeholder="请输入1~999，数字越小，排序越前"
            />
          </Form.Item>

          <Form.Item
            label="采访主题"
            name="dictId"
            rules={[{ required: true, message: "请选择采访主题!" }]}
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              options={selList.map((v) => ({
                value: v.id,
                label: v.name,
              }))}
            />
          </Form.Item>
          {/* 封面 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              人物肖像：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef1}
                isLook={false}
                fileCheck={fileCheck}
                size={2}
                dirCode="schoolThumb"
                myUrl="cms/person/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">
              <ZupOne
                ref={ZupOneRef2}
                isLook={false}
                fileCheck={fileCheck}
                size={500}
                dirCode="schoolVideo"
                myUrl="cms/person/upload"
                format={["video/mp4"]}
                formatTxt="mp4"
                checkTxt="请上传采访视频!"
                upTxt=""
                myType="video"
              />
            </div>
          </div>

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

const MemoA7tab1M = React.memo(A7tab1M);

export default MemoA7tab1M;
