/** 附件1 租赁订单 — 品牌型号级联与行数据 */

import vehiclesData from '../vehicle-management/data/vehicles.json';

export var READY_VEHICLE_STATUS = '已备车';

/** 车辆库中暂无「已备车」时的原型兜底数据 */
export var LEASE_READY_VEHICLE_FALLBACK = [
	{ plateNo: '粤AGR8556', brand: '现代', model: '帕力安牌4.5吨冷链车', vehicleStatus: '已备车' },
	{ plateNo: '粤BHY6688', brand: '现代', model: '18吨氢燃料电池车', vehicleStatus: '已备车' },
	{ plateNo: '粤CSL9901', brand: '苏龙', model: '9.6米氢燃料电池车', vehicleStatus: '已备车' },
	{ plateNo: '粤DFC7722', brand: '跃进', model: '4.2米冷链车', vehicleStatus: '已备车' },
	{ plateNo: '粤EGT5533', brand: '宇通', model: '氢燃料电池客车', vehicleStatus: '已备车' },
];

export function getReadyVehicles() {
	var ready = vehiclesData.filter(function (vehicle) {
		return vehicle.vehicleStatus === READY_VEHICLE_STATUS && vehicle.plateNo;
	});
	return ready.length > 0 ? ready : LEASE_READY_VEHICLE_FALLBACK;
}

export function getReadyVehiclePlateOptions(brandModels) {
	var vehicles = getReadyVehicles();
	var models = normalizeBrandModels({ brandModels: brandModels });
	if (models.length > 0) {
		vehicles = vehicles.filter(function (vehicle) {
			return models.some(function (pair) {
				return vehicle.brand === pair[0] && vehicle.model === pair[1];
			});
		});
	}
	return vehicles.map(function (vehicle) {
		return {
			value: vehicle.plateNo,
			label: vehicle.plateNo,
		};
	});
}

export function parsePlateSearchText(text) {
	return String(text || '')
		.split(/[\n,，;；\s]+/)
		.map(function (item) { return item.trim().toUpperCase(); })
		.filter(Boolean);
}

export var LEASE_VEHICLE_BRAND_MODEL_CATALOG = [
	{ brand: '现代', models: ['帕力安牌4.5吨冷链车', '18吨氢燃料电池车', '9.6米厢式货车'] },
	{ brand: '苏龙', models: ['9.6米氢燃料电池车'] },
	{ brand: '飞驰', models: ['集卡头', '半挂车'] },
	{ brand: '跃进', models: ['4.2米冷链车'] },
	{ brand: '宇通', models: ['氢燃料电池客车'] },
];

export var PROVINCE_CITY_CASCADER_OPTIONS = [
	{
		value: '浙江省',
		label: '浙江省',
		children: [
			{ value: '嘉兴市', label: '嘉兴市' },
			{ value: '杭州市', label: '杭州市' },
			{ value: '宁波市', label: '宁波市' },
		],
	},
	{
		value: '上海市',
		label: '上海市',
		children: [{ value: '上海市', label: '上海市' }],
	},
	{
		value: '广东省',
		label: '广东省',
		children: [
			{ value: '广州市', label: '广州市' },
			{ value: '深圳市', label: '深圳市' },
		],
	},
	{
		value: '江苏省',
		label: '江苏省',
		children: [
			{ value: '南京市', label: '南京市' },
			{ value: '苏州市', label: '苏州市' },
		],
	},
];

export function buildBrandModelCascaderOptions() {
	return LEASE_VEHICLE_BRAND_MODEL_CATALOG.map(function (item) {
		return {
			value: item.brand,
			label: item.brand,
			children: item.models.map(function (model) {
				return { value: model, label: model };
			}),
		};
	});
}

export var PLATE_ACTUAL_DELIVERY = '以实际交付为准';

export var POA_MAX_DELEGATES = 5;

