import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import styles from "./index.module.scss";
import { Button, DatePicker, Input, Popconfirm, Table } from "antd";
import { useDispatch, useSelector } from "react-redux";
import {
  A7_APIdel,
  A7_APIgetList,
  A7_APIgetSizeAll,
  A7_APIrecover,
} from "@/store/action/A7Recycled";
import { RootState } from "@/store";
import { A7tableType } from "@/types";
import { MessageFu } from "@/utils/message";

const { RangePicker } = DatePicker;

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

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

  // 文件获取总内存

  const [sizeAll, setSizeAll] = useState("0");

  const getSizeAllFu = useCallback(async () => {
    const res = await A7_APIgetSizeAll();
    if (res.code === 0) {
      let num = "0";

      if (res.data && res.data.pcs) num = (res.data.pcs / 1024).toFixed(2);

      setSizeAll(num);
    }
  }, []);

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

  // 输入框的定时器
  const tableTime = useRef(-1);

  const getListFu = useCallback(() => {
    dispatch(A7_APIgetList(fromData));
  }, [dispatch, fromData]);

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

  // 输入框的输入
  const tabInputChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: "searchKey" | "userId") => {
      clearTimeout(tableTime.current);
      tableTime.current = window.setTimeout(() => {
        setFromData({
          ...fromData,
          [key]: e.target.value,
          pageNum: 1,
        });
      }, 500);
    },
    [fromData]
  );

  // 时间选择器改变
  const timeChange = (date: any, dateString: any) => {
    let startTime = "";
    let endTime = "";
    if (dateString[0] && dateString[1]) {
      startTime = dateString[0] + " 00:00:00";
      endTime = dateString[1] + " 23:59:59";
    }
    setFromData({ ...fromData, startTime, endTime, pageNum: 1 });
  };

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

  // 从仓库获取表格数据
  const tableData = useSelector(
    (state: RootState) => state.A7Recycled.tableInfo
  );

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

  // 点击删除
  const delById = useCallback(
    async (ids: string, flag: boolean) => {
      const res = await A7_APIdel(ids);

      if (res.code === 0) {
        MessageFu.success("删除成功!");
        getSizeAllFu();
        getListFu();
        if (flag) {
          // 清空选中
          setSelectedRowKeys([]);
        }
      }
    },
    [getListFu, getSizeAllFu]
  );

  // 点击恢复
  const restortFu = useCallback(
    async (ids: string, flag: boolean) => {
      const res = await A7_APIrecover(ids);

      if (res.code === 0) {
        MessageFu.success("恢复成功!");
        getSizeAllFu();
        getListFu();
        if (flag) {
          // 清空选中
          setSelectedRowKeys([]);
        }
      }
    },
    [getListFu, getSizeAllFu]
  );

  const columns = useMemo(() => {
    return [
      {
        title: "文件名称",
        dataIndex: "fileName",
      },
      {
        title: "删除人",
        dataIndex: "creatorName",
      },
      {
        title: "删除日期",
        dataIndex: "createTime",
      },
      {
        title: "删除原因",
        render: (item: A7tableType) =>
          item.description.length >= 30 ? (
            <span style={{ cursor: "pointer" }} title={item.description}>
              {item.description.substring(0, 30) + "..."}
            </span>
          ) : (
            item.description
          ),
      },
      {
        title: "文件大小（MB）",
        render: (item: A7tableType) =>
          (Number(item.fileSize) / 1024).toFixed(2),
      },
      {
        title: "操作",
        render: (item: A7tableType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => restortFu(item.id + "", false)}
            >
              恢复
            </Button>
            <Popconfirm
              title="此次为物理删除，无法找回。请谨慎操作"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delById(item.id + "", false)}
              okButtonProps={{ loading: false }}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delById, restortFu]);

  return (
    <div className={styles.A7Recycled}>
      <div className="pageTitle">
        回收站&emsp;<span>当前文件占用内存：{sizeAll} MB</span>
      </div>
      <div className="A7Top">
        <div className="A7TopRow">
          <span>文件名称：</span>
          <Input
            maxLength={30}
            style={{ width: 200 }}
            placeholder="请输入内容，最多30字"
            allowClear
            onChange={(e) => tabInputChangeFu(e, "searchKey")}
          />
        </div>

        <div className="A7TopRow">
          <span>删除人：</span>
          <Input
            maxLength={10}
            style={{ width: 200 }}
            placeholder="请输入内容，最多10字"
            allowClear
            onChange={(e) => tabInputChangeFu(e, "userId")}
          />
        </div>

        <div className="A7TopRow">
          <span>删除日期：</span>
          <RangePicker onChange={timeChange} />
        </div>

        <div className="A7TopBtn">
          <Button
            disabled={selectedRowKeys.length <= 0}
            type="primary"
            onClick={() => restortFu(selectedRowKeys.join(","), true)}
          >
            批量恢复
          </Button>
          &emsp;
          <Popconfirm
            disabled={selectedRowKeys.length <= 0}
            title="此次为物理删除，无法找回。请谨慎操作"
            okText="删除"
            cancelText="取消"
            onConfirm={() => delById(selectedRowKeys.join(","), true)}
            okButtonProps={{ loading: false }}
          >
            <Button
              type="primary"
              danger
              disabled={selectedRowKeys.length <= 0}
            >
              批量删除
            </Button>
          </Popconfirm>
        </div>
      </div>

      <div className="A7tableBox">
        <Table
          rowSelection={{
            type: "checkbox",
            selectedRowKeys,
            onChange: (selectedRowKeys: React.Key[]) => {
              setSelectedRowKeys(selectedRowKeys);
            },
          }}
          scroll={{ y: 620 }}
          dataSource={tableData.list}
          columns={columns}
          rowKey="id"
          pagination={{
            showQuickJumper: true,
            position: ["bottomCenter"],
            showSizeChanger: true,
            current: fromData.pageNum,
            pageSize: fromData.pageSize,
            total: tableData.total,
            onChange: paginationChange(),
          }}
        />
      </div>
    </div>
  );
}

const MemoA7Recycled = React.memo(A7Recycled);

export default MemoA7Recycled;
