/** 附件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(brandModel) {
	var vehicles = getReadyVehicles();
	if (brandModel && brandModel.length >= 2) {
		vehicles = vehicles.filter(function (vehicle) {
			return vehicle.brand === brandModel[0] && vehicle.model === brandModel[1];
		});
	}
	return vehicles.map(function (vehicle) {
		return {
			value: vehicle.plateNo,
			label: vehicle.plateNo,
		};
	});
}

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 function createEmptyLeaseOrderRow() {
	return {
		id: 'lo-' + Date.now() + '-' + Math.random().toString(36).slice(2, 7),
		brandModel: [],
		plateNo: '',
		rentServiceSubtotal: null,
		rent: null,
		deposit: null,
		extraServices: [],
		leasePeriodStart: null,
		leasePeriodEnd: null,
	};
}

export function formatLeasePeriod(row) {
	if (!row) return '';
	if (row.leasePeriodStart && row.leasePeriodEnd) {
		return row.leasePeriodStart + ' ~ ' + row.leasePeriodEnd;
	}
	return row.leasePeriodStart || row.leasePeriodEnd || '';
}

/** 租赁订单附加服务（服务项 + 月费） */
export var LEASE_EXTRA_SERVICE_CATALOG = [
	{ value: 'door-delivery', name: '送车服务费', fee: 300 },
	{ value: 'door-pickup', name: '接车服务费', fee: 300 },
	{ value: 'carefree-pack', name: '无忧包', fee: 500 },
	{ value: 'tire-insurance', name: '轮胎保', fee: 200 },
	{ value: 'maintenance-insurance', name: '养护保', fee: 180 },
	{ value: 'tailgate', name: '尾板', fee: 150 },
];

export var LEASE_EXTRA_SERVICE_OPTIONS = LEASE_EXTRA_SERVICE_CATALOG.map(function (item) {
	return {
		value: item.value,
		label: item.name + ' ¥' + item.fee + '/月',
	};
});

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 selectedValues.map(function (value) {
		for (var i = 0; i < LEASE_EXTRA_SERVICE_CATALOG.length; i++) {
			var item = LEASE_EXTRA_SERVICE_CATALOG[i];
			if (item.value === value) {
				return item.name + ' ¥' + item.fee;
			}
		}
		return value;
	}).join('、');
}

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

export function calcLeaseOrderKpis(rows) {
	var rentServiceTaxTotal = 0;
	var depositTotal = 0;
	var hasSubtotal = false;
	var hasDeposit = false;
	(rows || []).forEach(function (row) {
		var subtotal = calcRentServiceSubtotal(row.rent, normalizeExtraServices(row));
		if (subtotal != null) {
			rentServiceTaxTotal += subtotal;
			hasSubtotal = true;
		}
		if (row.deposit != null && row.deposit !== '') {
			var depositVal = Number(row.deposit);
			if (Number.isFinite(depositVal)) {
				depositTotal += depositVal;
				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) {
	if (!rows || !rows.length) return 0;
	return rows.length;
}

export function createDefaultLeaseOrderState() {
	return {
		insuredVehicleCount: null,
		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()],
	};
}
