import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { Button, Form, FormInstance, Input, Select } from "antd";
import ZupOne from "@/components/ZupOne";
import { A1_APIgetInfo, A1_APIsave } from "@/store/action/A1video";
import { MessageFu } from "@/utils/message";
import MyPopconfirm from "@/components/MyPopconfirm";

type Props = {
  addId: number;
  closeFu: () => void;
  addTableFu: () => void;
  type: "video" | "poster";
};

function A1add({ addId, closeFu, addTableFu, type }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null);

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

  //  通过校验点击确定
  const onFinish = useCallback(
    async (value: any) => {
      setFileCheck(true);
      const coverUrl1 = ZupOneRef1.current?.fileComFileResFu();
      // 没有传 封面图
      if (!coverUrl1.filePath) return;

      let coverUrl2 = { filePath: "", fileName: "" };

      if (type === "video") {
        coverUrl2 = ZupOneRef2.current?.fileComFileResFu();
        // 没有传 视频
        if (!coverUrl2.filePath) return;
      }

      const obj = {
        ...value,
        id: addId > 0 ? addId : null,
        thumb: coverUrl1.filePath,
        type,
        filePath: type === "video" ? coverUrl2.filePath : null,
        fileName: type === "video" ? coverUrl2.fileName : null,
      };

      const res = await A1_APIsave(obj);
      if (res.code === 0) {
        MessageFu.success(addId > 0 ? "编辑成功!" : "新增成功!");
        addTableFu();
        closeFu();
      }
    },
    [addId, addTableFu, closeFu, type]
  );

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

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

  // 通过id获取详情
  const getInfoFu = useCallback(async (id: number) => {
    const res = await A1_APIgetInfo(id);
    if (res.code === 0) {
      const data = res.data;
      FormBoxRef.current?.setFieldsValue({
        name: data.name,
        display: data.display,
      });
      ZupOneRef1.current?.setFileComFileFu({
        fileName: "",
        filePath: data.thumb,
      });
      ZupOneRef2.current?.setFileComFileFu({
        fileName: data.fileName,
        filePath: data.filePath,
      });
    }
  }, []);

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

  return (
    <div className={styles.A1add}>
      <div className="A1Amain">
        <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>

          {/* 封面 */}
          <div className="formRow">
            <div className="formLeft">
              <span>* </span>
              {type === "video" ? "封面" : "海报"}：
            </div>
            <div className="formRight">
              <ZupOne
                ref={ZupOneRef1}
                isLook={false}
                fileCheck={fileCheck}
                size={type === "video" ? 5 : 10}
                dirCode={type === "video" ? "tab1Video" : "tab2Poster"}
                myUrl="cms/poster/upload"
                format={["image/jpeg", "image/png"]}
                formatTxt="png、jpg和jpeg"
                checkTxt="请上传封面图"
                upTxt="最多1张，建议比例：6480*1920"
                myType="thumb"
              />
            </div>
          </div>

          {/* 视频 */}
          {type === "video" ? (
            <div className="formRow">
              <div className="formLeft">
                <span>* </span>视频：
              </div>
              <div className="formRight">
                <ZupOne
                  ref={ZupOneRef2}
                  isLook={false}
                  fileCheck={fileCheck}
                  size={500}
                  dirCode={type === "video" ? "tab1Video" : "tab2Poster"}
                  myUrl="cms/poster/upload"
                  format={["video/mp4"]}
                  formatTxt="mp4"
                  checkTxt="请上传视频"
                  upTxt="最多1个"
                  myType="video"
                />
              </div>
            </div>
          ) : null}

          <Form.Item
            label="自动播放"
            name="display"
            rules={[{ required: true, message: "请选择自动播放!" }]}
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              options={[
                { value: 1, label: "是" },
                { value: 0, label: "否" },
              ]}
            />
          </Form.Item>

          <div className="formLastTit">当设为“是”时，该内容将参与自动播放</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 MemoA1add = React.memo(A1add);

export default MemoA1add;
