import { Button, Popconfirm, Switch, Table, Tooltip } from "antd";
import React, {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";
import { ExclamationCircleFilled } from "@ant-design/icons";
import styles from "./index.module.scss";

// 表格拖动排序-----------------
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import { MessageFu } from "@/utils/message";
import { WallTableListType } from "@/types";
import { useDispatch, useSelector } from "react-redux";
import { RootState } from "@/store";
import {
  awllDisplayAPI,
  getWallTableListAPI,
  wallRemoveAPI,
  wallSortAPI,
} from "@/store/action/B3Wall";
import WallLook from "../WallLook";

type Props = {
  tablePageIdFu: (id: number, scrollNum: number) => void;
  scrollNumInfo: {
    txt: string;
    num: number;
  };
};

function WallTable({ tablePageIdFu, scrollNumInfo }: Props) {
  const dispatch = useDispatch();

  useEffect(() => {
    // 如果是编辑，或者是进新增/编辑页面点击了取消。控制表格滚动到之前的位置
    if (scrollNumInfo.txt === "取消" || scrollNumInfo.txt === "编辑") {
      if (scrollNumInfo.num > 0) {
        const dom: any = document.querySelector("#wallTable .ant-table-body");
        dom.scrollTop = scrollNumInfo.num;
      }
    }

    dispatch(getWallTableListAPI());
  }, [dispatch, scrollNumInfo]);

  // 从仓库中获取列表数据
  const results = useSelector((state: RootState) => state.wallReducer.list);

  const editTableFu = useCallback(
    (id: number) => {
      if (id === -1 && results.length >= 20)
        return MessageFu.warning("最多支持上传20个内容！");

      // 获取当前表格的滚动位置
      const dom: any = document.querySelector("#wallTable .ant-table-body");
      tablePageIdFu(id, dom.scrollTop);
    },
    [results.length, tablePageIdFu]
  );

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

  // 切换表格中的启用停用状态
  const isEnabledClickFu = useCallback(
    async (val: boolean, id: number) => {
      const isDisable = val ? 1 : 0;
      const res: any = await awllDisplayAPI(id, isDisable);
      if (res.code === 0) dispatch(getWallTableListAPI());
    },
    [dispatch]
  );

  const columns = useMemo(() => {
    return [
      // {
      //   width: 80,
      //   title: "序号",
      //   render: (text: any, record: any, index: any) => index + 1,
      // },

      {
        title: "海报名称",
        dataIndex: "name",
      },
      {
        title: "展示状态",
        render: (item: WallTableListType) => (
          <Switch
            checkedChildren="启用"
            unCheckedChildren="停用"
            checked={item.display === 1}
            onChange={(val) => isEnabledClickFu(val, item.id)}
          />
        ),
      },
      {
        title: "操作",
        render: (item: WallTableListType) => (
          <>
            <Button
              size="small"
              type="text"
              onClick={() => editTableFu(item.id)}
            >
              编辑
            </Button>
            <Button
              size="small"
              type="text"
              onClick={() => setLookImgId(item.id)}
            >
              预览
            </Button>
            <Popconfirm
              title="删除后无法恢复，是否删除?"
              okText="删除"
              cancelText="取消"
              onConfirm={() => delTableFu(item.id)}
            >
              <Button size="small" type="text" danger>
                删除
              </Button>
            </Popconfirm>
          </>
        ),
      },
    ];
  }, [delTableFu, editTableFu, isEnabledClickFu]);

  // 表格拖动排序-----------------
  interface DraggableBodyRowProps
    extends React.HTMLAttributes<HTMLTableRowElement> {
    index: number;
    moveRow: (dragIndex: number, hoverIndex: number) => void;
  }

  const type = "DraggableBodyRow";

  const DraggableBodyRow = useCallback(
    ({
      index,
      moveRow,
      className,
      style,
      ...restProps
    }: DraggableBodyRowProps) => {
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const ref = useRef<HTMLTableRowElement>(null);
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const [{ isOver, dropClassName }, drop] = useDrop({
        accept: type,
        collect: (monitor) => {
          const { index: dragIndex } = monitor.getItem() || {};
          if (dragIndex === index) {
            return {};
          }
          return {
            isOver: monitor.isOver(),
            dropClassName:
              dragIndex < index ? " drop-over-downward" : " drop-over-upward",
          };
        },
        drop: (item: { index: number }) => {
          moveRow(item.index, index);
        },
      });
      // eslint-disable-next-line react-hooks/rules-of-hooks
      const [, drag] = useDrag({
        type,
        item: { index },
        collect: (monitor) => ({
          isDragging: monitor.isDragging(),
        }),
      });
      drop(drag(ref));

      return (
        <tr
          ref={ref}
          className={`${className}${isOver ? dropClassName : ""}`}
          style={{ cursor: "move", ...style }}
          {...restProps}
        />
      );
    },
    []
  );

  const components = {
    body: {
      row: DraggableBodyRow,
    },
  };

  const moveRow = useCallback(
    async (dragIndex: number, hoverIndex: number) => {
      if (dragIndex === hoverIndex) return;
      // 交互位置-之前的id
      const beforeId = results[dragIndex].id;
      const afterId = results[hoverIndex].id;

      const res = await wallSortAPI(beforeId, afterId);

      if (res.code === 0) dispatch(getWallTableListAPI());
    },
    [dispatch, results]
  );

  // 点击预览
  const [lookImgId, setLookImgId] = useState(0);

  return (
    <div className={styles.WallTable}>
      <div className="titleTxt">
        临时展海报管理
        <Tooltip title="按住鼠标可拖动表格调整顺序">
          <div className="inco" hidden={results.length < 2}>
            <ExclamationCircleFilled />
          </div>
        </Tooltip>
        <div className="tableBtn">
          <Button type="primary" onClick={() => editTableFu(-1)}>
            新增海报
          </Button>
        </div>
      </div>

      {/* 表格主体 */}
      <div className="table">
        <DndProvider backend={HTML5Backend}>
          <Table
            id="wallTable"
            scroll={{ y: 560 }}
            columns={columns}
            dataSource={results}
            components={components}
            rowKey="id"
            pagination={false}
            onRow={(_, index) => {
              const attr = {
                index,
                moveRow,
              };
              return attr as React.HTMLAttributes<any>;
            }}
          />
        </DndProvider>
      </div>

      {/* 点击预览打开的盒子 */}
      {lookImgId ? (
        <WallLook closeMoalFu={() => setLookImgId(0)} id={lookImgId} />
      ) : null}
    </div>
  );
}

const MemoWallTable = React.memo(WallTable);

export default MemoWallTable;
