import { getTableData } from '@/services/common/components';
import type { ProColumns } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Empty, Space, Table } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

type TableListItem = {
  [key: string]: any;
};
type ableType = {
  id: number; //id标识
  status: boolean;
  type: string;
};
type pageType = {
  pageSize: number;
  pageNum?: number;
};

type MenuTableType = {
  columns: ProColumns<TableListItem>[];
  initAPI: string;
  headerTitle: string;
  rowKey: string;
  reload: number;
  toolbar?: object;
  toolBarRender?: () => React.ReactNode[];
  isMass?: boolean;
  setMassIds?: (ids: (string | number)[]) => void;
  otherParams?: object;
  searchParams?: object;
  selectedValue?: (value: any) => void;
  getCheckboxProps?: (record: any) => any;
  pageParams?: pageType;
  scrollX?: string | number;
  disableEnable?: ableType; //{id,status}
  sortType?: ableType; //{id,type}
  isSerial?: boolean;
  isChildExpand?: boolean;
  lastTable?: boolean;
  tableProps?: any;
  setSearchTerms?: (value: any) => void;
  onResetSearch?: () => void;
  extendedMenus?:number
};

const MenuTable = ({
  columns,
  initAPI,
  headerTitle,
  toolbar,
  toolBarRender,
  rowKey,
  reload,
  isMass,
  setMassIds,
  selectedValue,
  getCheckboxProps,
  otherParams,
  searchParams,
  scrollX,
  pageParams,
  disableEnable,
  sortType,
  isSerial,
  isChildExpand,
  lastTable,
  tableProps,
  setSearchTerms,
  onResetSearch,
  extendedMenus
}: MenuTableType) => {
  const intl = useIntl();
  const [customColumns, setCustomColumns] = useState<any>();
  const [tableData, setTableData] = useState<any>([]);
  const expandChildrenColumnName =
    tableProps?.expandable?.childrenColumnName || 'children';

  // 操作表格
  const tableRef: React.MutableRefObject<any> = useRef();

  // 递归处理带子项child的表格，没数据将child转为null，防止出现空展开的图标
  const extractChildren = (arr: any) => {
    return arr.map((item: any) => {
      if (item.child && item.child.length === 0) {
        item.child = null;
      } else if (item.child && item.child.length > 0) {
        item.child = extractChildren(item.child);
      }
      return item;
    });
  };

  //判断数据是否为最后一位
  const markLastItem = (items: any) => {
    items.forEach((item: any, index: any, array: any) => {
      item.finally = index === array.length - 1;
      if (item[expandChildrenColumnName]) {
        markLastItem(item[expandChildrenColumnName]);
      }
    });
  };

  //搜索所有id
  const getAllkey = (items: any) => {
    let ids: any = [];
    const traverseItems = (items: any) => {
      items.forEach((item: any) => {
        ids.push(item[rowKey]);
        if (item[expandChildrenColumnName]) {
          traverseItems(item[expandChildrenColumnName]);
        }
      });
    };
    traverseItems(items);
    return ids;
  };

  // 封装表格类 网络请求
  const getTable: any = async (params: {
    pageSize: number;
    current: number;
  }) => {
    const req: any = {
      ...otherParams,
      ...params,
      ...searchParams,
      pageSize: pageParams?.pageSize || params.pageSize,
      pageNum: params.current,
    };
    delete req.current;
    const resp = await getTableData(initAPI, req);

    let dataItems;
    if (isSerial) {
      if (isChildExpand) {
        const data = resp.data.items.map((item: any, index: number) => ({
          ...item,
          orderIndex: index + 1 + (params.current - 1) * params.pageSize,
        }));
        dataItems = extractChildren(data);
      } else {
        dataItems = resp.data.items.map((item: any, index: number) => ({
          ...item,
          orderIndex: index + 1 + (params.current - 1) * params.pageSize,
        }));
      }
    } else {
      dataItems = resp.data.items;
    }
    if (lastTable) markLastItem(dataItems);
    setTableData(dataItems);

    if (setSearchTerms&&extendedMenus) {
      const paramsData: any = {
        ...otherParams,
        ...params,
        ...searchParams,
      };
      if (Object.keys(paramsData).length > extendedMenus) {
        const menuIds = getAllkey(dataItems);
        setSearchTerms(menuIds);
      } else {
        setSearchTerms([]);
      }
    }

    return {
      data: dataItems,
      success: true,
      total: resp.data?.totalCount,
    };
  };

  //禁用/启用子级逻辑
  const setRoutesStatus = (routes: any, status: any) => {
    routes.forEach((route: any) => {
      route.status = status;
      if (route[expandChildrenColumnName]) {
        setRoutesStatus(route[expandChildrenColumnName], status);
      }
    });
  };

  //禁用/启用父级逻辑
  const setStatusFalse = (items: any, id: number) => {
    const newItems = [...items];
    newItems.forEach((item: any) => {
      if (item[rowKey] === id) {
        item.status = !item.status;
        if (item[expandChildrenColumnName]) {
          setRoutesStatus(item[expandChildrenColumnName], item.status);
        }
      } else if (item[expandChildrenColumnName]) {
        setStatusFalse(item[expandChildrenColumnName], id);
      }
    });
    setTableData(newItems);
  };

  //排序逻辑
  const sortMenu = (items: any, id: number, type: string) => {
    const targetIndex = items.findIndex((item: any) => item[rowKey] === id);
    if (targetIndex === -1) {
      return items.map((item: any) =>
        item[expandChildrenColumnName]
          ? {
              ...item,
              [expandChildrenColumnName]: sortMenu(
                item[expandChildrenColumnName],
                id,
                type,
              ),
            }
          : item,
      );
    }
    const targetItem = items[targetIndex];
    const restItems = items.filter(
      (_: any, index: any) => index !== targetIndex,
    );

    switch (type) {
      case 'top':
        return [targetItem].concat(restItems);
      case 'bottom':
        return restItems.concat([targetItem]);
      case 'prev':
        return targetIndex === 0
          ? items
          : [
              ...restItems.slice(0, targetIndex - 1),
              targetItem,
              items[targetIndex - 1],
              ...restItems.slice(targetIndex),
            ];
      case 'next':
        return targetIndex === items.length - 1
          ? items
          : [
              ...restItems.slice(0, targetIndex),
              items[targetIndex + 1],
              targetItem,
              ...restItems.slice(targetIndex + 1),
            ];
      default:
        return items;
    }
  };

  // 重置
  const onReset = () => {
     onResetSearch?.();
  };

  useEffect(() => {
    if (isSerial) {
      setCustomColumns([
        {
          title: intl.formatMessage({
            id: 'columns.title.index',
            defaultMessage: '序号',
          }),
          dataIndex: 'orderIndex',
          render: (_: any, { orderIndex }: any) => (
            <span>{parseInt(orderIndex) > 0 ? parseInt(orderIndex) : ''}</span>
          ),
          key: 'index',
          width: 80,
          fixed: 'left',
          align: 'center',
          search: false,
        },
        ...columns.map((item) => {
          if (!item.title) return item;
          return {
            ...item,
            ellipsis: true,
          };
        }),
      ]);
    } else {
      setCustomColumns(columns);
    }
  }, []);

  useEffect(() => {
    tableRef.current.reload();
  }, [reload]);

  useEffect(() => {
    if (disableEnable?.id) {
      setStatusFalse(tableData, disableEnable.id);
    }
  }, [disableEnable]);

  useEffect(() => {
    if (sortType?.id) {
      const data = sortMenu(tableData, sortType.id, sortType.type);
      if (lastTable) {
        markLastItem(data);
      }
      setTableData(data);
    }
  }, [sortType]);

  return (
    <div style={{ padding: 24 }}>
      {
        <ProTable<TableListItem>
          locale={{
            emptyText: (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={
                  <span>{intl.formatMessage({ id: 'form.text.noData' })}</span>
                }
              />
            ),
          }}
          actionRef={tableRef}
          columns={customColumns}
          request={getTable}
          dataSource={tableData}
          scroll={{ x: scrollX || 'max-content' }}
          params={otherParams || {}}
          onDataSourceChange={() => {
            tableRef.current.clearSelected();
          }}
          rowSelection={
            isMass
              ? {
                  selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
                  onChange: (selectedRowKeys:any, value) => {
                    if (setMassIds) {
                      setMassIds(selectedRowKeys);
                    }
                    if (selectedValue) {
                      selectedValue(value);
                    }
                  },
                  getCheckboxProps: getCheckboxProps,
                }
              : undefined
          }
          rowKey={rowKey || 'id'}
          tableAlertRender={({ selectedRowKeys }) => {
            return (
              <Space size={24}>
                <span>
                  <FormattedMessage
                    id="columns.handel.selected"
                    defaultMessage="已选"
                  />
                  {selectedRowKeys.length}
                  <FormattedMessage
                    id="columns.handel.unit"
                    defaultMessage="项"
                  />
                </span>
              </Space>
            );
          }}
          pagination={{
            hideOnSinglePage: true,
            showQuickJumper: true,
            defaultPageSize: 10,
          }}
          search={{
            labelWidth: 'auto',
            // layout: 'vertical',
          }}
          dateFormatter="string"
          headerTitle={headerTitle}
          toolbar={toolbar}
          onReset={onReset}
          toolBarRender={toolBarRender || undefined}
          {...tableProps}
        />
      }
    </div>
  );
};

export default MenuTable;
