import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, Input, Popconfirm, Table } from "antd";
import classNames from "classnames";
import { baseUpUrl } from "@/utils/http";
import A1ORenFile from "./A1ORenFile";
import A1OMove from "./A1OMove";
import { A1OFileType } from "@/types";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import {
  A1_APIOgetList,
  A1_APIOdel,
  A1_APIOdownload,
} from "@/store/action/A1Project";
import { MessageFu } from "@/utils/message";
import A1OupFile from "./A1OupFile";
import { authFilesLookFu, urlChangeFu } from "@/utils/authFilesLook";
import AuthCom from "@/components/AuthCom";

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

function A1Outer({ projectId, projectName }: Props) {
  const dispatch = useDispatch();

  // 从仓库获取左侧写死列表 和 展示列表
  const { A1OleftArr, A1OtableInfo } = useSelector(
    (state: RootState) => state.A1Project
  );

  const [fromData, setFromData] = useState({
    parentId: 1,
    searchKey: "",
    pageNum: 1,
    pageSize: 10,
  });

  // 文件名的输入
  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 getListFu = useCallback(() => {
    dispatch(A1_APIOgetList({ ...fromData, projectId }));
    // 清空选中
    setSelectedRowKeys([]);
  }, [dispatch, fromData, projectId]);

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

  // 一级的高亮
  const [tab1, setTab1] = useState({} as A1OFileType);

  useEffect(() => {
    setTab1(A1OleftArr[0]);
  }, [A1OleftArr]);

  // 二级的选择
  const [tab2, setTab2] = useState({ id: 0, name: "" });

  // 一级的切换
  const cutTab1Fu = useCallback(
    (id: number, name: string) => {
      setTab2({ id: 0, name: "" });
      setTab1({ id, name } as A1OFileType);

      if (id !== fromData.parentId)
        setFromData({ ...fromData, parentId: id, pageNum: 1 });
    },
    [fromData]
  );

  // 点击表格里面的 文件夹 进入 2级
  const toTowFilesFu = useCallback(
    (id: number, type: 0 | 1, name: string) => {
      if (type === 1) {
        setTab2({ id, name });
        setFromData({ ...fromData, parentId: id, pageNum: 1 });
      }
    },
    [fromData]
  );

  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      setFromData({ ...fromData, pageNum, pageSize });
    },
    [fromData]
  );

  // 关于表格的多选
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

  // 新建文件夹或者 重命名
  const [renFile, setRenFile] = useState({} as A1OFileType);

  // 点击移动之后出来的数据
  const [moveId, setMoveId] = useState({ id: 0, name: "" });

  // 点击表格里面的删除
  const delById = useCallback(
    async (id: number) => {
      const res = await A1_APIOdel(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getListFu();
      }
    },
    [getListFu]
  );

  // 点击表格里面的 文件夹 的下载
  const downFilesFu = useCallback(async (id: number, name: string) => {
    const res = await A1_APIOdownload(id);
    if (res.code === 0) {
      urlChangeFu(res.data, true, undefined, name);
    }
  }, []);

  // 点击批量下载
  const downSelectFu = useCallback(async () => {
    const res = await A1_APIOdownload(selectedRowKeys.join(","));
    if (res.code === 0) {
      urlChangeFu(res.data, true, undefined, projectName);
      // 清空选中
      setSelectedRowKeys([]);
    }
  }, [projectName, selectedRowKeys]);

  // 点击-批量上传
  const [upFileId, setUpFileId] = useState(0);

  const columns = useMemo(() => {
    return [
      {
        title: "文件名",
        render: (item: A1OFileType) =>
          item.name.length >= 30 ? (
            <span style={{ cursor: "pointer" }} title={item.name}>
              <span
                onClick={() => toTowFilesFu(item.id, item.type, item.name)}
                className={classNames(item.type === 1 ? "A1OfilesTable" : "")}
              >
                {item.name.substring(0, 30) + "..."}
              </span>
            </span>
          ) : (
            <span
              onClick={() => toTowFilesFu(item.id, item.type, item.name)}
              className={classNames(item.type === 1 ? "A1OfilesTable" : "")}
            >
              {item.name}
            </span>
          ),
      },
      {
        title: "创建用户",
        dataIndex: "creatorName",
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
      },
      {
        title: "操作",
        render: (item: A1OFileType) => (
          <>
            {authFilesLookFu(item.name,'') ? (
              <Button
                size="small"
                type="text"
                onClick={() => authFilesLookFu(item.name, item.filePath)}
              >
                查看
              </Button>
            ) : null}

            {item.type === 1 ? (
              <AuthCom aId="1094">
                <Button
                  size="small"
                  type="text"
                  onClick={() => downFilesFu(item.id, item.name)}
                >
                  下载
                </Button>
              </AuthCom>
            ) : (
              <AuthCom aId="1094">
                <Button
                  size="small"
                  type="text"
                  onClick={() =>
                    urlChangeFu(item.filePath, true, undefined, item.name)
                  }
                >
                  下载
                </Button>
              </AuthCom>
            )}

            <Button size="small" type="text" onClick={() => setRenFile(item)}>
              重命名
            </Button>
            {item.type === 1 ? null : (
              <AuthCom aId="1095">
                <Button
                  size="small"
                  type="text"
                  onClick={() => setMoveId({ id: item.id, name: item.name })}
                >
                  移动
                </Button>
              </AuthCom>
            )}

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

  // 当前位置
  const nowLoc = useMemo(() => {
    return {
      tag: (
        <>
          <span
            className="A1OnowLocRow"
            onClick={() => cutTab1Fu(tab1.id, tab1.name)}
          >
            {tab1.name}
          </span>
          {tab2.id ? <span> / {tab2.name}</span> : null}
        </>
      ),
      txt: tab1.name + (tab2.id ? ` / ${tab2.name}` : ""),
    };
  }, [cutTab1Fu, tab1.id, tab1.name, tab2.id, tab2.name]);

  return (
    <div className={styles.A1Outer}>
      <div className="A1Otop">
        <div className="A1Otop1">
          <span>文件名：</span>
          <Input
            maxLength={30}
            style={{ width: 300 }}
            placeholder="请输入文件名称，最多30字"
            allowClear
            onChange={(e) => searchKeyChange(e)}
          />
          &emsp;&emsp;
          <span className="A1OnowLoc">当前位置：{nowLoc.tag}</span>
        </div>
        <div className="A1Otop2">
          {tab2.id ? null : (
            <>
              <AuthCom aId="1092">
                <Button
                  type="primary"
                  onClick={() =>
                    setRenFile({
                      id: -1,
                      name: "",
                      type: 1,
                      parentId: tab1.id,
                    } as A1OFileType)
                  }
                >
                  新建文件夹
                </Button>
                &emsp;
              </AuthCom>
            </>
          )}
          <AuthCom aId="1093">
            <Button
              type="primary"
              onClick={downSelectFu}
              disabled={selectedRowKeys.length <= 0}
            >
              批量下载
            </Button>
          </AuthCom>
          &emsp;
          <AuthCom aId="1091">
            <Button
              type="primary"
              onClick={() => setUpFileId(tab2.id ? tab2.id : tab1.id)}
            >
              批量上传
            </Button>
          </AuthCom>
          &emsp;
        </div>
      </div>
      {/* 表格主体 */}
      <div className="A1OtableBox">
        <div className="A1OtableBox1">
          <div className="A1OtableBox1_1">目录</div>
          {A1OleftArr.map((v) => {
            // 子标题用 , 隔开
            const temp = v.name.split(',')

            return (
              <div
                onClick={() => cutTab1Fu(v.id, temp[0])}
                className={classNames(
                  "A1OtableBox1_2",
                  tab1.id === v.id ? "A1OtableBox1_2Ac" : ""
                )}
                key={v.id}
              >
                <p>{temp[0]}</p>

                {temp[1] && (
                  <span style={{
                    textAlign: 'center'
                  }}>{temp[1]}</span>
                )}
              </div>
            )
          })}
        </div>
        <div className="A1OtableBox2">
          <Table
            rowSelection={{
              type: "checkbox",
              selectedRowKeys,
              onChange: (selectedRowKeys: React.Key[]) => {
                setSelectedRowKeys(selectedRowKeys);
              },
            }}
            scroll={{ y: 560 }}
            dataSource={A1OtableInfo.list}
            columns={columns}
            rowKey="id"
            pagination={{
              showQuickJumper: true,
              position: ["bottomCenter"],
              showSizeChanger: true,
              current: fromData.pageNum,
              pageSize: fromData.pageSize,
              total: A1OtableInfo.total,
              onChange: paginationChange(),
            }}
          />
        </div>
      </div>
      {/* 点击 新建 文件夹 或者 重命名 */}
      {renFile.id ? (
        <A1ORenFile
          addFu={() => setFromData({ ...fromData, searchKey: "", pageNum: 1 })}
          editFu={() => getListFu()}
          closeFu={() =>
            setRenFile({ id: 0, name: "", type: 0 } as A1OFileType)
          }
          fileInfo={renFile}
          projectId={projectId}
        />
      ) : null}

      {/* 点击移动 */}
      {moveId.id ? (
        <A1OMove
          mId={moveId}
          id1={tab1}
          id2={tab2}
          closeFu={() => setMoveId({ id: 0, name: "" })}
          projectId={projectId}
          moveSuFu={() => getListFu()}
        />
      ) : null}

      {/* 点击批量上传 */}
      {upFileId ? (
        <A1OupFile
          myUrl={baseUpUrl + "cms/item/upload"}
          fromData={{ parentId: upFileId, projectId }}
          nowLoc={nowLoc.txt}
          closeFu={() => setUpFileId(0)}
          upFileFu={() => getListFu()}
        />
      ) : null}
    </div>
  );
}

const MemoA1Outer = React.memo(A1Outer);

export default MemoA1Outer;
