/**
 * 车辆氢费明细 ↔ 加氢站模块 共享数据桥
 * 加氢站侧氢费/对账/加氢记录均读取本 Store；车辆氢费明细页运行时同步全量台账行。
 */

var H2_RECONCILE_RECONCILED = 'reconciled';
var H2_RECONCILE_PENDING = 'pending';

var H2_STATION_CODE_MAP = {
	'嘉兴加氢站（一期）': 'JX-H2-001',
	'杭州临平加氢站': 'HZ-H2-002',
	'上海宝山加氢站': 'SH-H2-003',
	'苏州工业园区备用站': 'SZ-H2-004'
};

/** 与车辆氢费明细、加氢站模块对齐的 canonical seed（10 条） */
var H2_CANONICAL_LEDGER_SEED = [
	{ key: 'rf-1', id: 'rf-1', stationId: 'JX-H2-001', stationName: '嘉兴加氢站（一期）', hydrogenTime: '2026-05-28 10:21:08', plateNo: '浙A12345F', customerName: '嘉兴市鑫峤供应链科技有限公司', hydrogenKg: 12.5, costUnitPrice: 42.5, costTotal: 531.25, customerUnitPrice: 45, customerAmount: 562.5, settlementStatus: 'customer', mileageKm: 128560, creatorName: '张三', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-2', id: 'rf-2', stationId: 'JX-H2-001', stationName: '嘉兴加氢站（一期）', hydrogenTime: '2026-05-26 14:08:33', plateNo: '浙A67890F', customerName: '浙江绿运物流有限公司', hydrogenKg: 10.0, costUnitPrice: 42.5, costTotal: 425.0, customerUnitPrice: 45, customerAmount: 450.0, settlementStatus: 'internal', mileageKm: 95230, creatorName: '李四', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-3', id: 'rf-3', stationId: 'JX-H2-001', stationName: '嘉兴加氢站（一期）', hydrogenTime: '2026-05-22 09:15:00', plateNo: '浙A88888F', customerName: '嘉兴市鑫峤供应链科技有限公司', hydrogenKg: 18.3, costUnitPrice: 42.5, costTotal: 777.75, customerUnitPrice: 45, customerAmount: 823.5, settlementStatus: 'customer_self', mileageKm: 201880, creatorName: '王静', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-4', id: 'rf-4', stationId: 'JX-H2-001', stationName: '嘉兴加氢站（一期）', hydrogenTime: '2026-05-18 16:42:11', plateNo: '浙A03561F', customerName: '嘉兴港务氢能运输队', hydrogenKg: 15.6, costUnitPrice: 42.5, costTotal: 663.0, customerUnitPrice: 45, customerAmount: 702.0, settlementStatus: 'customer', mileageKm: 167420, creatorName: '张三', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-5', id: 'rf-5', stationId: 'HZ-H2-002', stationName: '杭州临平加氢站', hydrogenTime: '2026-05-30 09:30:22', plateNo: '浙B23456F', customerName: '杭州临平城配中心', hydrogenKg: 15.3, costUnitPrice: 43.0, costTotal: 657.9, customerUnitPrice: 46, customerAmount: 703.8, settlementStatus: 'internal', mileageKm: 143200, creatorName: '赵敏', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-6', id: 'rf-6', stationId: 'HZ-H2-002', stationName: '杭州临平加氢站', hydrogenTime: '2026-05-27 18:10:05', plateNo: '浙B99999F', customerName: '浙江氢运科技', hydrogenKg: 18.2, costUnitPrice: 43.0, costTotal: 782.6, customerUnitPrice: 46, customerAmount: 837.2, settlementStatus: 'customer_self', mileageKm: 189650, creatorName: '陈浩', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-7', id: 'rf-7', stationId: 'HZ-H2-002', stationName: '杭州临平加氢站', hydrogenTime: '2026-05-24 11:05:40', plateNo: '浙B58888F', customerName: '杭州临平城配中心', hydrogenKg: 11.8, costUnitPrice: 43.0, costTotal: 507.4, customerUnitPrice: 46, customerAmount: 542.8, settlementStatus: 'customer', mileageKm: 110340, creatorName: '李四', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-8', id: 'rf-8', stationId: 'SH-H2-003', stationName: '上海宝山加氢站', hydrogenTime: '2026-04-20 16:45:18', plateNo: '沪A88888F', customerName: '上海羚牛氢运', hydrogenKg: 8.0, costUnitPrice: 44.0, costTotal: 352.0, customerUnitPrice: 47, customerAmount: 376.0, settlementStatus: 'internal', mileageKm: 88420, creatorName: '王静', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-9', id: 'rf-9', stationId: 'SH-H2-003', stationName: '上海宝山加氢站', hydrogenTime: '2026-04-08 09:12:55', plateNo: '沪BDB9161F', customerName: '宝山园区试运车队', hydrogenKg: 9.5, costUnitPrice: 44.0, costTotal: 418.0, customerUnitPrice: 47, customerAmount: 446.5, settlementStatus: 'customer_self', mileageKm: 76500, creatorName: '张三', reconcileStatus: H2_RECONCILE_RECONCILED },
	{ key: 'rf-10', id: 'rf-10', stationId: 'SZ-H2-004', stationName: '苏州工业园区备用站', hydrogenTime: '2026-03-15 10:00:00', plateNo: '苏E33333F', customerName: '苏州试运客户', hydrogenKg: 6.2, costUnitPrice: 41.0, costTotal: 254.2, customerUnitPrice: 44, customerAmount: 272.8, settlementStatus: 'customer', mileageKm: 45210, creatorName: '赵敏', reconcileStatus: H2_RECONCILE_PENDING }
];

