import {
	BizEditor,
	ButtonAccess,
	CompanyPaymentAccountSelect,
	InsertPosition,
	ProFormUploadMaterial,
} from '@/components';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { formLayout } from '@/utils/formLayout';
import {
	DrawerForm,
	ProCard,
	ProFormDependency,
	ProFormItem,
	ProFormMoney,
	ProFormText,
	RouteContext,
	RouteContextType,
} from '@ant-design/pro-components';
import { Col, message, Row } from 'antd';
import dayjs from 'dayjs';

export interface IOrderCostPayProps {
	insertPosition?: InsertPosition;
	orderCostVO: BusinessAPI.OrderCostVO;
	onFinish: () => void;
}

export default function OrderCostPay(props: IOrderCostPayProps) {
	const { orderCostVO, onFinish } = props;

	const handleSubmit = async (formData: any) => {
		console.log('费用付款数据：', formData);

		// 获取选中账户的详细信息
		const { data: accountData } =
			await business.companyPaymentAccount.showCompanyPaymentAccount({
				companyPaymentAccountShowQry: {
					accountId: formData.companyPaymentAccountId,
				},
			});

		if (!accountData) {
			message.error('获取账户信息失败');
			return false;
		}

		// 构建符合接口要求的数据结构
		const payData: BusinessAPI.OrderCostPayCmd = {
			orderCostId: orderCostVO.orderCostId,
			paidAmount: formData.paidAmount,
			...accountData,
			paidAt: dayjs().format('YYYY-MM-DD HH:mm:ss'),
			paidCredentials: formData.paidCredentials || [],
			remark: formData.remark,
		};

		console.log('转换后的费用付款数据：', payData);

		const { success } = await business.orderCost.payOrderCost(payData);
		if (success) {
			message.success('费用付款成功');
			onFinish();
		}
		return success;
	};

	return (
		<RouteContext.Consumer>
			{(value: RouteContextType) => {
				const { isMobile } = value;
				return (
					<DrawerForm
						title={'费用付款'}
						{...formLayout(isMobile)}
						width={isMobile ? '100%' : '85%'}
						drawerProps={{
							destroyOnHidden: true,
						}}
						params={{
							orderCostId: orderCostVO.orderCostId,
						}}
						request={async (params) => {
							const { data: orderCostVO } =
								await business.orderCost.showOrderCost({
									orderCostShowQry: params,
								});

							return {
								...orderCostVO,
								paidAmount: orderCostVO?.price,
							};
						}}
						trigger={
							<ButtonAccess
								key={'pay'}
								permission={'operation-order-cost-pay'}
								type={'link'}
								size={'small'}
							>
								付款
							</ButtonAccess>
						}
						onFinish={handleSubmit}
					>
						{/* 模块1：费用信息 */}
						<ProFormItem
							style={{
								width: '100%',
							}}
							label={'费用信息'}
						>
							<ProCard bordered>
								<Row gutter={[16, 16]}>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												订单信息
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{orderCostVO.orderVO
													? `${orderCostVO.orderVO.orderVehicle.dealerName} | 第 ${orderCostVO.orderVO.orderVehicle.vehicleNo || '暂无'} 车`
													: '-'}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												费用名称
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{orderCostVO.name || '-'}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												费用金额
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{formatCurrency(orderCostVO.price || 0)}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												负责人
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{orderCostVO.principal || '-'}
											</div>
										</div>
									</Col>
								</Row>
								<Row gutter={[16, 16]} style={{ marginTop: 16 }}>
									<Col span={12}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												付款公司
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{orderCostVO.orderCompany?.fullName || '-'}
											</div>
										</div>
									</Col>
									<Col span={12}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												费用归属
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{orderCostVO.belong === 'WORKER_TYPE'
													? '工人费用'
													: orderCostVO.belong === 'PRODUCTION_TYPE'
														? '生产费用'
														: orderCostVO.belong === 'DRIVER_TYPE'
															? '司机费用'
															: '其他'}
											</div>
										</div>
									</Col>
								</Row>
							</ProCard>
						</ProFormItem>

						{/* 模块2：本次付款 */}
						<ProFormMoney
							name="paidAmount"
							disabled={true}
							label={'付款金额'}
							placeholder={'请输入付款金额'}
							required={true}
							fieldProps={{
								precision: 2,
								min: 0.01,
								max: orderCostVO.price || 0,
							}}
							rules={[
								{
									required: true,
									message: '请输入付款金额',
								},
								{
									type: 'number',
									max: orderCostVO.price || 0,
									message: `付款金额不能超过费用金额 ${formatCurrency(
										orderCostVO.price || 0,
									)}`,
								},
							]}
						/>

						{/* 收款人 */}
						<ProFormText
							key={'payeeName'}
							disabled={true}
							name="payeeName"
							label={'收款人'}
							placeholder={'请输入收款人'}
							required={true}
							initialValue={orderCostVO.principal}
							rules={[
								{
									required: true,
									message: '请输入收款人',
								},
							]}
						/>

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

						{/* 上传付款凭证 */}
						<ProFormUploadMaterial
							key={'paidCredentials'}
							label={'付款凭证'}
							name={'paidCredentials'}
							fieldProps={{
								maxCount: 9,
							}}
						/>

						{/* 付款备注 */}
						<ProFormDependency key={'remark'} name={['remark']}>
							{({ remark }, form) => {
								return (
									<BizEditor
										key={'remark'}
										value={remark}
										onChange={(value) => {
											form.setFieldValue('remark', value);
										}}
										label={'付款备注'}
										name={'remark'}
										placeholder={'请输入付款备注'}
									/>
								);
							}}
						</ProFormDependency>
					</DrawerForm>
				);
			}}
		</RouteContext.Consumer>
	);
}
