import React, { useCallback, useMemo } from "react";
import { Button, Empty, Popconfirm, Table } from "antd";
import { useSelector } from "react-redux";
import { RootState } from "@/store";
import { A2_APIdel, A2_APIsort } from "@/store/action/A2Dict";
import { MessageFu } from "@/utils/message";
import { A5TableType } from "@/types";
import { A5_APIdel, A5_APIsort } from "@/store/action/A5Section";

type Props = {
  editFu: (item: A5TableType) => void;
  upTaleFu: () => void;
  myType: "字典" | "部门";
};

function A2Table3({ editFu, upTaleFu, myType }: Props) {
  // 获取表格数据
  const arr1 = useSelector((state: RootState) => state.A2Dict.A2Tab1_2Arr);
  const arr2 = useSelector((state: RootState) => state.A5Section.tableList);
  const tableList = useMemo(() => {
    if (myType === "字典") return arr1;
    else return arr2;
  }, [arr1, arr2, myType]);

  // 树型数组扁平化
  const arrAllArr = useMemo(() => {
    const arr: A5TableType[] = [...tableList];
    const arr1: A5TableType[] = [];
    arr.forEach((v) => {
      arr1.push(v);
      if (v.children && v.children.length) {
        v.children.forEach((v2) => {
          arr1.push(v2);
          if (v2.children && v2.children.length) {
            v2.children.forEach((v3) => {
              arr1.push(v3);
              if (v3.children && v3.children.length) {
                v3.children.forEach((v4) => {
                  arr1.push(v4);
                });
              }
            });
          }
        });
      }
    });
    return arr1;
  }, [tableList]);

  // 拿到当前点击 级别的 数组
  const sonArrFu = useCallback(
    (fId: string) => {
      const arr: A5TableType[] = arrAllArr.filter(
        (v) => v.parentId === fId && v.name !== "其它"
      );
      return arr;
    },
    [arrAllArr]
  );

  // 点击删除
  const delById = useCallback(
    async (id: string) => {
      const res = myType === "字典" ? await A2_APIdel(id) : await A5_APIdel(id);
      if (res.code === 0) {
        MessageFu.success("删除成功!");
        upTaleFu();
      }
    },
    [myType, upTaleFu]
  );

  // 点击 上移 和下移
  const sortMoveFu = useCallback(
    async (flag: 1 | -1, index: number, oldId: string, fId: string) => {
      const arr = sonArrFu(fId);
      const newId = arr[index + flag].id;

      const res =
        myType === "字典"
          ? await A2_APIsort(oldId, newId)
          : await A5_APIsort(oldId, newId);

      if (res.code === 0) {
        upTaleFu();
        MessageFu.success("排序修改成功!");
      }
    },
    [sonArrFu, myType, upTaleFu]
  );

  const columns = useMemo(() => {
    return [
      {
        title: <>&emsp;&nbsp;{myType === "字典" ? "字典名称" : "部门名称"}</>,
        dataIndex: "name",
      },
      {
        title: "说明",
        render: (item: A5TableType) =>
          item.description ? (
            item.description.length >= 30 ? (
              <span style={{ cursor: "pointer" }} title={item.description}>
                {item.description.substring(0, 30) + "..."}
              </span>
            ) : (
              item.description
            )
          ) : (
            "（空）"
          ),
      },
      {
        title: "同级排序",
        render: (item: A5TableType, _: any, index: number) =>
          item.name === "其它" ? "-" : item.level + "级 - " + (index + 1),
      },
      {
        title: "操作",
        render: (item: A5TableType, _: any, index: number) => (
          <>
            {item.level < 4 && item.name !== "其它" ? (
              <Button
                size="small"
                type="text"
                onClick={() =>
                  editFu({
                    id: "-1",
                    parentId: item.id,
                    name: item.name,
                    level: item.level + 1,
                  } as A5TableType)
                }
              >
                {myType === "字典" ? "新增子阶段" : "新增子部门"}
              </Button>
            ) : null}

            <Button size="small" type="text" onClick={() => editFu(item)}>
              编辑
            </Button>
            {index !== 0 && item.name !== "其它" ? (
              <Button
                size="small"
                type="text"
                onClick={() => sortMoveFu(-1, index, item.id, item.parentId)}
              >
                上移
              </Button>
            ) : null}

            {sonArrFu(item.parentId).length - 1 !== index &&
            item.name !== "其它" ? (
              <Button
                size="small"
                type="text"
                onClick={() => sortMoveFu(1, index, item.id, item.parentId)}
              >
                下移
              </Button>
            ) : null}

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

  return (
    <div id="A2Table3">
      {tableList.length ? (
        <Table
          size={myType === "字典" ? "small" : "large"}
          scroll={{ y: myType === "字典" ? "auto" : 750 }}
          dataSource={tableList}
          columns={columns}
          rowKey="id"
          pagination={false}
          expandable={{ defaultExpandAllRows: true }}
        />
      ) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
    </div>
  );
}

const MemoA2Table3 = React.memo(A2Table3);

export default MemoA2Table3;
