import {
	ExpenseCostList,
	ExpenseProvisionList,
	PageContainer,
} from '@/components';
import { business } from '@/services';
import Icon from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Button, DatePicker, message, Popconfirm } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';

export default function Page() {
	const [loading, setLoading] = useState<boolean>(false);

	const [currentDate, setCurrentDate] = useState<string>(() => {
		return dayjs(new Date()).format('YYYY-MM-DD');
	});
	const [expenseRecord, setExpenseRecord] =
		useState<BusinessAPI.ExpenseRecordVO>();

	// 日期选择器相关状态
	const [datePickerOpen, setDatePickerOpen] = useState(false);

	// 数据变更检测相关状态
	const [originalData, setOriginalData] =
		useState<BusinessAPI.ExpenseRecordVO>(); // 原始数据
	const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false); // 是否有未保存的变更
	const [confirmVisible, setConfirmVisible] = useState(false); // 确认对话框状态
	const [pendingDate, setPendingDate] = useState<string>(''); // 待切换的日期

	const lastSaveTime = useRef<number>(Date.now()); // 最后保存时间，用于优化变更检测

	// 数据变更检测函数
	const hasDataChanged = (
		current: BusinessAPI.ExpenseRecordVO,
		original: BusinessAPI.ExpenseRecordVO,
	) => {
		if (!current || !original) return false;

		// 比较计提列表
		const currentProvisions = current.expenseProvisionList || [];
		const originalProvisions = original.expenseProvisionList || [];

		if (currentProvisions.length !== originalProvisions.length) return true;

		for (let i = 0; i < currentProvisions.length; i++) {
			const curr = currentProvisions[i];
			const orig = originalProvisions[i];
			if (
				curr.dealerName !== orig.dealerName ||
				curr.provisionAmount !== orig.provisionAmount ||
				curr.vehicleNo !== orig.vehicleNo ||
				curr.remark !== orig.remark
			) {
				return true;
			}
		}

		// 比较费用列表
		const currentCosts = current.expenseCostList || [];
		const originalCosts = original.expenseCostList || [];

		if (currentCosts.length !== originalCosts.length) return true;

		for (let i = 0; i < currentCosts.length; i++) {
			const curr = currentCosts[i];
			const orig = originalCosts[i];
			if (
				curr.costName !== orig.costName ||
				curr.expenseAmount !== orig.expenseAmount ||
				curr.remark !== orig.remark
			) {
				return true;
			}
		}

		return false;
	};

	// 检查数据变更的函数
	const checkForChanges = (newData: BusinessAPI.ExpenseRecordVO) => {
		console.log('newData:', newData);
		console.log('originalData:', originalData);
		if (originalData) {
			const changed = hasDataChanged(newData, originalData);
			console.log('数据变更:', changed);
			setHasUnsavedChanges(changed);
		} else if (newData) {
			setHasUnsavedChanges(true);
		} else if (!newData) {
			setHasUnsavedChanges(false);
		}
	};

	// 保存数据函数
	const saveCurrentData = async () => {
		if (expenseRecord) {
			try {
				// 这里添加实际的保存逻辑
				console.log('保存数据:', expenseRecord);
				const { success } = await business.expenseRecord.createExpenseRecord({
					...expenseRecord,
					recordDate: currentDate,
				});

				if (success) {
					// 保存成功后更新原始数据
					setOriginalData(JSON.parse(JSON.stringify(expenseRecord)));
					setHasUnsavedChanges(false);
					lastSaveTime.current = Date.now();
				}

				return success;
			} catch (error) {
				console.error('保存数据失败:', error);
				return false;
			}
		}
		return false;
	};

	const loadExpenseData = async (currentDate: string) => {
		try {
			setLoading(true);
			const { data: expenseRecord, success } =
				await business.expenseRecord.showExpenseRecord({
					expenseRecordShowQry: {
						recordDate: currentDate, // 使用今天的日期
					},
				});

			if (success) {
				if (expenseRecord) {
					setExpenseRecord(expenseRecord);
					// 保存原始数据用于变更检测
					setOriginalData(JSON.parse(JSON.stringify(expenseRecord)));
				} else {
					setExpenseRecord(undefined);
					setOriginalData(undefined);
				}
				// 重置未保存变更状态
				setHasUnsavedChanges(false);
				lastSaveTime.current = Date.now();
			}
		} catch (error) {
			console.error('加载费用数据失败:', error);
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		if (currentDate) {
			loadExpenseData(currentDate).then();
		}
	}, [currentDate]);

	function onchange(expenseRecord: BusinessAPI.ExpenseRecordVO) {
		setExpenseRecord((prev) => {
			const totalProvision =
				expenseRecord.expenseProvisionList?.reduce(
					(sum, provision) => sum + (provision.provisionAmount || 0),
					0,
				) || 0;

			const totalExpense =
				expenseRecord.expenseCostList?.reduce(
					(sum, expense) => sum + (expense.expenseAmount || 0),
					0,
				) || 0;

			const newExpenseRecord = {
				...prev!,
				...expenseRecord,
				totalProvision: totalProvision,
				totalExpense: totalExpense,
				dailyProfit: totalProvision - totalExpense,
			};

			// 检查数据变更
			setTimeout(() => {
				checkForChanges(newExpenseRecord);
			}, 100);

			return newExpenseRecord;
		});
	}

	// 日期选择确认处理
	const handleDateSelect = (date: dayjs.Dayjs | null) => {
		if (date) {
			const newDate = date.format('YYYY-MM-DD');

			// 如果没有未保存变更，直接切换日期
			if (!hasUnsavedChanges) {
				setCurrentDate(newDate);
			} else {
				// 有未保存变更时，保存待切换日期，显示确认对话框
				setPendingDate(newDate);
				setConfirmVisible(true);
			}
		}
		setDatePickerOpen(false);
	};

	return (
		<PageContainer
			permission={''}
			fieldProps={{
				loading,
				extra: (
					<>
						<DatePicker
							open={datePickerOpen}
							value={currentDate ? dayjs(currentDate) : null}
							onOpenChange={setDatePickerOpen}
							onChange={handleDateSelect}
							disabledDate={(current) => {
								return current && current > dayjs().endOf('day');
							}}
							picker="date"
						/>
						<Button
							size="middle"
							block
							type="primary"
							onClick={async () => {
								const saveSuccess = await saveCurrentData();
								if (saveSuccess) {
									message.success('保存成功');
								} else {
									message.error('保存失败');
								}
							}}
							disabled={!hasUnsavedChanges}
						>
							保存数据 {hasUnsavedChanges ? '(有变更)' : ''}
						</Button>
					</>
				),
			}}
		>
			<ProCard ghost={true} gutter={24} direction={'column'}>
				<ExpenseProvisionList
					expenseRecord={expenseRecord}
					onChange={onchange}
				/>

				<ExpenseCostList expenseRecord={expenseRecord} onChange={onchange} />

				<div className="overflow-hidden rounded-md bg-white shadow-md">
					<div className={'flex flex-col gap-2.5 p-2.5'}>
						<div className="text-neutral-darkest text-base font-medium">
							今日利润计算
						</div>
						<div className="flex items-center justify-between">
							<div className="text-neutral-darker text-sm">计提总金额</div>
							<div className="text-neutral-darkest text-sm font-medium">
								¥{(expenseRecord?.totalProvision || 0).toLocaleString()}
							</div>
						</div>
						<div className="flex items-center justify-between">
							<div className="text-neutral-darker text-sm">花销小计</div>
							<div className="text-neutral-darkest text-sm font-medium">
								¥
								{expenseRecord?.expenseCostList
									?.reduce(
										(sum, expense) => sum + (expense.expenseAmount || 0),
										0,
									)
									.toFixed(2)}
							</div>
						</div>
						<div className="border-t border-gray-200 pt-2.5">
							<div className="flex items-center justify-between">
								<div className="text-neutral-darker text-sm">日常利润</div>
								<div
									className={`text-sm font-medium ${(expenseRecord?.dailyProfit || 0) >= 0 ? 'text-green-600' : 'text-red-600'}`}
								>
									¥{(expenseRecord?.dailyProfit || 0).toLocaleString()}
								</div>
							</div>
							<div className={'flex flex-row items-center'}>
								<Icon
									name={
										(expenseRecord?.dailyProfit || 0) >= 0
											? 'arrow-up'
											: 'arrow-down'
									}
									color={
										(expenseRecord?.dailyProfit || 0) >= 0 ? 'green' : 'red'
									}
									className="mr-1"
									size={14}
								/>
								<div
									className={`text-sm font-medium ${(expenseRecord?.dailyProfit || 0) >= 0 ? 'text-green-600' : 'text-red-600'}`}
								>
									{(expenseRecord?.dailyProfit || 0) >= 0
										? '盈利状态'
										: '亏损状态'}
								</div>
							</div>
						</div>
					</div>
				</div>
			</ProCard>
			{/* 日期切换确认对话框 */}
			<Popconfirm
				open={confirmVisible}
				title="未保存的变更"
				description="当前日期有未保存的变更，是否要保存这些更改？"
				onCancel={() => {
					// 取消操作，停留在当前日期
					setConfirmVisible(false);
					setPendingDate('');
				}}
				onConfirm={async () => {
					// 保存并切换
					setConfirmVisible(false);
					const saveSuccess = await saveCurrentData();
					if (saveSuccess && pendingDate) {
						setCurrentDate(pendingDate);
						setPendingDate('');
					}
				}}
				okText="保存并切换"
				cancelText="取消"
			/>
		</PageContainer>
	);
}
