import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import {
  Button,
  Form,
  FormInstance,
  Input,
  Modal,
  Popconfirm,
  Select,
} from "antd";
import UpFileOne from "@/components/Z_upFileOne";
import { A2TableType } from "@/types";

import { PlusCircleOutlined, CloseOutlined } from "@ant-design/icons";
import TextArea from "antd/es/input/TextArea";
import { A2_APIeditItem } from "@/store/action/A2Gallery";
import { MessageFu } from "@/utils/message";

type Props = {
  isEdit: { type: string; id: number; info: A2TableType; pid: number };
  inCloseFu: () => void;
  inEditFu: () => void;
};

function A2Modal({ isEdit, inCloseFu, inEditFu }: Props) {
  const FormBoxRef = useRef<FormInstance>(null);

  useEffect(() => {
    if (isEdit.type === "add") {
      FormBoxRef.current?.setFieldsValue({
        type: "基本陈列",
      });
    } else {
      FormBoxRef.current?.setFieldsValue(isEdit.info);
      setCover(isEdit.info.thumb);
      if (isEdit.info.tag) setTag(isEdit.info.tag.split(","));
    }
  }, [isEdit.info, isEdit.type]);

  // 封面图
  const [cover, setCover] = useState("");

  // 校验
  const [fromCheck, setFromCheck] = useState(false);

  // 标签数组
  const [tag, setTag] = useState([] as string[]);
  const tagChange = useCallback(
    (val: string, ind: number) => {
      const arr = [...tag];
      arr[ind] = val;
      setTag(arr);
    },
    [tag]
  );

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    setFromCheck(true);
    // return MessageFu.warning("有表单不符号规则!");
  }, []);

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      setFromCheck(true);
      if (!cover) return;

      const obj = {
        ...values,
        id: isEdit.type === "add" ? null : isEdit.id,
        parentId: isEdit.pid,
        thumb: cover,
        tag: tag.filter((v) => v !== "").join(","),
      };

      const res = await A2_APIeditItem(obj);

      if (res.code === 0) {
        MessageFu.success(isEdit.type === "add" ? "新增成功!" : "编辑成功!");
        inEditFu();
        inCloseFu();
      }
    },
    [cover, inCloseFu, inEditFu, isEdit.id, isEdit.pid, isEdit.type, tag]
  );

  return (
    <Modal
      wrapClassName={styles.A2Modal}
      destroyOnClose
      open={true}
      title={isEdit.type === "add" ? "新增展览" : "编辑展览"}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="Modal_box">
        <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={50} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="展览类型"
            name="type"
            rules={[{ required: true, message: "请输入展览名称!" }]}
          >
            <Select
              placeholder="请选择"
              style={{ width: 400 }}
              options={[
                { value: "基本陈列", label: "基本陈列" },
                { value: "临时展览", label: "临时展览" },
                { value: "专题展览", label: "专题展览" },
              ]}
            />
          </Form.Item>

          {/* 封面图 */}
          <div className="e_row">
            <div className="e_rowL">
              <span>* </span>封面：
            </div>
            <div className="e_rowR">
              <UpFileOne
                myUrl="cms/exhibition/upload"
                cover={cover}
                setCover={(val) => setCover(val)}
                isLook={false}
                coverCheck={fromCheck}
                size={5}
                dirCode={"inZ"}
              />
            </div>
          </div>

          {/* 标签 */}
          <div className="e_row e_rowTag">
            <div className="e_rowL">
              <span> </span>标签：
            </div>
            <div className="e_rowR">
              <Button
                onClick={() => setTag([...tag, ""])}
                type="primary"
                disabled={tag.some((v) => v === "")}
                icon={<PlusCircleOutlined />}
                hidden={tag.length >= 3}
              />
              &emsp;
              {tag.map((v, i) => (
                <div className="A2_Mtag" key={i}>
                  <Input
                    maxLength={6}
                    placeholder="请输入内容"
                    value={v}
                    onChange={(e) => tagChange(e.target.value.trim(), i)}
                  />

                  <div
                    className="tagClose"
                    onClick={() => setTag(tag.filter((v2, i2) => i2 !== i))}
                  >
                    <CloseOutlined />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <Form.Item
            label="展览地点"
            name="address"
            rules={[{ required: true, message: "请输入展览地点!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <Input maxLength={50} showCount placeholder="请输入内容" />
          </Form.Item>

          <Form.Item
            label="跳转链接"
            name="link"
            rules={[{ required: true, message: "请输入跳转链接!" }]}
            getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          >
            <TextArea
              autoSize
              placeholder="请输入内容"
              showCount
              maxLength={200}
            />
          </Form.Item>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 10, span: 16 }}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
            &emsp;
            <Popconfirm
              title="放弃编辑后，信息将不会保存!"
              okText="放弃"
              cancelText="取消"
              onConfirm={inCloseFu}
            >
              <Button>取消</Button>
            </Popconfirm>
          </Form.Item>
        </Form>
      </div>
    </Modal>
  );
}

const MemoA2Modal = React.memo(A2Modal);

export default MemoA2Modal;
