import {
	BizEditor,
	ButtonAccess,
	CompanyPaymentAccountSelect,
	InsertPosition,
	MaterialList,
	OrderSupplierInvoiceList,
	ProFormUploadMaterial,
	SupplierFarmerList,
	SupplierInvoiceList,
	SupplierSelect,
} from '@/components';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { formatParam } from '@/utils/formatParam';
import { formLayout } from '@/utils/formLayout';
import { useIntl } from '@@/exports';
import {
	ActionType,
	DrawerForm,
	ProCard,
	ProFormDependency,
	ProFormItem,
	ProFormMoney,
	RouteContext,
	RouteContextType,
} from '@ant-design/pro-components';
import { Col, Row, Space, Table } from 'antd';
import { useRef } from 'react';

export interface IPaymentTaskPayProps {
	insertPosition?: InsertPosition;
	paymentTaskVO: BusinessAPI.PaymentTaskVO;
	onFinish: () => void;
}

export default function PaymentTaskPay(props: IPaymentTaskPayProps) {
	const { paymentTaskVO, onFinish } = props;
	const intl = useIntl();
	const intlPrefix = 'paymentTask';

	// 计算剩余付款金额
	const unpaidAmount =
		(paymentTaskVO.totalAmount || 0) - (paymentTaskVO.paidAmount || 0);

	const actionRef = useRef<ActionType>();

	const handleSubmit = async (formData: any) => {
		console.log('付款数据：', formData);
		// TODO: 调用付款接口
		// const { success } = await business.paymentTask.pay({
		//   ...formData,
		// });
		// if (success) {
		//   message.success('付款成功');
		onFinish();
		// }
		// return success;
		return true;
	};

	return (
		<RouteContext.Consumer>
			{(value: RouteContextType) => {
				const { isMobile } = value;
				return (
					<DrawerForm
						title={intl.formatMessage({
							id: intlPrefix + '.modal.pay.title',
						})}
						{...formLayout(isMobile)}
						width={isMobile ? '100%' : '85%'}
						drawerProps={{
							destroyOnHidden: true,
						}}
						params={{
							paymentTaskId: paymentTaskVO.paymentTaskId,
						}}
						request={async (params) => {
							const { data } = await business.paymentTask.showPaymentTask({
								paymentTaskShowQry: params,
							});

							return data;
						}}
						trigger={
							<ButtonAccess
								key={'pay'}
								permission={'operation-payment-task-pay'}
								type={'link'}
								size={'small'}
							>
								{intl.formatMessage({
									id: intlPrefix + '.modal.pay.button',
								})}
							</ButtonAccess>
						}
						onFinish={handleSubmit}
					>
						{/* 模块1：付款任务信息 */}
						<ProFormItem
							style={{
								width: '100%',
							}}
							label={intl.formatMessage({
								id: intlPrefix + '.modal.pay.section.taskInfo',
							})}
						>
							<ProCard bordered>
								<Row gutter={[16, 16]}>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												{intl.formatMessage({
													id: intlPrefix + '.modal.pay.taskInfo.supplierName',
												})}
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{paymentTaskVO.supplierVO?.name}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												{intl.formatMessage({
													id: intlPrefix + '.modal.pay.taskInfo.totalAmount',
												})}
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{formatCurrency(paymentTaskVO.totalAmount || 0)}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												{intl.formatMessage({
													id: intlPrefix + '.modal.pay.taskInfo.paidAmount',
												})}
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{formatCurrency(paymentTaskVO.paidAmount || 0)}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												{intl.formatMessage({
													id: intlPrefix + '.modal.pay.taskInfo.unpaidAmount',
												})}
											</div>
											<div style={{ fontWeight: 'bold', color: '#ff4d4f' }}>
												{formatCurrency(unpaidAmount)}
											</div>
										</div>
									</Col>
								</Row>
								<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
									<Col span={12}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												{intl.formatMessage({
													id: intlPrefix + '.modal.pay.taskInfo.paymentCode',
												})}
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{paymentTaskVO.paymentCode}
											</div>
										</div>
									</Col>
									<Col span={12}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												{intl.formatMessage({
													id: intlPrefix + '.modal.pay.taskInfo.taskName',
												})}
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{paymentTaskVO.taskName}
											</div>
										</div>
									</Col>
								</Row>
							</ProCard>
						</ProFormItem>

						{/* 模块2：瓜农车次列表 */}
						<ProFormDependency name={['orderSupplierVOList']}>
							{({ orderSupplierVOList }) => {
								return (
									<ProFormItem
										name="orderSupplierVOList"
										style={{
											width: '100%',
										}}
										label={intl.formatMessage({
											id: intlPrefix + '.modal.pay.section.orderSupplier',
										})}
									>
										<ProCard bordered>
											<OrderSupplierInvoiceList
												rowKey="orderSupplierId"
												dataSource={orderSupplierVOList || []}
												columns={[
													{
														title: '开票瓜农',
														dataIndex: 'supplierInvoiceVO',
														key: 'supplierName',
														render: (
															supplierInvoiceVO: BusinessAPI.SupplierInvoiceVO,
														) => {
															return (
																supplierInvoiceVO && (
																	<SupplierFarmerList
																		ghost={true}
																		mode={'detail'}
																		supplierId={supplierInvoiceVO.supplierId}
																		trigger={() => (
																			<a>{supplierInvoiceVO.supplierName}</a>
																		)}
																	/>
																)
															);
														},
													},
													{
														title: '发票编码',
														dataIndex: 'supplierInvoiceVO',
														render: (
															supplierInvoiceVO: BusinessAPI.SupplierInvoiceVO,
														) => {
															return (
																<SupplierInvoiceList
																	ghost={true}
																	mode={'detail'}
																	supplierInvoiceId={
																		supplierInvoiceVO.supplierInvoiceId
																	}
																	trigger={() => (
																		<Space>
																			<a>{supplierInvoiceVO.invoiceSn}</a>
																		</Space>
																	)}
																/>
															);
														},
													},
												]}
												pagination={false}
												size="small"
												summary={(pageData) => {
													let totalAmount = 0;
													pageData.forEach(
														({ invoiceAmount, depositAmount }) => {
															totalAmount +=
																(invoiceAmount || 0) - (depositAmount || 0);
														},
													);
													return (
														<Table.Summary fixed>
															<Table.Summary.Row>
																<Table.Summary.Cell index={0} colSpan={4}>
																	<strong>合计</strong>
																</Table.Summary.Cell>
																<Table.Summary.Cell index={1}>
																	<strong style={{ color: '#ff4d4f' }}>
																		{formatCurrency(totalAmount)}
																	</strong>
																</Table.Summary.Cell>
																<Table.Summary.Cell index={2} />
															</Table.Summary.Row>
														</Table.Summary>
													);
												}}
											/>
										</ProCard>
									</ProFormItem>
								);
							}}
						</ProFormDependency>

						{/* 模块3：本次付款 */}
						<ProFormMoney
							name="paymentAmount"
							label={intl.formatMessage({
								id: intlPrefix + '.modal.pay.currentPayment.amount',
							})}
							placeholder={intl.formatMessage({
								id: intlPrefix + '.modal.pay.currentPayment.amountPlaceholder',
							})}
							required={true}
							fieldProps={{
								precision: 2,
								min: 0.01,
								max: unpaidAmount,
							}}
							rules={[
								{
									required: true,
									message: intl.formatMessage({
										id: intlPrefix + '.modal.pay.currentPayment.amountRequired',
									}),
								},
								{
									type: 'number',
									max: unpaidAmount,
									message: `付款金额不能超过剩余金额 ${formatCurrency(unpaidAmount)}`,
								},
							]}
						/>

						{/* 收款人 */}
						<SupplierSelect
							key={'supplierId'}
							params={{
								type: 'FARMER',
							}}
							name="supplierId"
							label={intl.formatMessage({
								id: intlPrefix + '.modal.pay.currentPayment.payeeName',
							})}
							placeholder={intl.formatMessage({
								id:
									intlPrefix + '.modal.pay.currentPayment.payeeNamePlaceholder',
							})}
							required={true}
							initialValue={paymentTaskVO.supplierVO?.name}
							rules={[
								{
									required: true,
									message: intl.formatMessage({
										id:
											intlPrefix +
											'.modal.pay.currentPayment.payeeNameRequired',
									}),
								},
							]}
						/>

						{/* 选择付款账户 */}
						<CompanyPaymentAccountSelect
							name={'companyPaymentAccountId'}
							label={'付款账户'}
							placeholder={'请选择付款账户'}
							required={true}
							params={{
								status: true,
							}}
							rules={[
								{
									required: true,
									message: '请选择付款账户',
								},
							]}
						/>

						{/* 上传付款凭证 */}
						<ProFormUploadMaterial
							key={'backgroundImageUrl'}
							label={intl.formatMessage({
								id: intlPrefix + '.form.backgroundImageUrl.label',
							})}
							name={'backgroundImageUrlList'}
							transform={(value) => {
								return {
									backgroundImageUrlList: value,
									backgroundImageUrl: value[0],
								};
							}}
							fieldProps={{
								maxCount: 1,
								actionRef: actionRef,
								toolBarRender: () => [
									<MaterialList
										key={'create'}
										ghost={true}
										mode={'create'}
										search={false}
										onValueChange={() => actionRef.current?.reload()}
									/>,
								],
								request: async (params, sorter, filter) => {
									const { data, success, totalCount } =
										await business.material.pageMaterial({
											materialPageQry: formatParam<typeof params>(
												params,
												sorter,
												filter,
											),
										});

									return {
										data: data || [],
										total: totalCount,
										success,
									};
								},
							}}
						/>

						{/* 付款备注 */}
						<ProFormDependency key={'remark'} name={['remark']}>
							{({ remark }, form) => {
								return (
									<BizEditor
										key={'remark'}
										value={remark}
										onChange={(value) => {
											form.setFieldValue('remark', value);
										}}
										label={intl.formatMessage({
											id: intlPrefix + '.modal.pay.remark.label',
										})}
										name={'remark'}
										placeholder={intl.formatMessage({
											id: intlPrefix + '.modal.pay.remark.placeholder',
										})}
									/>
								);
							}}
						</ProFormDependency>
					</DrawerForm>
				);
			}}
		</RouteContext.Consumer>
	);
}