function h2BridgeCloneRows(rows) {
	return (rows || []).map(function (r) { return Object.assign({}, r); });
}

function h2BridgeFormatDateTime(value) {
	if (!value) return '';
	if (typeof value === 'string') return value;
	if (value.format) return value.format('YYYY-MM-DD HH:mm:ss');
	return String(value);
}

function h2BridgeMatchStatementPatch(row, patch) {
	if (patch.ledgerId && row.ledgerSyncId && patch.ledgerId === row.ledgerSyncId) return true;
	var rowTime = h2BridgeFormatDateTime(row.hydrogenTime);
	var patchTime = String(patch.hydrogenTime || '');
	return (row.stationName || '') === (patch.stationName || '')
		&& (row.plateNo || '') === (patch.plateNo || '')
		&& (rowTime === patchTime || String(row.hydrogenTime || '') === patchTime);
}

function h2BridgeApplyStatementPatches(rows, patches) {
	if (!patches || !patches.length) return h2BridgeCloneRows(rows);
	return (rows || []).map(function (r) {
		var patch = null;
		var i;
		for (i = 0; i < patches.length; i++) {
			if (h2BridgeMatchStatementPatch(r, patches[i])) {
				patch = patches[i];
				break;
			}
		}
		if (!patch) return r;
		return Object.assign({}, r, {
			statementPatched: true,
			reconcileDate: patch.reconcileDate,
			receiptDate: patch.receiptDate,
			stationPaymentStatus: patch.paymentStatus || 'paid',
			paymentStatus: patch.paymentStatus || 'paid',
			reconciledAt: patch.reconcileDate
		});
	});
}

function h2BridgeBuildInitialRows() {
	var patches = (typeof window !== 'undefined' && window.H2_STATION_STATEMENT_LEDGER_UPDATES) || [];
	return h2BridgeApplyStatementPatches(h2BridgeCloneRows(H2_CANONICAL_LEDGER_SEED), patches);
}

function h2BridgeCreateStore() {
	var listeners = [];
	var state = { rows: h2BridgeBuildInitialRows() };

	function notify() {
		listeners.forEach(function (fn) {
			try { fn(state.rows); } catch (_e) { /* noop */ }
		});
	}

	return {
		getRows: function () { return h2BridgeCloneRows(state.rows); },
		setRows: function (rows) {
			state.rows = h2BridgeCloneRows(rows);
			notify();
		},
		subscribe: function (fn) {
			listeners.push(fn);
			return function () {
				listeners = listeners.filter(function (item) { return item !== fn; });
			};
		},
		applyPatches: function (patches) {
			if (!patches || !patches.length) return;
			state.rows = h2BridgeApplyStatementPatches(state.rows, patches);
			notify();
		}
	};
}

function h2BridgeMapToRefuelRecord(row) {
	var costTotal = row.costTotal != null ? row.costTotal : row.costAmount;
	return {
		id: row.id || row.key,
		stationName: row.stationName,
		hydrogenTime: h2BridgeFormatDateTime(row.hydrogenTime),
		plateNo: row.plateNo,
		customerName: row.customerName,
		hydrogenKg: row.hydrogenKg,
		costUnitPrice: row.costUnitPrice,
		costAmount: costTotal,
		customerUnitPrice: row.customerUnitPrice,
		customerAmount: row.customerAmount,
		settlementStatus: row.settlementStatus,
		orderNo: row.orderNo,
		mileageKm: row.mileageKm
	};
}

function h2BridgeBuildRefuelOrderNo(record, index) {
	if (record && record.orderNo) return record.orderNo;
	var idPart = String((record && record.id) || (record && record.key) || '').replace(/\D/g, '') || String(index + 1);
	return 'JQ' + idPart.padStart(4, '0') + String(100 + index);
}

function h2BridgeMapToStationLedgerRow(row, index) {
	var costTotal = row.costTotal != null ? row.costTotal : row.costAmount;
	var isReconciled = row.reconcileStatus === H2_RECONCILE_RECONCILED;
	return {
		id: row.id || row.key || ('ledger-' + index),
		stationName: row.stationName,
		hydrogenTime: h2BridgeFormatDateTime(row.hydrogenTime),
		plateNo: row.plateNo,
		customerName: row.customerName,
		hydrogenKg: row.hydrogenKg,
		costUnitPrice: row.costUnitPrice,
		costTotal: costTotal,
		settlementStatus: row.settlementStatus,
		orderNo: h2BridgeBuildRefuelOrderNo(row, index),
		reconcileStatus: row.reconcileStatus || (isReconciled ? H2_RECONCILE_RECONCILED : H2_RECONCILE_PENDING),
		statementRecordId: row.statementRecordId || null,
		reconcileDate: row.reconcileDate || null,
		receiptDate: row.receiptDate || null,
		paymentStatus: row.paymentStatus || (isReconciled ? 'unpaid' : null)
	};
}

