import {
	BizEditor,
	ButtonAccess,
	InsertPosition,
	OrderSupplierInvoiceList,
	SupplierFarmerList,
} from '@/components';
import OrderSupplierModal from '@/components/Order/OrderSupplierModal';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { formLayout } from '@/utils/formLayout';
import { useIntl } from '@@/exports';
import { PlusOutlined } from '@ant-design/icons';
import {
	DrawerForm,
	ProCard,
	ProFormDependency,
	ProFormItem,
	ProFormSelect,
	ProFormText,
	RouteContext,
	RouteContextType,
} from '@ant-design/pro-components';
import { Button, Col, Image, message, Row, Table, Tag } from 'antd';
import { useState } from 'react';

export interface IPaymentTaskCreateProps {
	onFinish: () => void;
	insertPosition?: InsertPosition;
}

export default function PaymentTaskCreate(props: IPaymentTaskCreateProps) {
	const { onFinish } = props;
	const intl = useIntl();
	const intlPrefix = 'paymentTask';
	const [selectedSupplier, setSelectedSupplier] =
		useState<BusinessAPI.SupplierVO | null>(null);
	const [selectedOrderSupplierList, setSelectedOrderSupplierList] = useState<
		BusinessAPI.OrderSupplierVO[]
	>([]);
	const [orderSupplierModalOpen, setOrderSupplierModalOpen] = useState(false);

	// 计算总金额和订单数量
	const totalAmount = selectedOrderSupplierList.reduce(
		(sum, order) =>
			sum + (order.invoiceAmount || 0) - (order.depositAmount || 0),
		0,
	);
	const orderCount = selectedOrderSupplierList.length;

	const handleReset = () => {
		setSelectedSupplier(null);
		setSelectedOrderSupplierList([]);
	};
	console.log(selectedOrderSupplierList);

	const handleSubmit = async (formData: any) => {
		if (!selectedSupplier) {
			message.error('请选择付款瓜农');
			return false;
		}

		if (selectedOrderSupplierList.length === 0) {
			message.error('请选择付款车次');
			return false;
		}

		// 构建付款任务数据
		const paymentTaskData: BusinessAPI.PaymentTaskCreateCmd = {
			taskName: formData.taskName,
			taskType: 'MELON_FARMER', // 瓜农付款任务
			paymentCode: `PAY-${Date.now()}`, // 生成付款编码
			targetId: selectedSupplier.supplierId,
			totalAmount: totalAmount,
			paidAmount: 0,
			state: 'PENDING', // 待付款任务
			orderCount: orderCount,
			remark: formData.remark,
			orderSupplierVOList: selectedOrderSupplierList,
		};

		const { success } =
			await business.paymentTask.createPaymentTask(paymentTaskData);

		if (success) {
			message.success(
				intl.formatMessage({
					id: intlPrefix + '.modal.create.success',
				}),
			);
			handleReset();
			onFinish();
		}

		return success;
	};

	// 获取瓜农列表
	const loadSupplierList = async () => {
		const { data } = await business.supplier.listSupplier({
			supplierListQry: {
				type: 'FARMER',
				status: true,
			},
		});
		return (data || []).map((supplier: BusinessAPI.SupplierVO) => ({
			label: supplier.name,
			value: supplier.supplierId,
			...supplier,
		}));
	};

	return (
		<>
			<RouteContext.Consumer>
				{(value: RouteContextType) => {
					const { isMobile } = value;
					return (
						<DrawerForm<any>
							title={intl.formatMessage({
								id: intlPrefix + '.modal.create.title',
							})}
							{...formLayout(isMobile)}
							width={isMobile ? '100%' : '85%'}
							drawerProps={{
								destroyOnHidden: true,
								onClose: handleReset,
							}}
							trigger={
								<ButtonAccess
									key={'createPaymentTask'}
									permission={'operation-paymentTask-create'}
									type={'primary'}
									size={'middle'}
									icon={<PlusOutlined />}
								>
									{intl.formatMessage({
										id: intlPrefix + '.modal.create.button',
									})}
								</ButtonAccess>
							}
							onFinish={handleSubmit}
						>
							{/* 选择瓜农 */}
							<ProFormSelect
								name="supplierId"
								label={intl.formatMessage({
									id: intlPrefix + '.form.supplier.label',
								})}
								placeholder={intl.formatMessage({
									id: intlPrefix + '.form.supplier.placeholder',
								})}
								required={true}
								showSearch={true}
								request={loadSupplierList}
								fieldProps={{
									labelInValue: true,
								}}
								rules={[
									{
										required: true,
										message: intl.formatMessage({
											id: intlPrefix + '.form.supplier.required',
										}),
									},
								]}
								onChange={(value: any) => {
									setSelectedSupplier(value);
									// 切换瓜农时清空已选订单
									setSelectedOrderSupplierList([]);
								}}
							/>

							{/* 显示瓜农信息 */}
							{selectedSupplier && (
								<ProFormItem
									label={'瓜农信息'}
									style={{
										width: '100%',
									}}
								>
									<ProCard bordered style={{ marginBottom: 16 }}>
										<Row gutter={[16, 16]}>
											<Col span={6}>
												<div>
													<div style={{ color: '#999', marginBottom: 4 }}>
														姓名
													</div>
													<div style={{ fontWeight: 'bold' }}>
														{selectedSupplier.name}
													</div>
												</div>
											</Col>
											<Col span={6}>
												<div>
													<div style={{ color: '#999', marginBottom: 4 }}>
														手机号
													</div>
													<div style={{ fontWeight: 'bold' }}>
														{selectedSupplier.phone}
													</div>
												</div>
											</Col>
											<Col span={6}>
												<div>
													<div style={{ color: '#999', marginBottom: 4 }}>
														银行卡号
													</div>
													<div style={{ fontWeight: 'bold' }}>
														{selectedSupplier.bankCard}
													</div>
												</div>
											</Col>
											<Col span={6}>
												<div>
													<div style={{ color: '#999', marginBottom: 4 }}>
														微信收款码
													</div>
													<div style={{ fontWeight: 'bold' }}>
														{selectedSupplier.wechatQr ? (
															<Image
																width={80}
																alt={'暂无'}
																src={selectedSupplier.wechatQr}
															/>
														) : (
															<div>暂无</div>
														)}
													</div>
												</div>
											</Col>
										</Row>
									</ProCard>
								</ProFormItem>
							)}

							{/* 选择车次 */}
							{selectedSupplier && (
								<ProFormItem
									label={'付款车次'}
									style={{
										width: '100%',
									}}
								>
									<ProCard
										bordered
										title="选择需要付款的车次"
										extra={
											<Button
												type="primary"
												size="middle"
												onClick={() => setOrderSupplierModalOpen(true)}
											>
												添加车次
											</Button>
										}
										style={{ marginBottom: 16 }}
									>
										{selectedOrderSupplierList.length > 0 ? (
											<OrderSupplierInvoiceList
												rowKey="orderSupplierId"
												dataSource={selectedOrderSupplierList}
												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',
														key: 'invoiceSn',
														render: (
															supplierInvoiceVO: BusinessAPI.SupplierInvoiceVO,
														) => {
															return <a>{supplierInvoiceVO.invoiceSn}</a>;
														},
													},
													// 开票状态（自开票，代开票，未开票）
													{
														title: '开票状态',
														key: 'invoiceStatus',
														render: (record: BusinessAPI.OrderSupplierVO) => {
															let invoiceStatus = 'NOT_INVOICE';
															if (record.invoiceUpload && record.invoiceId) {
																if (
																	record.supplierId ===
																	record.supplierInvoiceVO?.supplierId
																) {
																	invoiceStatus = 'SELF';
																}
																if (
																	record.supplierId !==
																	record.supplierInvoiceVO?.supplierId
																) {
																	invoiceStatus = 'AGENT';
																}
															} else {
																invoiceStatus = 'NOT_INVOICE';
															}

															switch (invoiceStatus) {
																case 'SELF':
																	return '自开票';
																case 'AGENT':
																	return '代开票';
																case 'NOT_INVOICE':
																	return '未开票';
																default:
															}
														},
													},
													{
														title: '操作',
														key: 'action',
														render: (record: BusinessAPI.OrderSupplierVO) => (
															<Button
																type="link"
																danger
																onClick={() => {
																	setSelectedOrderSupplierList(
																		selectedOrderSupplierList.filter(
																			(item) =>
																				item.orderSupplierId !==
																				record.orderSupplierId,
																		),
																	);
																}}
															>
																移除
															</Button>
														),
													},
												]}
												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>
													);
												}}
											/>
										) : (
											<div
												style={{
													textAlign: 'center',
													padding: '40px 0',
													color: '#999',
												}}
											>
												暂无数据，请点击「添加车次」按钮添加
											</div>
										)}
									</ProCard>
								</ProFormItem>
							)}

							{/* 任务信息 */}
							{selectedOrderSupplierList.length > 0 && (
								<>
									<ProFormItem label={'任务摘要'} style={{ width: '100%' }}>
										{/* 任务摘要 */}
										<ProCard bordered style={{ marginBottom: 16 }}>
											<Row gutter={[16, 16]}>
												<Col span={6}>
													<div>
														<div style={{ color: '#999', marginBottom: 4 }}>
															付款瓜农
														</div>
														<div style={{ fontWeight: 'bold' }}>
															{selectedSupplier?.name}
														</div>
													</div>
												</Col>
												<Col span={6}>
													<div>
														<div style={{ color: '#999', marginBottom: 4 }}>
															车次数量
														</div>
														<div style={{ fontWeight: 'bold' }}>
															{orderCount} 车
														</div>
													</div>
												</Col>
												<Col span={6}>
													<div>
														<div style={{ color: '#999', marginBottom: 4 }}>
															付款总额
														</div>
														<div
															style={{ fontWeight: 'bold', color: '#ff4d4f' }}
														>
															{formatCurrency(totalAmount)}
														</div>
													</div>
												</Col>
												<Col span={6}>
													<div>
														<div style={{ color: '#999', marginBottom: 4 }}>
															付款状态
														</div>
														<div>
															<Tag color="orange">待付款</Tag>
														</div>
													</div>
												</Col>
											</Row>
										</ProCard>
									</ProFormItem>

									{/* 任务名称和备注 */}
									<ProFormText
										name="taskName"
										label={intl.formatMessage({
											id: intlPrefix + '.form.taskName.label',
										})}
										placeholder={intl.formatMessage({
											id: intlPrefix + '.form.taskName.placeholder',
										})}
										required={true}
										rules={[
											{
												required: true,
												message: intl.formatMessage({
													id: intlPrefix + '.form.taskName.required',
												}),
											},
										]}
									/>
									<ProFormDependency key={'remark'} name={['remark']}>
										{({ remark }, form) => {
											return (
												<BizEditor
													key={'remark'}
													value={remark}
													onChange={(value) => {
														form.setFieldValue('remark', value);
													}}
													label={intl.formatMessage({
														id: intlPrefix + '.form.remark.label',
													})}
													name={'remark'}
													placeholder={intl.formatMessage({
														id: intlPrefix + '.form.remark.placeholder',
													})}
												/>
											);
										}}
									</ProFormDependency>
								</>
							)}
						</DrawerForm>
					);
				}}
			</RouteContext.Consumer>

			{/* 选择车次模态框 */}
			<OrderSupplierModal
				open={orderSupplierModalOpen}
				title="选择需要付款的车次"
				type="checkbox"
				selectedList={selectedOrderSupplierList}
				onFinish={(orderSupplierList) => {
					// 过滤掉已经选择的订单
					const newOrders = orderSupplierList.filter(
						(item) =>
							!selectedOrderSupplierList.some(
								(selected) => selected.orderSupplierId === item.orderSupplierId,
							),
					);
					setSelectedOrderSupplierList([
						...selectedOrderSupplierList,
						...newOrders,
					]);
					setOrderSupplierModalOpen(false);
				}}
				onCancel={() => setOrderSupplierModalOpen(false)}
				params={{
					type: 'FARMER',
					isPaid: false,
					supplierId: selectedSupplier?.supplierId,
				}}
				tips="请选择该瓜农未付款的车次"
				num={999}
			/>
		</>
	);
}