export function createEmptyLeaseOrderRow() {
	return {
		id: 'lo-' + Date.now() + '-' + Math.random().toString(36).slice(2, 7),
		brandModels: [],
		plateNos: [PLATE_ACTUAL_DELIVERY],
		rentServiceSubtotal: null,
		rent: null,
		serviceFee: null,
		deposit: null,
		extraServices: [],
		leasePeriodMonths: null,
		leasePeriodStart: null,
		leasePeriodEnd: null,
	};
}

export function normalizeBrandModels(row) {
	if (!row) return [];
	if (Array.isArray(row.brandModels) && row.brandModels.length) {
		return row.brandModels.filter(function (item) {
			return item && item.length >= 2 && item[0] && item[1];
		});
	}
	if (row.brandModel && row.brandModel.length >= 2) {
		return [row.brandModel.slice(0, 2)];
	}
	return [];
}

export function normalizePlateNos(row) {
	if (!row) return [PLATE_ACTUAL_DELIVERY];
	if (Array.isArray(row.plateNos) && row.plateNos.length) {
		return row.plateNos.filter(function (item) { return Boolean(item); });
	}
	if (row.plateNo) {
		return [row.plateNo];
	}
	return [PLATE_ACTUAL_DELIVERY];
}

export function formatBrandModelPair(brand, model) {
	if (!brand && !model) return '';
	if (!model) return brand;
	if (!brand) return model;
	return brand + '-' + model;
}

export function formatBrandModelsDisplay(brandModels) {
	return (brandModels || []).map(function (pair) {
		return formatBrandModelPair(pair[0], pair[1]);
	}).filter(Boolean);
}

export function getRowVehicleCountForPricing(row, order) {
	var plates = normalizePlateNos(row);
	var actualPlates = plates.filter(function (plate) {
		return plate !== PLATE_ACTUAL_DELIVERY;
	});
	if (actualPlates.length > 0) return actualPlates.length;
	if (plates.indexOf(PLATE_ACTUAL_DELIVERY) >= 0) {
		var rows = (order && order.rows) || [];
		var allActualOnly = rows.length > 0 && rows.every(function (item) {
			var itemPlates = normalizePlateNos(item);
			return itemPlates.length === 1 && itemPlates[0] === PLATE_ACTUAL_DELIVERY;
		});
		if (allActualOnly && rows.length === 1) {
			return calcInsuredVehicleCount(order) || 1;
		}
		return 1;
	}
	return 0;
}

export function calcInsuredVehicleCount(order) {
	var rows = (order && order.rows) || [];
	var autoFromPlates = 0;
	var hasActualOnly = false;
	rows.forEach(function (row) {
		var plates = normalizePlateNos(row);
		var actualPlates = plates.filter(function (plate) {
			return plate !== PLATE_ACTUAL_DELIVERY;
		});
		if (actualPlates.length > 0) {
			autoFromPlates += actualPlates.length;
			return;
		}
		if (plates.indexOf(PLATE_ACTUAL_DELIVERY) >= 0) {
			hasActualOnly = true;
		}
	});
	if (autoFromPlates > 0) return autoFromPlates;
	if (hasActualOnly) {
		var manual = order && order.insuredVehicleCount != null ? Number(order.insuredVehicleCount) : 0;
		if (Number.isFinite(manual) && manual > 0) return Math.floor(manual);
		return 1;
	}
	return 0;
}

export function isInsuredVehicleCountEditable(order) {
	var rows = (order && order.rows) || [];
	return rows.some(function (row) {
		var plates = normalizePlateNos(row);
		return plates.length === 1 && plates[0] === PLATE_ACTUAL_DELIVERY;
	}) && !rows.some(function (row) {
		return normalizePlateNos(row).some(function (plate) {
			return plate !== PLATE_ACTUAL_DELIVERY;
		});
	});
}

export function formatLeasePeriod(row) {
	if (!row) return '';
	if (row.leasePeriodMonths != null && row.leasePeriodMonths !== '') {
		return String(row.leasePeriodMonths) + ' 个月';
	}
	if (row.leasePeriodStart && row.leasePeriodEnd) {
		return row.leasePeriodStart + ' ~ ' + row.leasePeriodEnd;
	}
	return row.leasePeriodStart || row.leasePeriodEnd || '';
}

