import { BizValueType } from '@/components';
import { formatParam } from '@/utils/formatParam';
import { pagination } from '@/utils/pagination';
import { useIntl } from '@@/exports';
import { ProTable, ProTableProps } from '@ant-design/pro-components';
import { Button, Drawer } from 'antd';
import { useState } from 'react';
import { BizPageProps } from './typing';

export default function BizPage<
	BizVO extends Record<string, any>,
	BizPageQry extends Record<string, any>,
	Func extends Record<string, any>,
>(props: BizPageProps<BizVO, BizPageQry, Func>) {
	const {
		rowKey,
		method,
		func,
		methodUpper,
		columns,
		fieldProps,
		trigger,
		isMobile,
		intlPrefix,
	} = props;
	const [open, setOpen] = useState(false);
	const intl = useIntl();

	const rest: ProTableProps<BizVO, BizPageQry, BizValueType> = {
		rowKey: rowKey,
		...fieldProps,
		columns: columns,
		columnsState: {
			persistenceType: 'sessionStorage',
			persistenceKey: method + 'ColumnStateKey',
			defaultValue: {
				// option: { show: true, fixed: 'right' },
			},
		},
		scroll: { x: 'max-content' },
		params: {
			...fieldProps?.params,
		} as any,
		...(fieldProps?.search !== false && {
			search: {
				labelWidth: 'auto',
				defaultCollapsed: false,
				showHiddenNum: true,
				optionRender: (searchConfig, formProps, dom) => [
					...dom.reverse(),
					<Button
						hidden={true}
						key="out"
						onClick={() => {
							const values = searchConfig?.form?.getFieldsValue();
							console.log(values);
						}}
					>
						导出
					</Button>,
				],
			},
		}),
	};

	const renderTable = () => {
		return (
			<ProTable<BizVO, BizPageQry, BizValueType>
				request={async (params, sorter, filter) => {
					const { data, success, totalCount } = await func?.[
						`page${methodUpper}`
					]({
						[`${method}PageQry`]: formatParam<typeof params>(
							params,
							sorter,
							filter,
						),
					});

					return {
						data,
						success,
						total: totalCount,
					};
				}}
				pagination={{
					...pagination(),
					position: ['bottomRight'],
				}}
				{...rest}
			/>
		);
	};

	if (trigger) {
		return (
			<>
				<Drawer
					title={intl.formatMessage({
						id: intlPrefix + '.modal.page.title',
					})}
					width={isMobile ? '100%' : '85%'}
					destroyOnHidden={true}
					open={open}
					onClose={() => setOpen(false)}
				>
					{renderTable()}
				</Drawer>
				<div
					onClick={() => {
						setOpen(true);
					}}
				>
					{trigger?.()}
				</div>
			</>
		);
	}

	return renderTable();
}
