import {
	BizContainer,
	BizValueType,
	DealerPaymentAccountList,
	DealerSelect,
	ModeType,
	ProFormUploadMaterial,
	ReconciliationSelect,
} from '@/components';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { useIntl } from '@@/exports';
import {
	ProColumns,
	ProFormDatePicker,
	ProFormDependency,
	ProFormMoney,
	ProFormSelect,
} from '@ant-design/pro-components';
import { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import dayjs from 'dayjs';
import React from 'react';

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

export default function ReconciliationInvoiceList(
	props: IReconciliationInvoiceListProps,
) {
	const {
		ghost = false,
		reconciliationId,
		reconciliationVO,
		dealerId,
		search = true,
		mode = 'page',
		trigger,
		onValueChange,
	} = props;
	const intl = useIntl();
	const intlPrefix = 'reconciliationInvoice';

	// 定义表格列
	const columns: ProColumns<
		BusinessAPI.ReconciliationInvoiceVO,
		BizValueType
	>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.invoiceSn' }),
			dataIndex: 'invoiceSn',
			key: 'invoiceSn',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.dealer' }),
			dataIndex: 'dealerVO',
			key: 'dealerId',
			valueType: 'dealer',
			hidden: !!dealerId,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.account' }),
			dataIndex: 'dealerPaymentAccountVO',
			key: 'accountId',
			render: (_, record) => {
				const { dealerPaymentAccountVO } = record;
				return (
					dealerPaymentAccountVO && (
						<DealerPaymentAccountList
							ghost={true}
							mode={'detail'}
							search={false}
							accountId={dealerPaymentAccountVO.accountId}
							trigger={() => {
								return <a>{dealerPaymentAccountVO.companyName}</a>;
							}}
						/>
					)
				);
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.company' }),
			dataIndex: 'companyVO',
			key: 'companyId',
			valueType: 'company',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.invoiceAmount' }),
			dataIndex: 'invoiceAmount',
			key: 'invoiceAmount',
			valueType: 'money',
			search: false,
			render: (_, record) => (
				<span className="text-green-600 font-medium">
					￥{formatCurrency(record.invoiceAmount)}
				</span>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.invoiceDate' }),
			dataIndex: 'invoiceDate',
			key: 'invoiceDate',
			valueType: 'dateRange',
			render: (_, record) => (
				<span>
					{record.invoiceDate && dayjs(record.invoiceDate).format('YYYY-MM-DD')}
				</span>
			),
		},
	];

	const formContext = [
		<DealerSelect key={'dealerId'} />,
		<ProFormDependency key={'reconciliationId'} name={['dealerId']}>
			{({ dealerId }, form) => {
				return (
					dealerId && (
						<>
							<ReconciliationSelect
								key={'reconciliationId'}
								params={{
									dealerId,
									state: 'RECONCILED',
								}}
								onFinish={(reconciliationVOList) => {
									const reconciliation = reconciliationVOList[0];
									form.setFieldsValue({
										pendingAmount: reconciliation?.reconciliationAmount,
									});
								}}
							/>
							<ProFormSelect
								key="accountId"
								name="accountId"
								label={intl.formatMessage({
									id: intlPrefix + '.form.accountId.label',
								})}
								placeholder={intl.formatMessage({
									id: intlPrefix + '.form.accountId.placeholder',
								})}
								required
								rules={[
									{
										required: true,
										message: intl.formatMessage({
											id: intlPrefix + '.form.accountId.required',
										}),
									},
								]}
								dependencies={['dealerId']}
								request={async (params) => {
									const { data } =
										await business.dealerPaymentAccount.listDealerPaymentAccount(
											{
												dealerPaymentAccountListQry: {
													...params,
												},
											},
										);
									return (
										data?.map((item) => ({
											label: item.companyName,
											value: item.accountId,
										})) || []
									);
								}}
							/>
						</>
					)
				);
			}}
		</ProFormDependency>,
		<ProFormMoney
			key="pendingAmount"
			name="pendingAmount"
			label={intl.formatMessage({
				id: intlPrefix + '.form.pendingAmount.label',
			})}
			disabled
			readonly
		/>,
		<ProFormDependency key="currentInvoiceAmount" name={['pendingAmount']}>
			{({ pendingAmount }) => (
				<ProFormMoney
					name="currentInvoiceAmount"
					label={intl.formatMessage({
						id: intlPrefix + '.form.currentInvoiceAmount.label',
					})}
					placeholder={intl.formatMessage({
						id: intlPrefix + '.form.currentInvoiceAmount.placeholder',
					})}
					required
					rules={[
						{
							required: true,
							message: intl.formatMessage({
								id: intlPrefix + '.form.currentInvoiceAmount.required',
							}),
						},
					]}
					fieldProps={{
						max: pendingAmount,
					}}
				/>
			)}
		</ProFormDependency>,
		<ProFormSelect
			key="companyId"
			name="companyId"
			label={intl.formatMessage({ id: intlPrefix + '.form.companyId.label' })}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.companyId.placeholder',
			})}
			required
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.companyId.required',
					}),
				},
			]}
			request={async (params) => {
				const { data } = await business.company.listCompany({
					companyListQry: {
						...params,
					},
				});
				return (
					data?.map((item) => ({
						label: item.fullName,
						value: item.companyId,
					})) || []
				);
			}}
		/>,
		<ProFormDatePicker
			key="invoiceDate"
			name="invoiceDate"
			label={intl.formatMessage({ id: intlPrefix + '.form.invoiceDate.label' })}
			placeholder={intl.formatMessage({
				id: intlPrefix + '.form.invoiceDate.placeholder',
			})}
			required
			rules={[
				{
					required: true,
					message: intl.formatMessage({
						id: intlPrefix + '.form.invoiceDate.required',
					}),
				},
			]}
			fieldProps={{
				style: { width: '100%' },
			}}
		/>,
		<ProFormUploadMaterial
			mode={'file'}
			key={'invoiceImgList'}
			tooltip={intl.formatMessage({ id: intlPrefix + '.form.invoiceFile.tip' })}
			label={intl.formatMessage({
				id: intlPrefix + '.form.invoiceFile.label',
			})}
			transform={(fileList: BusinessAPI.MaterialVO[]) => {
				console.log('fileList', fileList);
				return {
					invoiceImgList: fileList,
					invoiceImg: fileList.map((item: BusinessAPI.MaterialVO) => {
						// const itemInfo = await getImageInfo(item.url);
						return {
							/** 文件名 */
							fileName: item.name,
							/** 文件路径 */
							filePath: item.url,
							/** 文件类型 */
							fileType: item.url.split('.').pop(),
							/** 文件大小 */
							fileSize: 0,
						};
					}),
				};
			}}
			name={'invoiceFile'}
			fieldProps={{
				maxCount: 9,
			}}
		/>,
	];

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

	return (
		<BizContainer<
			typeof business.reconciliationInvoice,
			BusinessAPI.ReconciliationInvoiceVO,
			BusinessAPI.ReconciliationInvoicePageQry
		>
			rowKey={'reconciliationInvoiceId'}
			permission={'operation-reconciliation-invoice'}
			func={business.reconciliationInvoice}
			method={'reconciliationInvoice'}
			methodUpper={'ReconciliationInvoice'}
			intlPrefix={intlPrefix}
			modeType={mode}
			onValueChange={onValueChange}
			container={{ ghost }}
			remark={{ mode: 'editor' }}
			status={false}
			page={{
				fieldProps: {
					bordered: true,
					ghost,
					//@ts-ignore
					search,
					//@ts-ignore
					params: {
						...(reconciliationId && { reconciliationId }),
						...(dealerId && { dealerId }),
					},
				},
				columns,
				options: () => [],
			}}
			create={{
				formType: 'drawer',
				formContext,
				trigger,
				initValues: {
					...(reconciliationVO && {
						reconciliationId: reconciliationVO.reconciliationId,
						reconciliationVO: reconciliationVO,
						canChangeReconciliation: false,
						dealerId: reconciliationVO.dealerId,
						dealerVO: reconciliationVO.dealerVO,
						canChangeDealer: false,
					}),
				},
			}}
			update={false}
			destroy={false}
			detail={{
				rowId: reconciliationId,
				formType: 'drawer',
				columns: detailColumns,
				trigger,
			}}
		/>
	);
}