/** 租赁订单附加服务（按类目分组；fee 仅作原型参考，不在选择器中展示） */
export var LEASE_EXTRA_SERVICE_TREE = [
	{
		category: '交还车服务',
		items: [
			{ value: 'door-delivery', name: '送车服务费', fee: 300 },
			{ value: 'door-pickup', name: '接车服务费', fee: 300 },
		],
	},
	{
		category: '增值保障',
		items: [
			{ value: 'carefree-pack', name: '无忧包', fee: 500 },
			{ value: 'tire-insurance', name: '轮胎保', fee: 200 },
			{ value: 'maintenance-insurance', name: '养护保', fee: 180 },
		],
	},
	{
		category: '车辆加装',
		items: [
			{ value: 'tailgate', name: '尾板', fee: 150 },
		],
	},
];

export var LEASE_EXTRA_SERVICE_CATALOG = LEASE_EXTRA_SERVICE_TREE.reduce(function (list, group) {
	return list.concat(group.items);
}, []);

export function flattenExtraServiceOptions() {
	var options = [];
	LEASE_EXTRA_SERVICE_TREE.forEach(function (group) {
		group.items.forEach(function (item) {
			options.push({
				value: item.value,
				name: item.name,
				category: group.category,
			});
		});
	});
	return options;
}

export function matchExtraServiceOption(option, query) {
	var normalized = (query || '').trim().toLowerCase();
	if (!normalized) return true;
	return option.name.toLowerCase().indexOf(normalized) >= 0
		|| option.category.toLowerCase().indexOf(normalized) >= 0;
}

export function getExtraServiceCategoryByValue(value) {
	for (var i = 0; i < LEASE_EXTRA_SERVICE_TREE.length; i++) {
		var group = LEASE_EXTRA_SERVICE_TREE[i];
		for (var j = 0; j < group.items.length; j++) {
			if (group.items[j].value === value) {
				return group.category;
			}
		}
	}
	return '';
}

export var LEASE_EXTRA_SERVICE_OPTIONS = LEASE_EXTRA_SERVICE_CATALOG.map(function (item) {
	return {
		value: item.value,
		label: item.name,
	};
});

export function getExtraServiceFeeByValue(value) {
	for (var i = 0; i < LEASE_EXTRA_SERVICE_CATALOG.length; i++) {
		if (LEASE_EXTRA_SERVICE_CATALOG[i].value === value) {
			return LEASE_EXTRA_SERVICE_CATALOG[i].fee;
		}
	}
	return 0;
}

export function getExtraServiceByValue(value) {
	for (var i = 0; i < LEASE_EXTRA_SERVICE_CATALOG.length; i++) {
		if (LEASE_EXTRA_SERVICE_CATALOG[i].value === value) {
			return LEASE_EXTRA_SERVICE_CATALOG[i];
		}
	}
	return null;
}

export function getExtraServiceNames(selectedValues) {
	if (!selectedValues || !selectedValues.length) return [];
	return selectedValues.map(function (value) {
		var item = getExtraServiceByValue(value);
		return item ? item.name : value;
	});
}

export function normalizeExtraServices(row) {
	if (!row) return [];
	if (Array.isArray(row.extraServices)) return row.extraServices;
	if (row.extraService) return [row.extraService];
	return [];
}

export function sumExtraServiceFees(selectedValues) {
	if (!selectedValues || !selectedValues.length) return 0;
	var total = 0;
	selectedValues.forEach(function (value) {
		total += getExtraServiceFeeByValue(value);
	});
	return total;
}

export function formatExtraServicesDisplay(selectedValues) {
	if (!selectedValues || !selectedValues.length) return '';
	return getExtraServiceNames(selectedValues).join('、');
}

