import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./index.module.scss";
import { Button, Checkbox, Input, Modal, Popconfirm, Radio } from "antd";
import { A2Tab2Type } from "@/types/api/A2Dict";
import TextArea from "antd/es/input/TextArea";
import { MessageFu } from "@/utils/message";
import A2Tab2AddTable from "./A2Tab2AddTable";
import { RootState } from "@/store";
import { useSelector } from "react-redux";
import { A2_APIFileAdd } from "@/store/action/A2Dict";

const row3ArrData = [
  { id: 1, name: "所有格式" },
  { id: 2, name: "指定格式" },
];

const arrTemp = [
  {
    id: 1,
    done: true,
    label: "pdf",
  },
];

type Props = {
  info: A2Tab2Type;
  closeFu: () => void;
  addFu: () => void;
};

function A2Tab2Add({ info, closeFu, addFu }: Props) {
  // 文件名称
  const [name, setName] = useState("");

  // 文件说明
  const [description, setDescription] = useState("");

  // 支持格式
  const [row3, setRow3] = useState<"所有格式" | "指定格式">("所有格式");

  const [row3Arr, setRow3Arr] = useState(arrTemp);

  const row3OnChangeFu = useCallback(
    (val: boolean, id: number) => {
      if (row3Arr.filter((v) => v.done).length <= 1 && !val)
        return MessageFu.warning("至少指定一种格式!");

      setRow3Arr(
        row3Arr.map((v) => ({
          ...v,
          done: v.id === id ? val : v.done,
        }))
      );
    },
    [row3Arr]
  );

  // 责任部门
  const arr1 = useSelector((state: RootState) => state.A5Section.tableList);

  const [row4Id, setRow4Id] = useState("");

  const row4Ref = useRef<any>(null);

  // 所属阶段
  const arr2 = useSelector((state: RootState) => state.A2Dict.A2Tab1_2Arr);

  const [row5Id, setRow5Id] = useState("");

  const row5Ref = useRef<any>(null);

  //  如果是编辑
  useEffect(() => {
    if (info.id !== -1) {
      setName(info.name);
      setDescription(info.description);
      if (info.formatType === "0") setRow3("所有格式");
      else {
        setRow3("指定格式");
        const arr = info.suffix.split(",");
        arr.forEach((v1) => {
          arrTemp.forEach((v2) => {
            if (v1 === v2.label) v2.done = true;
          });
        });
        setRow3Arr(arrTemp);
      }

      setRow4Id(info.deptId + "");

      setRow5Id(info.stageId + "");
    }
  }, [info]);

  // 点击提交
  const btnOkFu = useCallback(async () => {
    if (!name) return MessageFu.warning("文件名称不能为空!");

    let obj = {};

    if (info.name === "其它") {
      obj = {
        id: info.id,
        name,
        description,
      };
    } else {
      const row3Txt = row3Arr
        .filter((v) => v.done)
        .map((v) => v.label)
        .join(",");

      const id3 = row4Ref.current.A2Tab2AddTableResFu();
      const id4 = row5Ref.current.A2Tab2AddTableResFu();

      if (!id3) return MessageFu.warning("请选择责任部门!");
      if (!id4) return MessageFu.warning("请选择所属阶段!");

      obj = {
        id: info.id === -1 ? null : info.id,
        name,
        description,
        deptId: id3 + "",
        stageId: id4 + "",
        suffix: row3 === "指定格式" ? row3Txt : "",
        formatType: row3 === "所有格式" ? "0" : "1",
        type: "内控文件",
      };
    }

    const res = await A2_APIFileAdd(obj);

    if (res.code === 0) {
      MessageFu.success(info.id === -1 ? "新增成功!" : "编辑成功!");
      addFu();
      closeFu();
    }
  }, [addFu, closeFu, description, info.id, info.name, name, row3, row3Arr]);

  return (
    <Modal
      wrapClassName={styles.A2Tab2Add}
      destroyOnClose
      open={true}
      title={info.id === -1 ? "新增内控文件" : "编辑内控文件"}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className="A2Tab2AddMain">
        <div className="A2Tab2AddMainC">
          <div className="A2Tab2AddRow">
            <span className="bs rowSpan">文件名称：</span>
            <div className="inputBox">
              <Input
                disabled={info.name === "其它"}
                maxLength={10}
                value={name}
                onChange={(e) => setName(e.target.value.replace(/\s+/g, ""))}
                showCount
                placeholder="请输入内容，不能重复"
              />
            </div>
          </div>

          <div className="A2Tab2AddRow">
            <span className="rowSpan">文件说明：</span>
            <div className="inputBox">
              <TextArea
                rows={4}
                placeholder="请输入内容"
                maxLength={100}
                showCount
                value={description}
                onChange={(e) =>
                  setDescription(e.target.value.replace(/\s+/g, ""))
                }
              />
            </div>
          </div>

          {info.name === "其它" ? null : (
            <>
              <div className="A2Tab2AddRow">
                <span className="bs rowSpan">支持格式：</span>
                <div className="A2Tab2AddRowRigth">
                  <Radio.Group
                    onChange={(e) => setRow3(e.target.value)}
                    value={row3}
                  >
                    {row3ArrData.map((v) => (
                      <Radio value={v.name} key={v.id}>
                        {v.name}
                      </Radio>
                    ))}
                  </Radio.Group>
                  <div className="A2T2row3" hidden={row3 === "所有格式"}>
                    {row3Arr.map((v) => (
                      <Checkbox
                        key={v.id}
                        onChange={(e) => row3OnChangeFu(e.target.checked, v.id)}
                        checked={v.done}
                      >
                        {v.label}
                      </Checkbox>
                    ))}
                  </div>
                </div>
              </div>

              <div className="A2Tab2AddRow">
                <span className="bs rowSpan">责任部门：</span>
                <div className="inputBox">
                  <A2Tab2AddTable
                    data={arr1}
                    type="部门"
                    valAc={row4Id}
                    ref={row4Ref}
                  />
                </div>
              </div>

              <div className="A2Tab2AddRow">
                <span className="bs rowSpan">所属阶段：</span>
                <div className="inputBox">
                  <A2Tab2AddTable
                    data={arr2}
                    type="阶段"
                    valAc={row5Id}
                    ref={row5Ref}
                  />
                </div>
              </div>
            </>
          )}
        </div>

        <div className="A2Tab2AddMBtn">
          <Popconfirm
            title="放弃编辑后，信息将不会保存!"
            okText="放弃"
            cancelText="取消"
            onConfirm={closeFu}
            okButtonProps={{ loading: false }}
          >
            <Button>取消</Button>
          </Popconfirm>
          &emsp;
          <Button type="primary" onClick={btnOkFu}>
            提交
          </Button>
        </div>
      </div>
    </Modal>
  );
}

const MemoA2Tab2Add = React.memo(A2Tab2Add);

export default MemoA2Tab2Add;
