import { formatParam } from '@/utils/formatParam';
import { useIntl } from '@@/exports';
import { DragSortTable, DragTableProps } from '@ant-design/pro-components';
import { Drawer } from 'antd';
import { useState } from 'react';
import { BizDragProps, BizValueType } from './typing';
import { pagination } from '@/utils/pagination';

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

	const rest: DragTableProps<BizVO, BizPageQry> = {
		rowKey: rowKey,
		...fieldProps,
		//@ts-ignore
		columns: columns,
		columnsState: {
			persistenceType: 'sessionStorage',
			persistenceKey: method + 'ColumnStateKey',
			defaultValue: {
				...fieldProps?.columnsState?.defaultValue,
			},
		},
		dragSortKey: 'sort',
		scroll: { x: 'max-content' },
		params: {
			...fieldProps?.params,
		} as any,
		...(fieldProps?.search !== false && {
			search: {
				labelWidth: 'auto',
				showHiddenNum: true,
			},
		}),
	};

	const handleDragSortEnd = async (
		beforeIndex: number,
		afterIndex: number,
		newDataSource: any,
	) => {
		// 根据 afterIndex 在 newDataSource 找出currentId prevId nextId
		const currentId = newDataSource[afterIndex][`${rowKey as string}`];
		const prevId = newDataSource[afterIndex - 1]
			? newDataSource[afterIndex - 1][`${rowKey as string}`]
			: null;
		const nextId = newDataSource[afterIndex + 1]
			? newDataSource[afterIndex + 1][`${rowKey as string}`]
			: null;
		await func?.[`drag${methodUpper}`]({
			currentId,
			nextId,
			prevId,
		});

		//@ts-ignore
		fieldProps?.actionRef?.current?.reload();
	};

	const renderTable = () => {
		return (
			<DragSortTable<BizVO, BizPageQry, BizValueType>
				request={async (params, sorter, filter) => {
					if (mode === 'list') {
						const { data, success } = await func?.[`list${methodUpper}`]({
							[`${method}ListQry`]: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

						return {
							data,
							success,
						};
					}

					if (mode === 'tree') {
						const { data, success } = await func?.[`tree${methodUpper}`]({
							[`${method}TreeQry`]: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

						return {
							data,
							success,
						};
					}

					return {
						data: [],
						success: true,
					};
				}}
				onDragSortEnd={handleDragSortEnd}
				pagination={{
					...pagination(),
					position: ['bottomRight'],
				}}
				{...rest}
				columns={[
					{
						title: '排序',
						dataIndex: 'sort',
						key: 'sort',
						search: false,
					},
					//@ts-ignore
					...columns,
				]}
			/>
		);
	};

	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>
			</>
		);
	} else {
		return renderTable();
	}
}