export function calcRentServiceSubtotal(rent, serviceFee, vehicleCount) {
	var serviceFeeTotal = serviceFee != null && serviceFee !== '' ? Number(serviceFee) : 0;
	if (!Number.isFinite(serviceFeeTotal)) serviceFeeTotal = 0;
	var hasRent = rent != null && rent !== '';
	if (!hasRent && serviceFeeTotal <= 0) return null;
	var rentVal = hasRent ? Number(rent) : 0;
	if (!Number.isFinite(rentVal)) return null;
	var count = vehicleCount != null && vehicleCount !== '' ? Number(vehicleCount) : 1;
	if (!Number.isFinite(count) || count <= 0) count = 1;
	return Math.round((rentVal + serviceFeeTotal) * count * 100) / 100;
}

export function getRowPlateCount(row) {
	var plates = normalizePlateNos(row);
	var actualPlates = plates.filter(function (plate) {
		return plate !== PLATE_ACTUAL_DELIVERY;
	});
	if (actualPlates.length > 0) return actualPlates.length;
	if (plates.indexOf(PLATE_ACTUAL_DELIVERY) >= 0) return 1;
	return 0;
}

export function calcLeaseOrderKpis(rows, order) {
	var rentServiceTaxTotal = 0;
	var depositTotal = 0;
	var hasSubtotal = false;
	var hasDeposit = false;
	(rows || []).forEach(function (row) {
		var vehicleCount = getRowVehicleCountForPricing(row, order || { rows: rows });
		var subtotal = calcRentServiceSubtotal(row.rent, row.serviceFee, vehicleCount);
		if (subtotal != null) {
			rentServiceTaxTotal += subtotal;
			hasSubtotal = true;
		}
		if (row.deposit != null && row.deposit !== '') {
			var depositVal = Number(row.deposit);
			if (Number.isFinite(depositVal)) {
				depositTotal += depositVal * vehicleCount;
				hasDeposit = true;
			}
		}
	});
	function roundMoney(amount) {
		return Math.round(amount * 100) / 100;
	}
	var monthlyTotal = hasSubtotal ? roundMoney(rentServiceTaxTotal) : null;
	return {
		rentServiceTaxTotal: monthlyTotal,
		depositTotal: hasDeposit ? roundMoney(depositTotal) : null,
		firstPeriodRentService: monthlyTotal,
	};
}

export function formatKpiAmount(value) {
	if (value == null || !Number.isFinite(value)) {
		return '0元';
	}
	return '¥' + value.toLocaleString('zh-CN', {
		minimumFractionDigits: 2,
		maximumFractionDigits: 2,
	});
}

export function countLeaseOrderRows(rows, order) {
	if (!rows || !rows.length) return 0;
	if (order) return calcInsuredVehicleCount(order);
	var total = 0;
	rows.forEach(function (row) {
		total += getRowPlateCount(row);
	});
	return total;
}

export function isDelegateRowStarted(row) {
	if (!row) return false;
	return Boolean((row.name || '').trim())
		|| Boolean((row.contact || '').trim())
		|| Boolean((row.idNumber || '').trim());
}

export function isDelegateRowComplete(row) {
	if (!row) return false;
	return Boolean((row.name || '').trim())
		&& Boolean((row.contact || '').trim())
		&& Boolean((row.idNumber || '').trim());
}

export function normalizeDelegateRows(delegates) {
	return (delegates || []).filter(isDelegateRowStarted);
}

export function createDefaultLeaseOrderState() {
	return {
		insuredVehicleCount: 1,
		thirdPartyLiabilityMillion: null,
		deliveryRegion: [],
		deliveryDate: null,
		rows: [createEmptyLeaseOrderRow()],
	};
}

/** @deprecated 使用 createDefaultLeaseOrderState */
export var DEFAULT_LEASE_ORDERS = createDefaultLeaseOrderState().rows;

/** 授权委托书 — 委托人行数据 */

export function createEmptyDelegateRow() {
	return {
		id: 'del-' + Date.now() + '-' + Math.random().toString(36).slice(2, 7),
		name: '',
		contact: '',
		idNumber: '',
	};
}

export function createDefaultPowerOfAttorneyState() {
	return {
		delegates: [createEmptyDelegateRow()],
	};
}
