/**
 * 章节 HTML 合并 / 拆分（合同模板管理 ↔ 租赁合同预览共用）
 */

export var DOCUMENT_SECTION_TABS = [
	{ key: 'main', label: '合同主体' },
	{ key: 'lease_order', label: '租赁订单', markers: ['<b>1：租赁订单 </b>', '附件 1：租赁订单', '附件1：租赁订单'] },
	{ key: 'vehicle_cost', label: '车辆产生的费用', markers: ['附件2:车辆产生的费用', '附件2：车辆产生的费用', '<b>附件2：车辆产生的费用</b>'] },
	{ key: 'safety_notice', label: '安全责任告知书', markers: ['附件3:安全责任告知书', '附件3：安全责任告知书', '<b>附件3：安全责任告知书</b>'] },
	{ key: 'dynamic_supervision', label: '重型普通货运车辆租赁动态监管责任告知与确认书', markers: ['附件4：重型普通货运车辆租赁动态监管责任告知与确认书', '附件4:'] },
	{ key: 'safety_commitment', label: '安全责任承诺书', markers: ['<b>附件5：</b>', '<b>安全责任承诺书</b></p><p class="ct-word-body">为严格落实', '附件5：', '附件5:'] },
	{ key: 'vehicle_spec', label: '车辆使用规范和驾驶员要求', markers: ['<b>附件6：车辆使用规范和驾驶员要求</b>', '附件6：车辆使用规范和驾驶员要求', '附件6:'] },
	{ key: 'authorization', label: '授权委托书', markers: ['font: 28.0px Times; color: #000000"><b>授权委托书</b>', '<b>授权委托书</b></p><p class="ct-word-body">致：', '<b>授权委托书</b><b></b></p><p class="ct-word-body">致：'] },
	{ key: 'safety_agreement', label: '安全责任协议', markers: ['data-risk-redline="1"><b>安全责任协议</b></span></p>', '<b>安全责任协议</b></p><p class="ct-word-body"><br></p><p class="ct-word-body"><b>甲方（出租方）：</b>', '<b>安全责任协议</b></p><p class="ct-word-body"><br></p>'] },
];

export function emptySectionMap() {
	var map = {};
	DOCUMENT_SECTION_TABS.forEach(function (tab) { map[tab.key] = ''; });
	return map;
}

export function mergeMonolithicHtml(sectionMap) {
	var map = sectionMap || {};
	var out = String(map.main || '');
	DOCUMENT_SECTION_TABS.slice(1).forEach(function (tab) {
		var chunk = map[tab.key];
		if (chunk) out += String(chunk);
	});
	return out;
}

function isValidSectionMarkerMatch(source, index, marker) {
	if (index < 0) return false;
	var text = String(source || '');
	var before = text.slice(Math.max(0, index - 8), index);
	var after = text.slice(index, index + String(marker || '').length + 12);
	if (/[（(]$/.test(before)) return false;
	if (/、$/.test(before)) return false;
	if (/^《/.test(after.slice(String(marker).length))) return false;
	var nearby = text.slice(Math.max(0, index - 24), index + String(marker).length + 24);
	if (/详见.{0,20}附件/.test(nearby)) return false;
	if (/以附件/.test(nearby)) return false;
	if (String(marker).length <= 10 && !/<b>/.test(nearby)) return false;
	return true;
}

function findFirstMarker(source, markers) {
	var text = String(source || '');
	var best = -1;
	(markers || []).forEach(function (marker) {
		var from = 0;
		while (from < text.length) {
			var idx = text.indexOf(marker, from);
			if (idx < 0) break;
			if (isValidSectionMarkerMatch(text, idx, marker)) {
				if (best < 0 || idx < best) best = idx;
				break;
			}
			from = idx + 1;
		}
	});
	return best;
}

function findSafeHtmlSplitIndex(source, index) {
	var text = String(source || '');
	var candidates = ['</p>', '</table>', '</div>'];
	var best = index;
	candidates.forEach(function (tag) {
		var idx = text.lastIndexOf(tag, index);
		if (idx >= 0) {
			var end = idx + tag.length;
			if (end > best) best = end;
		}
	});
	return best > 0 ? best : index;
}

/** 将整份 Word HTML 按附件标记拆为章节 map（种子数据 / 导入用） */
export function splitMonolithicHtml(html) {
	var source = String(html || '');
	var result = emptySectionMap();
	if (!source.trim()) return result;
	var splitPoints = [];
	DOCUMENT_SECTION_TABS.slice(1).forEach(function (tab) {
		var idx = findFirstMarker(source, tab.markers || [tab.label]);
		if (idx >= 0) splitPoints.push({ key: tab.key, index: idx });
	});
	splitPoints.sort(function (a, b) { return a.index - b.index; });
	var deduped = [];
	splitPoints.forEach(function (point) {
		if (!deduped.length || deduped[deduped.length - 1].index !== point.index) deduped.push(point);
	});
	result.main = deduped.length ? source.slice(0, findSafeHtmlSplitIndex(source, deduped[0].index)) : source;
	for (var i = 0; i < deduped.length; i++) {
		var start = deduped[i].index;
		var end = i + 1 < deduped.length ? findSafeHtmlSplitIndex(source, deduped[i + 1].index) : source.length;
		result[deduped[i].key] = source.slice(start, end);
	}
	return result;
}
