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 { baseURL } from "@/utils/http";
import filesLookFu from "@/utils/filesLook";
import A1ORenFile from "./A1ORenFile";
import A1OMove from "./A1OMove";

export const leftTabArr:{
  id: number;
  type?: string;
  name: string;
}[] = [
  { id: 1, type: "文件夹", name: "重要文档-已盖章" },
  { id: 2, type: "文件夹", name: "重要文档-未盖章" },
  { id: 3, type: "文件夹", name: "其他过程文件" },
];

const towTableArr = [
  {
    id: 2,
    b: "第二级",
    fileName: "899845646.pdf",
    type: "文件",
  },
  {
    id: 22,
    b: "第二级2222",
    fileName: "899845646杀杀杀.pdf",
    type: "文件",
  },
];

type Props = {
  id: number;
};

function A1Outer({ id }: Props) {
  const [fromData, setFromData] = useState({
    id: 1,
    aaaa: "",
    pageNum: 1,
    pageSize: 10,
  });

  // 文件名的输入
  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 getListFu = useCallback(() => {
    console.log("tab2发送请求", fromData);

    // 清空选中
    setSelectedRowKeys([]);

    setTableInfo({
      list: [
        {
          id: 11,
          c: "2020-02-02 12:34:56",
          type: "文件夹",
          fileName: "一个文件夹",
          filePath: "xxx",
        },
        {
          id: 2,
          b: "阿三大苏打阿三大苏打",
          fileName: "899845646.pdf",
          type: "文件",
        },
      ],
      total: 200,
    });
  }, [fromData]);

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

  // 一级的高亮
  const [tab1, setTab1] = useState(leftTabArr[0]);

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

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

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

  // 点击表格里面的删除
  const delById = useCallback((id: number) => {
    console.log("---点击删除");
  }, []);

  // 点击表格里面的 文件夹 的下载
  const downFilesFu = useCallback((id: number) => {
    console.log("ssss,点击文件夹的下载");
  }, []);

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

        // 后面调试接口的时候 删掉
        setTimeout(() => {
          setTableInfo({ list: towTableArr, total: 200 });
        }, 200);
      }
    },
    [fromData]
  );

  // 表格数据
  const [tableInfo, setTableInfo] = useState({
    list: [
      {
        id: 11,
        c: "2020-02-02 12:34:56",
        type: "文件夹",
        fileName: "一个文件夹",
        filePath: "xxx",
      },
      {
        id: 2,
        b: "阿三大苏打阿三大苏打",
        fileName: "899845646.pdf",
        type: "文件",
      },
    ],
    total: 2,
  });

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

            {item.type === "文件夹" ? (
              <Button
                size="small"
                type="text"
                onClick={() => downFilesFu(item.id)}
              >
                下载
              </Button>
            ) : (
              <a
                href={baseURL + item.filePath}
                download={item.fileName}
                target="_blank"
                rel="noreferrer"
              >
                <Button size="small" type="text">
                  下载
                </Button>
              </a>
            )}

            <Button
              size="small"
              type="text"
              onClick={() =>
                setRenFile({
                  id: item.id,
                  fileName: item.fileName,
                  type: item.type,
                })
              }
            >
              重命名
            </Button>
            {item.type === "文件夹" ? null : (
              <Button
                size="small"
                type="text"
                onClick={() => setMoveId({ id: item.id, name: item.fileName })}
              >
                移动
              </Button>
            )}

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

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

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

  // 新建文件夹或者 重命名
  const [renFile, setRenFile] = useState({
    id: 0,
    fileName: "",
    type: "",
  });

  // 点击移动之后出来的数据
  const [moveId, setMoveId] = useState({ id: 0, 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) => aaaaChange(e)}
          />
          &emsp;&emsp;
          <span className="A1OnowLoc">
            <span>当前位置：{tab1.name}</span>
            {tab2.id ? <> / {tab2.name}</> : null}
          </span>
        </div>
        <div className="A1Otop2">
          {tab2.id ? null : (
            <>
              <Button
                type="primary"
                onClick={() =>
                  setRenFile({ id: -1, fileName: "", type: "文件夹" })
                }
              >
                新建文件夹
              </Button>
              &emsp;
            </>
          )}
          <Button type="primary" disabled={selectedRowKeys.length <= 0}>
            批量下载
          </Button>
          &emsp;
          <Button type="primary">批量上传</Button>&emsp;
        </div>
      </div>
      {/* 表格主体 */}
      <div className="A1OtableBox">
        <div className="A1OtableBox1">
          <div className="A1OtableBox1_1">目录</div>
          {leftTabArr.map((v) => (
            <div
              onClick={() => cutTab1Fu(v.id, v.name)}
              className={classNames(
                "A1OtableBox1_2",
                tab1.id === v.id ? "A1OtableBox1_2Ac" : ""
              )}
              key={v.id}
            >
              {v.name}
            </div>
          ))}
        </div>
        <div className="A1OtableBox2">
          <Table
            rowSelection={{
              type: "checkbox",
              selectedRowKeys,
              onChange: (selectedRowKeys: React.Key[]) => {
                console.log("选中的ids", selectedRowKeys);
                setSelectedRowKeys(selectedRowKeys);
              },
            }}
            scroll={{ y: 560 }}
            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>
      </div>
      {/* 点击 新建 文件夹 或者 重命名 */}
      {renFile.id ? (
        <A1ORenFile
          closeFu={() => setRenFile({ id: 0, fileName: "", type: "" })}
          fileInfo={renFile}
        />
      ) : null}

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

const MemoA1Outer = React.memo(A1Outer);

export default MemoA1Outer;
