import {
	BizContainer,
	BizValueType,
	ModeType,
	ReconciliationComplete,
	ReconciliationCreate,
} from '@/components';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { useIntl } from '@@/exports';
import { ActionType, ProColumns } from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import React, { useRef, useState } from 'react';

interface IReconciliationRecordListProps {
	ghost?: boolean;
	reconciliationId?: BusinessAPI.ReconciliationVO['reconciliationId'];
	search?: boolean;
	onValueChange?: () => void;
	mode?: ModeType;
	trigger?: () => React.ReactNode;
}

export default function ReconciliationList(
	props: IReconciliationRecordListProps,
) {
	const {
		ghost = false,
		reconciliationId,
		search = true,
		mode = 'page',
		trigger,
		onValueChange,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'reconciliation';

	const [activeKey, setActiveKey] = useState<string>('PENDING');

	// 对账状态映射
	const stateMap: Record<string, { label: string; color: string }> = {
		PENDING: {
			label: intl.formatMessage({
				id: intlPrefix + '.state.pending',
			}),
			color: 'default',
		},
		RECONCILED: {
			label: intl.formatMessage({
				id: intlPrefix + '.state.reconciled',
			}),
			color: 'processing',
		},
		PARTIAL_INVOICE: {
			label: intl.formatMessage({
				id: intlPrefix + '.state.partialInvoice',
			}),
			color: 'warning',
		},
		INVOICED: {
			label: intl.formatMessage({
				id: intlPrefix + '.state.invoiced',
			}),
			color: 'success',
		},
		PARTIAL_PAYMENT: {
			label: intl.formatMessage({
				id: intlPrefix + '.state.partialPayment',
			}),
			color: 'warning',
		},
		PAID: {
			label: intl.formatMessage({
				id: intlPrefix + '.state.paid',
			}),
			color: 'success',
		},
	};

	const columns: ProColumns<BusinessAPI.ReconciliationVO, BizValueType>[] = [
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.reconciliationSn',
			}),
			dataIndex: 'reconciliationSn',
			key: 'reconciliationSn',
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.dealer',
			}),
			dataIndex: 'dealerVO',
			key: 'dealerId',
			valueType: 'dealer',
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.company',
			}),
			dataIndex: 'companyVO',
			key: 'companyId',
			valueType: 'company',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.originalAmount' }),
			dataIndex: 'originalAmount',
			key: 'originalAmount',
			valueType: 'money',
			search: false,
			render: (_, record) => (
				<span className="text-gray-600">
					￥{formatCurrency(record.originalAmount)}
				</span>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.roundingAmount' }),
			dataIndex: 'roundingAmount',
			key: 'roundingAmount',
			valueType: 'money',
			search: false,
			render: (_, record) => (
				<span
					className={record.roundingAmount ? 'text-blue-600' : 'text-gray-400'}
				>
					{record.roundingAmount
						? `￥${formatCurrency(record.roundingAmount)}`
						: '-'}
				</span>
			),
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.reconciliationAmount',
			}),
			dataIndex: 'reconciliationAmount',
			key: 'reconciliationAmount',
			valueType: 'money',
			search: false,
			render: (_, record) => (
				<span className="text-green-600 font-medium">
					￥{formatCurrency(record.reconciliationAmount)}
				</span>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.state' }),
			dataIndex: 'state',
			key: 'state',
			valueType: 'select',
			valueEnum: Object.entries(stateMap).reduce(
				(acc, [key, value]) => ({
					...acc,
					[key]: { text: value.label, status: value.color as any },
				}),
				{},
			),
			search: false,
			render: (_, record) => {
				const stateInfo = stateMap[record.state as string];
				return stateInfo ? (
					<span className={`text-${stateInfo.color}-600`}>
						{stateInfo.label}
					</span>
				) : (
					<span>{record.state}</span>
				);
			},
		},
	];

	const detailColumns: ProDescriptionsItemProps<
		BusinessAPI.ReconciliationVO,
		BizValueType
	>[] = columns as ProDescriptionsItemProps<
		BusinessAPI.ReconciliationVO,
		BizValueType
	>[];

	const actionRef = useRef<ActionType>();

	return (
		<BizContainer<
			typeof business.reconciliation,
			BusinessAPI.ReconciliationVO,
			BusinessAPI.ReconciliationPageQry
		>
			rowKey={'reconciliationId'}
			permission={'operation-reconciliation-record'}
			func={business.reconciliation}
			method={'reconciliation'}
			methodUpper={'Reconciliation'}
			intlPrefix={intlPrefix}
			modeType={mode}
			onValueChange={onValueChange}
			container={{
				ghost,
			}}
			remark={{
				mode: 'editor',
			}}
			status={false}
			page={{
				fieldProps: {
					actionRef: actionRef,
					bordered: true,
					ghost,
					//@ts-ignore
					search,
					params: {
						...(reconciliationId && { reconciliationId }),
						...(activeKey !== 'ALL' && {
							state: activeKey as BusinessAPI.ReconciliationVO['state'],
						}),
					},
					toolbar: {
						menu: {
							type: 'tab',
							activeKey: activeKey,
							items: [
								{
									key: 'ALL',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.all',
									}),
								},
								{
									key: 'PENDING',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.pending',
									}),
								},
								{
									key: 'RECONCILED',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.reconciled',
									}),
								},
								{
									key: 'PARTIAL_INVOICE',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.partialInvoice',
									}),
								},
								{
									key: 'INVOICED',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.invoiced',
									}),
								},
								{
									key: 'PARTIAL_PAYMENT',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.partialPayment',
									}),
								},
								{
									key: 'PAID',
									label: intl.formatMessage({
										id: intlPrefix + '.tab.paid',
									}),
								},
							],
							onChange: (key) => {
								setActiveKey(key as string);
							},
						},
						actions: [
							<ReconciliationCreate
								mode={'drawer'}
								key={'create'}
								onFinish={() => {
									actionRef.current?.reload();
									onValueChange?.();
								}}
							/>,
						],
					},
				},
				columns,
				options: (record, actionRef) => [
					record.state && (
						<ReconciliationComplete
							key={'complete'}
							reconciliationVO={record}
							intlPrefix={intlPrefix}
							onFinish={() => {
								actionRef.current?.reload();
								onValueChange?.();
							}}
						/>
					),
				],
			}}
			create={false}
			update={false}
			destroy={false}
			detail={{
				rowId: reconciliationId,
				formType: 'drawer',
				columns: detailColumns,
				trigger,
			}}
		/>
	);
}