function h2BridgeMapToHrRecord(row, index, fillerNames) {
	var fillers = fillerNames || ['张三', '李四', '王静', '赵敏', '陈浩'];
	return {
		id: row.id || row.key || ('hr-' + (index + 1)),
		hydrogenTime: h2BridgeFormatDateTime(row.hydrogenTime),
		plateNo: row.plateNo,
		hydrogenKg: row.hydrogenKg,
		customerAmount: row.customerAmount,
		mileageKm: row.mileageKm,
		fillerName: row.creatorName || fillers[index % fillers.length],
		settlementStatus: row.settlementStatus,
		stationName: row.stationName,
		stationCode: row.stationId || H2_STATION_CODE_MAP[row.stationName] || ''
	};
}

function h2BridgeMapToOrderRecord(row, index) {
	var time = h2BridgeFormatDateTime(row.hydrogenTime);
	return {
		id: index + 1,
		stationCode: row.stationId || H2_STATION_CODE_MAP[row.stationName] || '',
		stationName: row.stationName,
		time: time.length >= 16 ? time.slice(0, 16) : time,
		plateNo: (row.plateNo || '').replace(/F$/, ''),
		amountKg: row.hydrogenKg,
		amountYuan: row.customerAmount
	};
}

function h2BridgeGetStore() {
	if (typeof window === 'undefined') return null;
	if (!window.H2_VEHICLE_LEDGER_STORE) {
		window.H2_VEHICLE_LEDGER_STORE = h2BridgeCreateStore();
	}
	return window.H2_VEHICLE_LEDGER_STORE;
}

function h2BridgeEnsureApi() {
	if (typeof window === 'undefined') return;
	var store = h2BridgeGetStore();
	var existing = window.H2_VEHICLE_LEDGER_API || {};
	window.H2_VEHICLE_LEDGER_API = Object.assign({}, existing, {
		getRows: function () { return store.getRows(); },
		syncRows: function (rows) {
			if (!rows) return;
			store.setRows(rows);
		},
		applyPatches: function (patches) {
			store.applyPatches(patches);
			if (typeof existing.applyPatches === 'function') {
				existing.applyPatches(patches);
			}
		}
	});
}

function h2BridgeGetAllRefuelRecords() {
	var store = h2BridgeGetStore();
	return store.getRows().map(h2BridgeMapToRefuelRecord);
}

function h2BridgeGetRefuelRecordsByStation(stationName) {
	var name = String(stationName || '').trim();
	return h2BridgeGetAllRefuelRecords()
		.filter(function (r) { return (r.stationName || '') === name; })
		.sort(function (a, b) {
			return String(b.hydrogenTime || '').localeCompare(String(a.hydrogenTime || ''));
		});
}

function h2BridgeBuildStationLedgerStore() {
	var store = h2BridgeGetStore();
	return store.getRows().map(h2BridgeMapToStationLedgerRow);
}

function h2BridgeGetHrRecords(fillerNames) {
	var store = h2BridgeGetStore();
	return store.getRows().map(function (row, index) {
		return h2BridgeMapToHrRecord(row, index, fillerNames);
	});
}

function h2BridgeGetOrderRecords() {
	var store = h2BridgeGetStore();
	return store.getRows().map(h2BridgeMapToOrderRecord);
}

function h2BridgeGetStationList() {
	var seen = {};
	var list = [];
	h2BridgeGetStore().getRows().forEach(function (row) {
		var code = row.stationId || H2_STATION_CODE_MAP[row.stationName];
		if (!code || seen[code]) return;
		seen[code] = true;
		list.push({ value: code, label: row.stationName });
	});
	return list;
}

function h2BridgeInit() {
	h2BridgeEnsureApi();
	var store = h2BridgeGetStore();
	if (typeof window !== 'undefined') {
		window.H2VehicleLedgerBridge = {
			getRows: function () { return store.getRows(); },
			getAllRefuelRecords: h2BridgeGetAllRefuelRecords,
			getRefuelRecordsByStation: h2BridgeGetRefuelRecordsByStation,
			buildStationLedgerStore: h2BridgeBuildStationLedgerStore,
			getHrRecords: h2BridgeGetHrRecords,
			getOrderRecords: h2BridgeGetOrderRecords,
			getStationList: h2BridgeGetStationList,
			subscribe: function (fn) { return store.subscribe(fn); }
		};
	}
	return store;
}

h2BridgeInit();

export {
	H2_CANONICAL_LEDGER_SEED,
	H2_STATION_CODE_MAP,
	h2BridgeInit,
	h2BridgeGetStore,
	h2BridgeGetAllRefuelRecords,
	h2BridgeGetRefuelRecordsByStation,
	h2BridgeBuildStationLedgerStore,
	h2BridgeGetHrRecords,
	h2BridgeGetOrderRecords,
	h2BridgeGetStationList
};
