import { ButtonAccess } from '@/components';
import { business } from '@/services';
import { useIntl } from '@@/exports';
import { ExclamationCircleFilled } from '@ant-design/icons';
import { message, Modal } from 'antd';

export interface IReconciliationCompleteProps {
	/** 权限标识 */
	permission?: string;
	/** 行数据 */
	reconciliationVO: BusinessAPI.ReconciliationVO;
	/** 国际化前缀 */
	intlPrefix?: string;
	/** 完成回调 */
	onFinish?: () => void;
	/** 位置Key */
	positionKey?: string;
}

export default function ReconciliationComplete(
	props: IReconciliationCompleteProps,
) {
	const {
		permission = 'operation-reconciliation-record',
		reconciliationVO,
		onFinish,
		positionKey,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'reconciliation';

	const handleComplete = async (
		reconciliationId: BusinessAPI.ReconciliationVO['reconciliationId'],
	) => {
		try {
			const { success, errCode } =
				await business.reconciliation.completeReconciliation({
					reconciliationId: reconciliationId,
				});

			if (success) {
				if (errCode === '401') {
					message.error(
						intl.formatMessage({ id: 'message.error.permissionDenied' }),
					);
				} else {
					message.success(
						intl.formatMessage({
							id: intlPrefix + '.modal.complete.success',
						}),
					);
				}
			} else {
				message.error(
					intl.formatMessage({ id: intlPrefix + '.modal.complete.error' }),
				);
			}
		} finally {
			onFinish?.();
		}
	};

	const complete = (
		reconciliationId?: BusinessAPI.ReconciliationVO['reconciliationId'],
	) => {
		Modal.confirm({
			title: intl.formatMessage({
				id: intlPrefix + '.modal.complete.confirm.title',
			}),
			icon: <ExclamationCircleFilled />,
			content: intl.formatMessage({
				id: intlPrefix + '.modal.complete.confirm.content',
			}),
			okText: intl.formatMessage({
				id: intlPrefix + '.modal.complete.confirm.okText',
			}),
			cancelText: intl.formatMessage({
				id: intlPrefix + '.modal.complete.confirm.cancelText',
			}),
			onOk: async () => {
				if (!reconciliationId) {
					message.error(intl.formatMessage({ id: 'message.error' }));
					return false;
				}
				await handleComplete(reconciliationId);
				return true;
			},
			onCancel() {},
		});
	};

	return (
		<ButtonAccess
			key={'complete'}
			permission={`${permission}-complete`}
			type={'link'}
			onClick={(event) => {
				event.stopPropagation();
				complete(reconciliationVO.reconciliationId);
			}}
			positionKey={positionKey}
		>
			{intl.formatMessage({
				id: intlPrefix + '.modal.complete.button',
			})}
		</ButtonAccess>
	);
}
