import { DefaultPagination } from '@/common/constant';
import type { ParamsType, ProTableProps, RequestData } from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-components';
import type { SearchConfig } from '@ant-design/pro-table/lib/components/Form/FormRender';
import type { SortOrder } from 'antd/lib/table/interface';
import { useState } from 'react';

export type MesTableProps<T, U, ValueType> = ProTableProps<T, U, ValueType>;

/**
 * ProTable封装
 * @param props
 * @returns
 */
const SuperTable = <
    T extends Record<string, any>,
    U extends ParamsType = ParamsType,
    ValueType = 'text',
>(
    props: MesTableProps<T, U, ValueType>,
) => {
    const { search, pagination, options, ...restProps } = props;
    const { filterType, ...restSearch } = search || {};

    const [pageSize, setPageSize] = useState(DefaultPagination.PAGE_SIZE);

    const ww = window.document.body.clientWidth;

    let newSearch: SearchConfig = {
        span: {
            xs: 24,
            sm: 12,
            md: 12,
            lg: 8,
            xl: 6,
            xxl: ww >= 1920 ? 4 : 6,
        },
        filterType,
        labelWidth: 'auto',
    };

    if (!filterType || filterType !== 'light') {
        // newSearch.showHiddenNum = true;
    }
    newSearch = { ...newSearch, ...restSearch };

    const { onChange, ...restPagination } = pagination || {};

    return (
        <ProTable<T, U, ValueType>
            rowKey="id"
            bordered
            size="small"
            search={search === false ? false : newSearch}
            sticky={{ offsetHeader: 56 }}
            pagination={
                pagination !== false && {
                    pageSizeOptions: [10, 15, 20, 25, 30, 50, 100, 200, 500, 1000],
                    showSizeChanger: true,
                    pageSize: pageSize,
                    size: 'default',
                    onChange(page, pageSize) {
                        setPageSize(pageSize);
                        onChange?.(page, pageSize);
                    },
                    ...restPagination,
                }
            }
            options={{
                density: false,
                fullScreen: true,
                ...(options || {}),
            }}
            {...restProps}
        />
    );
};

/** 统一处理后台请求及返回数据 */
SuperTable.requestPageAgent = async function <P extends API.PageQueryType & ParamsType, D>(
    antParams: {
        params: ParamsType;
        sort?: Record<string, SortOrder>;
    },
    run: (params: P) => Promise<API.PageResponse<D> | undefined>,
): Promise<RequestData<D>> {
    // const { params, sort } = antParams;
    const { params } = antParams;
    if (!params || !params.current) {
        throw new Error('无分页参数');
    }

    // let sortParams: { sortField?: string, sortOrder?: 'descend' | 'ascend' } = {};
    // if (sort) {
    //     for (const k in sort) {
    //         if (sort.hasOwnProperty(k)) {
    //             const sortk = sort[k];
    //             if (!sortk) {
    //                 break;
    //             }
    //             sortParams = {
    //                 sortField: k,
    //                 sortOrder: sortk,
    //             };
    //             break;
    //         }
    //     }
    // }

    const { current, pageSize, ...resetParams } = params;
    const data = await run({
        ...resetParams,
        pageIndex: current || DefaultPagination.PAGE_INDEX,
        pageSize: pageSize || DefaultPagination.PAGE_SIZE,
    } as P);
    if (!data) {
        return {} as RequestData<D>;
    }
    return {
        data: (params?.current ? data.items : data) ?? [],
        success: true,
        total: params?.current ? data.totalCount : null,
    } as RequestData<D>;
};

export default SuperTable;
