import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Cascader, Input, Select, Table, Tooltip } from "antd";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import {
  A1_APIIdowns,
  A1_APIIgetIresList,
  A1_APIIgetList,
} from "@/store/action/A1Project";
import { A1ItableType } from "@/types";
import { authFilesLookFu, urlChangeFu } from "@/utils/authFilesLook";
import A1IRemove from "./A1IRemove";
import A1ILack from "./A1ILack";
import A1IAudit from "./A1IAudit";
import A1IupFile from "./A1IupFile";
import { baseUpUrl } from "@/utils/http";
import { A2Tab2Type } from "@/types/api/A2Dict";
import AuthCom from "@/components/AuthCom";

type FromType = {
  searchKey: string;
  attrId: number | "";
  deptId: any;
  auditStatus: 0 | 1 | 2 | "";
  projectId: number;
};

type Props = {
  projectId: number;
  myTitle: string;
  projectName: string;
};

function A1Inner({ projectId, myTitle, projectName }: Props) {
  // 表单数据
  const [fromData, setFromData] = useState<FromType>({
    searchKey: "",
    attrId: "",
    deptId: [""],
    auditStatus: "",
    projectId,
  });
  // 关于表格的多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  const getListFu = useCallback(async () => {
    // 处理级联为最后一级的id
    let deptId: "" | number = "";

    if (fromData.deptId && fromData.deptId[0]) {
      deptId = Number(fromData.deptId[fromData.deptId.length - 1]);
    }

    const obj = {
      ...fromData,
      deptId,
    };
    const res = await A1_APIIgetList(obj);

    if (res.code === 0) {
      // 清空选中
      setSelectedRowKeys([]);
      setData(res.data);
    }
  }, [fromData]);

  useEffect(() => {
    getListFu();
  }, [getListFu]);

  const fromTime = useRef(-1);

  // 搜索项 的输入
  const searchKeyChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(fromTime.current);
      fromTime.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          searchKey: e.target.value,
        });
      }, 500);
    },
    [fromData]
  );

  // 获取 内控文件属性 下拉 数据（已过滤权限）

  const [iResList, setIResList] = useState<A2Tab2Type[]>([]);
  const getIresListFu = useCallback(async () => {
    const res = await A1_APIIgetIresList();
    if (res.code === 0) {
      setIResList(res.data);
    }
  }, []);

  useEffect(() => {
    getIresListFu();
  }, [getIresListFu]);

  // 从仓库获取部门 级联 信息
  const deptList = useSelector((state: RootState) => state.A5Section.tableList);

  // 表格信息
  const [data, setData] = useState<A1ItableType[]>([]);

  // 点击批量下载
  const downSelectFu = useCallback(async () => {
    const res = await A1_APIIdowns(selectedRowKeys.join(","));

    if (res.code === 0) {
      // console.log(123,res.data);
      urlChangeFu(res.data, true, undefined, projectName + "(内)");
      // 清空选中
      setSelectedRowKeys([]);
    }
  }, [projectName, selectedRowKeys]);

  // 删除的弹窗数据
  const [delInfo, setDelInfo] = useState({ id: 0, name: "" });

  // 权限
  const authArr = useSelector((state: RootState) => state.A4Role.A4RoleAll);

  // 关于 审核
  const adidtDom = useCallback(
    (item: A1ItableType) => {
      const num = item.auditStatus;

      const txt = num === 0 ? "待审批" : num === 1 ? "审批通过" : "审批驳回";

      const dom =
        item.auditDesc && num !== 0 ? (
          <Tooltip title={item.auditDesc}>
            <div
              className="iconHoverTit A1ItablauidtBox"
              onClick={() =>
                setAuditInfo({
                  id: item.id,
                  sta: num,
                  txt: item.auditDesc || "",
                })
              }
            >
              {txt}&nbsp;
              <div className="iconHoverTitTxt">?</div>
            </div>
          </Tooltip>
        ) : (
          <div
            className="A1ItablauidtBox"
            onClick={() =>
              setAuditInfo({ id: item.id, sta: num, txt: item.auditDesc || "" })
            }
          >
            {txt}
          </div>
        );

      if (authArr.includes("1104")) return dom;
      else return txt;
    },
    [authArr]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "所属阶段",
        dataIndex: "stageName",
      },
      {
        title: "文件类别",
        dataIndex: "attrName",
      },
      {
        title: "责任部门",
        dataIndex: "deptName",
      },
      {
        title: "文件名称",
        render: (item: A1ItableType) =>
          item.hasLack === 1 ? (
            <>
              {item.description === "-未填信息" ? (
                "无法提供"
              ) : (
                <Tooltip title={item.description}>
                  <div className="iconHoverTit">
                    无法提供&nbsp;
                    <div className="iconHoverTitTxt">?</div>
                  </div>
                </Tooltip>
              )}
            </>
          ) : (
            item.fileName
          ),
      },
      {
        title: "上传人",
        dataIndex: "uploadName",
      },
      {
        title: "上传时间",
        dataIndex: "updateTime",
      },
      {
        title: "审批状态",
        render: (item: A1ItableType) => adidtDom(item),
      },
      {
        title: "审核人",
        render: (item: A1ItableType) =>
          item.auditorName ? item.auditorName : "（空）",
      },
      {
        title: "审核时间",
        render: (item: A1ItableType) =>
          item.auditTime ? item.auditTime : "（空）",
      },
      {
        title: "操作",
        render: (item: A1ItableType) =>
          item.hasLack === 1 ? (
            "-"
          ) : (
            <>
              {authFilesLookFu(item.fileName) ? (
                <Button
                  size="small"
                  type="text"
                  onClick={() => authFilesLookFu(item.fileName, item.filePath)}
                >
                  查看
                </Button>
              ) : null}
              <AuthCom aId="1106">
                <Button
                  size="small"
                  type="text"
                  onClick={() =>
                    urlChangeFu(item.filePath, true, undefined, item.fileName)
                  }
                >
                  下载
                </Button>
              </AuthCom>

              <AuthCom aId="1107">
                <Button
                  size="small"
                  type="text"
                  danger
                  onClick={() =>
                    setDelInfo({ id: item.id, name: item.fileName })
                  }
                >
                  删除
                </Button>
              </AuthCom>
            </>
          ),
      },
    ];
  }, [adidtDom]);

  // 登记缺失文件的开启和关闭
  const [lack, setLack] = useState(false);

  // 审批状态的开启和关闭
  const [auditInfo, setAuditInfo] = useState<{
    id: number;
    sta: 0 | 1 | 2;
    txt: string;
  }>({
    id: 0,
    sta: 0,
    txt: "",
  });

  // 批量上传的弹窗
  const [upFileOpen, setUpFileOpen] = useState(false);

  return (
    <div className={styles.A1Inner}>
      <div className="A1Itop">
        <div className="A1ItopRow">
          <span>搜索项：</span>
          <Input
            maxLength={30}
            style={{ width: 210 }}
            placeholder="请输入文件名称，最多30字"
            allowClear
            onChange={(e) => searchKeyChange(e)}
          />
        </div>

        <div className="A1ItopRow">
          <span>文件类别：</span>
          <Select
            style={{ width: 120 }}
            value={fromData.attrId}
            onChange={(e) => setFromData({ ...fromData, attrId: e })}
            options={[
              { value: "", label: "全部" },
              ...iResList.map((v) => ({ value: v.id, label: v.name })),
            ]}
          />
        </div>

        <div className="A1ItopRow">
          <span>审批状态：</span>
          <Select
            style={{ width: 120 }}
            value={fromData.auditStatus}
            onChange={(e) => setFromData({ ...fromData, auditStatus: e })}
            options={[
              { value: "", label: "全部" },
              { value: 0, label: "待审批" },
              { value: 1, label: "审批通过" },
              { value: 2, label: "审批驳回" },
            ]}
          />
        </div>

        <div className="A1ItopRow">
          <span>责任部门：</span>
          <Cascader
            allowClear={false}
            style={{ width: 200 }}
            options={[{ id: "", name: "全部" }, ...deptList]}
            value={fromData.deptId}
            onChange={(e) => setFromData({ ...fromData, deptId: e })}
            fieldNames={{ label: "name", value: "id" }}
            placeholder="请选择"
          />
        </div>

        <div className="A1ItopRow A1ItopRow2">
          <AuthCom aId="1105">
            <Button type="primary" onClick={() => setLack(true)}>
              登记缺失文件
            </Button>
          </AuthCom>
          &emsp;
          <AuthCom aId="1103">
            <Button type="primary" onClick={() => setUpFileOpen(true)}>
              批量上传
            </Button>
          </AuthCom>
          &emsp;
          <AuthCom aId="1102">
            <Button
              type="primary"
              onClick={downSelectFu}
              disabled={selectedRowKeys.length <= 0}
            >
              批量下载
            </Button>
          </AuthCom>
        </div>
      </div>

      <div className="A1ItableBox">
        <Table
          rowSelection={{
            type: "checkbox",
            selectedRowKeys,
            onChange: (selectedRowKeys: React.Key[]) => {
              setSelectedRowKeys(selectedRowKeys);
            },
            // 禁用
            getCheckboxProps: (item) => ({
              disabled: item.hasLack === 1, // 配置无法勾选的列
            }),
          }}
          scroll={{ y: 610 }}
          dataSource={data}
          columns={columns}
          rowKey="id"
          pagination={false}
        />
      </div>

      {/* 点击删除出来的弹窗 */}
      {delInfo.id ? (
        <A1IRemove
          mId={delInfo.id}
          name={delInfo.name}
          colseFu={() => setDelInfo({ id: 0, name: "" })}
          delSuFu={() => getListFu()}
        />
      ) : null}

      {/* 点击登记缺失文件出来的弹窗 */}
      {lack ? (
        <A1ILack
          projectId={projectId}
          closeFu={() => setLack(false)}
          addSuFu={() => getListFu()}
        />
      ) : null}

      {/* 点击审批出来的弹窗 */}
      {auditInfo.id ? (
        <A1IAudit
          info={auditInfo}
          closeFu={() => setAuditInfo({ id: 0, sta: 0, txt: "" })}
          editSuFu={() => getListFu()}
        />
      ) : null}

      {upFileOpen ? (
        <A1IupFile
          myUrl={`${baseUpUrl}cms/inside/upload/${projectId}`}
          upFileFu={() => getListFu()}
          closeFu={() => setUpFileOpen(false)}
          myTitle={myTitle}
          projectId={projectId}
          typeData={iResList}
        />
      ) : null}
    </div>
  );
}

const MemoA1Inner = React.memo(A1Inner);

export default MemoA1Inner;
