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 { useSelector } from "react-redux";
import { RootState } from "@/store";
import { A1TableType } from "@/types";
import A1Add from "./A1Add";
import A1Down from "./A1Down";
import A1Look from "./A1Look";

const bbbbArr = [
  {
    value: "1111s",
    label: "shaogen - 邵根",
  },
  {
    value: "2222s",
    label: "wuweihao - 吴伟浩",
  },
];

const ccccArr = [
  {
    value: "ccc1111s",
    label: "shaogen - 邵根",
  },
  {
    value: "ccc2222s",
    label: "wuweihao - 吴伟浩",
  },
];

const ddddArr = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "项目状态1",
    label: "项目状态1",
  },
  {
    value: "项目状态2",
    label: "项目状态2",
  },
];

const eeeeArr = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "已完成",
    label: "已完成",
  },
  {
    value: "未完成",
    label: "未完成",
  },
];

const ffffArr = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "存在待审批的文件",
    label: "存在待审批的文件",
  },
  {
    value: "存在审批通过的文件",
    label: "存在审批通过的文件",
  },
  {
    value: "存在审批驳回的文件",
    label: "存在审批驳回的文件",
  },
];

const ggggArr = [
  {
    value: "",
    label: "全部",
  },
  {
    value: "我创建的项目",
    label: "我创建的项目",
  },
  {
    value: "我参与的项目",
    label: "我参与的项目",
  },
];

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

  // 表单数据
  const [fromData, setFromData] = useState({
    aaaa: "",
    bbbb: "",
    cccc: "",
    dddd: "",
    eeee: "",
    ffff: "",
    gggg: "",
    pageNum: 1,
    pageSize: 10,
  });

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

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

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

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

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

  // 点击重置
  const [inputKey, setInputKey] = useState(1);
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setInputKey(Date.now());
    setFromData({
      aaaa: "",
      bbbb: "",
      cccc: "",
      dddd: "",
      eeee: "",
      ffff: "",
      gggg: "",
      pageNum: 1,
      pageSize: 10,
    });
  }, []);

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

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

  // 点击删除
  const delById = useCallback((id: number) => {}, []);

  // 点击下载
  const [downId, setDownId] = useState(0);

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

  const columns = useMemo(() => {
    const arr: any = [
      {
        title: "项目编号",
        dataIndex: "a",
      },
      {
        title: "项目名称",
        dataIndex: "a",
      },
      {
        title: "建设单位",
        dataIndex: "a",
      },
      {
        title: "项目地点",
        dataIndex: "a",
      },
      {
        title: "项目周期",
        dataIndex: "a",
      },
      {
        title: "项目经理",
        dataIndex: "a",
      },
      {
        title: "商务经理",
        dataIndex: "a",
      },
      {
        title: "项目状态",
        dataIndex: "a",
      },
      {
        title: "最近编辑时间",
        dataIndex: "a",
      },
    ];

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

    arr.push({
      title: "操作",
      render: (item: A1TableType) => (
        <>
          <Button
            size="small"
            type="text"
            onClick={() => {
              lookTabType.current = false;
              setPageType({ txt: "look", id: item.id });
            }}
          >
            查看
          </Button>
          {topType === "inner" ? (
            <Button
              size="small"
              type="text"
              onClick={() => {
                lookTabType.current = true;
                setPageType({ txt: "look", id: item.id });
              }}
            >
              审批
            </Button>
          ) : null}

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

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

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

  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">
            <Button
              onClick={() => topTypeFu("outer")}
              type={topType === "outer" ? "primary" : "default"}
            >
              项目文件视图
            </Button>
            <Button
              onClick={() => topTypeFu("inner")}
              type={topType === "inner" ? "primary" : "default"}
            >
              内控文件视图
            </Button>
          </div>

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

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

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

          {/* 通过顶部状态 动态渲染 这3个下拉框 */}
          {topType === "outer" ? null : (
            <>
              <div className="A1SearchRow">
                <span>收集进度：</span>
                <Select
                  style={{ width: 164 }}
                  value={fromData.eeee}
                  onChange={(e) =>
                    setFromData({ ...fromData, eeee: e, pageNum: 1 })
                  }
                  options={eeeeArr}
                />
              </div>

              <div className="A1SearchRow">
                <span>审批进度：</span>
                <Select
                  style={{ width: 164 }}
                  value={fromData.ffff}
                  onChange={(e) =>
                    setFromData({ ...fromData, ffff: e, pageNum: 1 })
                  }
                  options={ffffArr}
                />
              </div>

              <div className="A1SearchRow">
                <span>项目角色：</span>
                <Select
                  style={{ width: 164 }}
                  value={fromData.gggg}
                  onChange={(e) =>
                    setFromData({ ...fromData, gggg: e, pageNum: 1 })
                  }
                  options={ggggArr}
                />
              </div>
            </>
          )}

          <div className="A1SearchRow A1SearchBtn">
            <Button
              type="primary"
              onClick={() => setPageType({ txt: "add", id: 0 })}
            >
              新增项目
            </Button>
            &emsp;&emsp;
            <Button onClick={resetSelectFu}>重置</Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className="A1tableBox">
        <Table
          scroll={{ y: 575 }}
          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 })}
          tabType={lookTabType.current}
        />
      ) : null}

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

const MemoA1Project = React.memo(A1Project);

export default MemoA1Project;
