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 { MessageFu } from "@/utils/message";
import MyPopconfirm from "@/components/MyPopconfirm";
import { A6_APIgetInfo, A6_APIsave } from "@/store/action/A6activity";
import ZRichText from "@/components/ZRichText";
import ZupVideos from "@/components/ZupVideos";

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

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

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

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

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

      setDirCode(entity.dirCode);

      // 设置富文本
      ZRichTextRef.current?.ritxtShowFu(entity.rtf);

      // 设置附件视频
      ZupVideosRef.current?.setFileComFileFu(file || []);

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

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

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

      FormBoxRef.current?.setFieldsValue({
        myTime: dayjs(Date.now()),
        isNeed: 0,
        dictId: activityList.find((v) => v.name === "其他")?.id,
      });
    }
  }, [activityList, 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 MessageFu.warning("请上传封面图!");

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

      const flieList = ZupVideosRef.current?.fileComFileResFu() || [];

      // 富文本
      const rtfObj = ZRichTextRef.current?.fatherBtnOkFu();

      const obj = {
        ...values,
        id: editId > 0 ? editId : null,
        publishDate,
        thumb: coverUrl1.filePath,
        rtf: rtfObj.val || "",
        fileIds: flieList.map((v: any) => v.id).join(","),
      };

      const res = await A6_APIsave(obj);

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

  return (
    <div className={styles.A6edit}>
      <div className="A6eMain">
        <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={activityList.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>

          {/* 视频 */}
          <div className="formRow">
            <div className="formLeft">视频：</div>
            <div className="formRight">
              <ZupVideos
                isLook={false}
                size={500}
                fileNum={5}
                dirCode={dirCode}
                myUrl="cms/activity/upload"
                upTxt="；数量不超过5个。"
                ref={ZupVideosRef}
              />
            </div>
          </div>

          <Form.Item
            label="需要预约"
            name="isNeed"
            rules={[{ required: true, message: "请选择需要预约!" }]}
          >
            <Select
              placeholder="请选择"
              style={{ width: 200 }}
              options={[
                { value: 0, label: "否" },
                { value: 1, label: "是" },
              ]}
            />
          </Form.Item>

          {/* 富文本 */}
          <div className="formRow">
            <div className="formLeft">正文：</div>
            <div className="formRight" style={{ height: 450 }}>
              <ZRichText
                check={false}
                dirCode={dirCode}
                isLook={false}
                ref={ZRichTextRef}
                myUrl="cms/activity/upload"
              />
            </div>
          </div>
          <br />

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

const MemoA6edit = React.memo(A6edit);

export default MemoA6edit;
