import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Select, Table, Tooltip } from "antd";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import { A1TableType } from "@/types";
import A1Add from "./A1Add";
import A1Down from "./A1Down";
import A1Look from "./A1Look";
import { A1_APIgetList, A1_APIdelProject } from "@/store/action/A1Project";
import { getUserListAPI } from "@/store/action/A3User";
import { A2_APIgetList1 } from "@/store/action/A2Dict";
import { hasAuditStatusArr } from "./data";
import { MessageFu } from "@/utils/message";
import AuthCom from "@/components/AuthCom";

function A1Project() {
  const dispatch = useDispatch();

  useEffect(() => {
    // 获取用户列表（项目管理下拉筛选使用）
    dispatch(getUserListAPI({ pageNum: 1, pageSize: 99999 }));
    // 获取 字典 的 职能（项目详情的项目成员用）  和 状态（这个页面用）
    dispatch(A2_APIgetList1());
  }, [dispatch]);

  // 从仓库获取用户列表--项目经理下拉框 和 商务经理下拉框使用
  const A3UserList = useSelector(
    (state: RootState) => state.A3User.tableInfo.list
  );

  const pmUserIdArr = useMemo(() => {
    const arr1 = A3UserList.filter((v) => v.userName !== "admin");
    const arr2: { value: number; label: string }[] = arr1.map((v) => ({
      value: v.id,
      label: v.userName + " - " + v.realName,
    }));
    return arr2;
  }, [A3UserList]);

  // 从仓库 获取 项目状态的下拉框 数据
  const statusArr = useSelector(
    (state: RootState) => state.A2Dict.A2Tab1_1Obj.status
  );

  // 顶部的试图切换
  const [topType, setTopType] = useState<"outer" | "inner">("outer");

  // 表单数据
  const [fromData, setFromData] = useState({
    searchKey: "",
    pmUserId: "",
    bmUserId: "",
    statusId: "",
    hasAuditStatus: "",
    projectRole: "",
    pageNum: 1,
    pageSize: 10,
    type: "inside",
  });

  // 封装发送请求的函数
  const A1getListFu = useCallback(() => {
    dispatch(A1_APIgetList(fromData));
  }, [dispatch, fromData]);

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

  // 项目编号/项目名称/建设单位 的 输入
  const searchKeyTime = useRef(-1);
  const searchKeyChange = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>) => {
      clearTimeout(searchKeyTime.current);
      searchKeyTime.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          searchKey: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [fromData]
  );

  // 项目经理 下拉 搜索 的 改变
  const pmUserIdChange = useCallback(
    (value: string) => {
      const val = value ? value : "";
      setFromData({
        ...fromData,
        pmUserId: val,
        pageNum: 1,
      });
    },
    [fromData]
  );

  // 商务经理 下拉 搜索 的 改变
  const bmUserIdChange = useCallback(
    (value: string) => {
      const val = value ? value : "";
      setFromData({
        ...fromData,
        bmUserId: val,
        pageNum: 1,
      });
    },
    [fromData]
  );

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setFromData({
      searchKey: "",
      pmUserId: "",
      bmUserId: "",
      statusId: "",
      hasAuditStatus: "",
      projectRole: "",
      pageNum: 1,
      pageSize: 10,
      type: "inside",
    });
  }, []);

  // 点击顶部的切换视图 按钮
  const topTypeFu = useCallback(
    (val: "outer" | "inner") => {
      if (topType === val) return;
      setTopType(val);
      resetSelectFu();
    },
    [resetSelectFu, topType]
  );

  // 权限-------项目视图 和 内控文件视图
  const authArr = useSelector((state: RootState) => state.A4Role.A4RoleAll);

  useEffect(() => {
    // 没有项目文件视图权限，一定有内控文件视图权限
    if (!authArr.includes("1010")) setTopType("inner");
  }, [authArr]);

  // 从仓库获取表格数据
  const tableInfo = useSelector(
    (state: RootState) => state.A1Project.tableInfo
  );
  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setFromData({ ...fromData, pageNum, pageSize });
    },
    [fromData]
  );

  // 点击删除
  const delById = useCallback(
    async (id: number) => {
      const res = await A1_APIdelProject(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        A1getListFu();
      }
    },
    [A1getListFu]
  );

  // 点击下载
  const [downId, setDownId] = useState({ id: 0, txt: "" });

  // 点击审批
  const lookTabType = useRef(false);

  // 待审批，通过，驳回 的 格式处理
  const pcsTxt = useCallback((s1: string, s2: string, s3: string) => {
    const ss1 = s1 ? s1 : "0";
    const ss2 = s2 ? `/${s2}` : "/0";
    const ss3 = s3 ? `/${s3}` : "/0";
    return ss1 + ss2 + ss3;
  }, []);

  const columns = useMemo(() => {
    const arr: any = [
      {
        title: "项目编号",
        dataIndex: "num",
      },
      {
        title: "项目名称",
        dataIndex: "name",
      },
      {
        title: "建设单位",
        render: (item: A1TableType) => (item.unit ? item.unit : "（空）"),
      },
      {
        title: "项目地点",
        render: (item: A1TableType) =>
          item.province ? item.province : "（空）",
      },
      {
        title: "项目周期",
        render: (item: A1TableType) =>
          item.dateScope ? item.dateScope : "（空）",
      },
      {
        title: "项目经理",
        render: (item: A1TableType) =>
          item.snapPmUser ? item.snapPmUser : "（空）",
      },
      {
        title: "商务经理",
        render: (item: A1TableType) =>
          item.snapBmUser ? item.snapBmUser : "（空）",
      },
      {
        title: "项目状态",
        render: (item: A1TableType) =>
          item.statusName ? item.statusName : "（空）",
      },
    ];

    if (topType === "inner") {
      arr.push(
        {
          title: "收集文件类型",
          render: (item: A1TableType) =>
            item.pcsCollect ? item.pcsCollect : "（空）",
        },
        {
          width: 164,
          title: (
            <Tooltip title="该项目内控文件的审批状态和数量">
              <div className="iconHoverTit">
                待审批/通过/驳回&nbsp;
                <div className="iconHoverTitTxt">?</div>
              </div>
            </Tooltip>
          ),
          render: (item: A1TableType) =>
            pcsTxt(item.pcs0, item.pcs1, item.pcs2),
        }
      );
    }

    arr.push({
      title: "存在待审批文件",
      render: (item: A1TableType) => (item.hasAuditStatus ? "是" : "否"),
    });

    arr.push({
      title: "最近编辑时间",
      dataIndex: "updateTime",
    });

    arr.push({
      title: "操作",
      render: (item: A1TableType) => (
        <>
          <Button
            size="small"
            type="text"
            onClick={() => {
              lookTabType.current = false;
              setPageType({
                txt: "look",
                id: item.id,
                tit: item.num + " - " + item.name,
              });
            }}
          >
            查看
          </Button>
          {topType === "inner" ? (
            <>
              <AuthCom aId="1104">
                <Button
                  hidden={!authArr.includes("1101")}
                  size="small"
                  type="text"
                  onClick={() => {
                    lookTabType.current = true;
                    setPageType({
                      txt: "look",
                      id: item.id,
                      tit: item.num + " - " + item.name,
                    });
                  }}
                >
                  审批
                </Button>
              </AuthCom>

              <AuthCom aId="1050">
                <Button
                  size="small"
                  type="text"
                  onClick={() =>
                    setDownId({
                      id: item.id,
                      txt: item.num + " - " + item.name,
                    })
                  }
                >
                  下载内控文件
                </Button>
              </AuthCom>
            </>
          ) : null}

          <AuthCom aId="1060">
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delById(item.id)}
              okButtonProps={{ loading: false }}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </AuthCom>
        </>
      ),
    });

    return arr;
  }, [authArr, delById, pcsTxt, topType]);

  // 新增和查看
  const [pageType, setPageType] = useState<{
    txt: string;
    id: number;
    tit?: string;
  }>({ txt: "", id: 0 });

  // 是否只有 项目文件视图 / 内控文件视图的 其中一个
  const isOneTopType = useMemo(() => {
    if (authArr.includes("1010") && authArr.includes("1020")) return false;
    else return true;
  }, [authArr]);

  return (
    <div className={styles.A1Project}>
      <div className="pageTitle">
        项目管理
        {pageType.txt === "add"
          ? " > 新增项目"
          : pageType.txt === "look"
          ? " > 查看项目"
          : null}
      </div>

      {/* 顶部筛选 */}
      <div className="A1top">
        <div className="A1Search">
          {/* 顶部试图切换 */}
          <div className="A1SearchRow" hidden={isOneTopType}>
            <AuthCom aId="1010">
              <Button
                onClick={() => topTypeFu("outer")}
                type={topType === "outer" ? "primary" : "default"}
              >
                项目文件视图
              </Button>
            </AuthCom>

            <AuthCom aId="1020">
              <Button
                onClick={() => topTypeFu("inner")}
                type={topType === "inner" ? "primary" : "default"}
              >
                内控文件视图
              </Button>
            </AuthCom>
          </div>

          <div className="A1SearchRow">
            <span>项目编号/项目名称/建设单位：</span>
            <Input
              key={inputKey}
              maxLength={20}
              style={{ width: 200 }}
              placeholder="请输入内容，最多20字"
              allowClear
              onChange={(e) => searchKeyChange(e)}
            />
          </div>

          <div className="A1SearchRow">
            <span>项目经理：</span>
            <Select
              key={inputKey}
              style={{ width: 200 }}
              showSearch
              allowClear
              placeholder="请选择或输入内容搜索"
              optionFilterProp="children"
              onChange={pmUserIdChange}
              filterOption={(input, option) =>
                (option?.label ?? "")
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
              options={pmUserIdArr}
            />
          </div>

          <div className="A1SearchRow">
            <span>商务经理：</span>
            <Select
              key={inputKey}
              style={{ width: 200 }}
              showSearch
              allowClear
              placeholder="请选择或输入内容搜索"
              optionFilterProp="children"
              onChange={bmUserIdChange}
              filterOption={(input, option) =>
                (option?.label ?? "")
                  .toLowerCase()
                  .includes(input.toLowerCase())
              }
              options={pmUserIdArr}
            />
          </div>
        </div>
        <div className="A1Search A1Search2">
          <div className="A1SearchRow">
            <span>项目状态：</span>
            <Select
              style={{ width: 164 }}
              value={fromData.statusId}
              onChange={(e) =>
                setFromData({ ...fromData, statusId: e, pageNum: 1 })
              }
              options={[
                { value: "", label: "全部" },
                ...statusArr.map((v) => ({ value: v.id, label: v.name })),
              ]}
            />
          </div>

          {/* 通过顶部状态 动态渲染 这3个下拉框 */}
          {topType === "outer" ? null : (
            <>
              <div className="A1SearchRow">
                <span>是否存在待审批文件：</span>
                <Select
                  style={{ width: 164 }}
                  value={fromData.hasAuditStatus}
                  onChange={(e) =>
                    setFromData({ ...fromData, hasAuditStatus: e, pageNum: 1 })
                  }
                  options={hasAuditStatusArr}
                />
              </div>
            </>
          )}

          <div className="A1SearchRow A1SearchBtn">
            <AuthCom aId="1030">
              <Button
                type="primary"
                onClick={() => setPageType({ txt: "add", id: 0 })}
              >
                新增项目
              </Button>
            </AuthCom>
            &emsp;&emsp;
            <Button onClick={resetSelectFu}>重置</Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="A1tableBox">
        <Table
          scroll={{ y: 550 }}
          dataSource={tableInfo.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: fromData.pageNum,
            pageSize: fromData.pageSize,
            total: tableInfo.total,
            onChange: paginationChange(),
          }}
        />
      </div>
      {/* 新增、查看 */}
      {pageType.txt === "add" ? (
        <A1Add
          pageType={pageType}
          closeFu={() => setPageType({ txt: "", id: 0 })}
          addFu={() => resetSelectFu()}
          editFu={() => A1getListFu()}
        />
      ) : pageType.txt === "look" ? (
        <A1Look
          pageType={pageType}
          closeFu={() => {
            setPageType({ txt: "", id: 0 });
            // 从查看页面返回的时候更新列表数据
            A1getListFu();
          }}
          tabType={lookTabType.current}
          lookTit={pageType.tit!}
        />
      ) : null}

      {/* 下载 */}
      {downId.id ? (
        <A1Down downId={downId} closeFu={() => setDownId({ id: 0, txt: "" })} />
      ) : null}
    </div>
  );
}

const MemoA1Project = React.memo(A1Project);

export default MemoA1Project;
