/** 风险信号概览详情弹窗：与 viewRiskSignal 详情逻辑对齐的纯函数 */

/** 从概览/列表行解析详情接口 id */
export function resolveRiskSignalRowId(row) {
	if (!row || typeof row !== "object") {
		return "";
	}
	// 概览页通用接口 `/api/commonFeature/riskSignal/{moduleId}` 返回结构里，
	// 详情接口 getRiskSignalInfoById 需要的是 signalId（而非 orderId/reportId 等业务 id）。
	// 因此优先取 signalId；其次再取已映射的 id/riskId 等。
	const keys = ["signalId", "id", "riskId", "riskSignalId", "orderId"];
	for (const k of keys) {
		const v = row[k];
		if (v != null && String(v).trim() !== "") {
			return String(v).trim();
		}
	}
	return "";
}

/** PageLimit 列表项：领域标签（优先 domainNames，兼容 domainName / domains） */
export function parseRiskSignalTagList(item) {
	const names = item?.domainNames;
	if (names != null && String(names).trim() !== "") {
		return String(names)
			.split(/[,，、;；|]+/)
			.map((s) => s.trim())
			.filter(Boolean);
	}
	const dn = item?.domainName;
	if (dn != null && String(dn).trim() !== "") {
		return [String(dn).trim()];
	}
	const raw = item?.domains;
	if (Array.isArray(raw)) {
		return raw.map((d) => (typeof d === "string" ? d : d?.name)).filter(Boolean);
	}
	if (typeof raw === "string" && raw.trim()) {
		return raw.split(/[,，]/).map((s) => s.trim()).filter(Boolean);
	}
	return [];
}

/** 发布时间：YYYY-MM-DD HH:mm:ss →「2026年1月26日  00:00」；仅日期则「2026年1月26日」 */
export function formatRiskPublishDisplay(raw) {
	if (raw == null || raw === "") {
		return "";
	}
	const s = String(raw).trim();
	const dt = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})\s+(\d{1,2}):(\d{2})(?::(\d{2}))?/);
	if (dt) {
		const h = String(Number(dt[4])).padStart(2, "0");
		const mi = String(Number(dt[5])).padStart(2, "0");
		return `${Number(dt[1])}年${Number(dt[2])}月${Number(dt[3])}日  ${h}:${mi}`;
	}
	const m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})(?:$|[T\s])/);
	if (m) {
		return `${Number(m[1])}年${Number(m[2])}月${Number(m[3])}日`;
	}
	return s;
}

export function getEmptyRiskDetailPayload() {
	return {
		title: "",
		origin: "",
		time: "",
		dsc: "",
		tag: [],
		risktype: "",
		category: "",
		/** 风险方向（接口 direction，可多值）对应中文文案列表 */
		directionLabels: [],
		relationType: "",
		relationTitle: "",
		relationModelCode: "",
		relationReferedId: ""
	};
}

/** 风险信号详情接口 `direction` 字段 → 中文（与 `model` 的 0100/0101 含义不同，单独映射） */
export const RISK_SIGNAL_DIRECTION_LABEL_MAP = {
	"0100": "政策法规打压类风险",
	"0101": "核心自主可控性风险",
	"0102": "科技要素风险",
	"0103": "其他风险动向"
};

export function getRiskSignalDirectionLabel(code) {
	const c = String(code ?? "").trim();
	return RISK_SIGNAL_DIRECTION_LABEL_MAP[c] ?? "";
}

/** 解析接口 `direction`：支持数组、逗号/分号分隔字符串 */
export function parseRiskSignalDirectionCodes(raw) {
	if (raw == null) {
		return [];
	}
	if (Array.isArray(raw)) {
		return raw.map((x) => String(x ?? "").trim()).filter(Boolean);
	}
	const s = String(raw).trim();
	if (!s) {
		return [];
	}
	return s.split(/[,，、;；|]+/).map((x) => x.trim()).filter(Boolean);
}

/** 方向编码列表 → 去重后的中文标签（顺序：先 data 后 list 合并去重） */
export function buildRiskSignalDirectionLabels(codes) {
	if (!Array.isArray(codes) || !codes.length) {
		return [];
	}
	const seen = new Set();
	const labels = [];
	for (const code of codes) {
		const c = String(code ?? "").trim();
		if (!c || seen.has(c)) {
			continue;
		}
		seen.add(c);
		const lbl = getRiskSignalDirectionLabel(c);
		if (lbl) {
			labels.push(lbl);
		}
	}
	return labels;
}

/** 风险信号详情：model 字典编码 → 中文类型 */
export const RISK_SIGNAL_MODEL_LABEL_MAP = {
	"0100": "法案",
	"0101": "政令",
	"0102": "智库报告",
	"0103": "出口管制",
	"0104": "市场准入",
	"0105": "创新主体",
	"0106": "合作限制",
	"0107": "科研资助体系",
	"0108": "规则限制",
	"0109": "投融资限制",
	"01031": "实体清单",
	"01032": "商业管制清单",
	"01091": "特别指定国民清单",
	"01092": "涉军企业清单",
	"01041": "337调查",
	"01042": "232调查",
	"01043": "301调查"
};

export function getRiskSignalModelLabel(code) {
	const c = String(code ?? "").trim();
	return RISK_SIGNAL_MODEL_LABEL_MAP[c] ?? "";
}

/** 根据 model + referedId 解析新开页路由 */
export function resolveRiskSignalRelationRoute(modelCode, referedId) {
	const code = String(modelCode ?? "").trim();
	const id = String(referedId ?? "").trim();
	if (!id) {
		return null;
	}
	switch (code) {
		case "0100":
			return { path: "/billLayout/bill/introduction", query: { billId: id } };
		case "0101":
			return { path: "/decreeLayout/overview/introduction", query: { id } };
		case "0102":
			return { name: "ReportDetail", params: { id } };
		case "0103":
			return { path: "/exportControl", query: { id } };
		case "0104":
		case "01041":
		case "01042":
		case "01043":
			return { path: "/marketSingleCaseLayout/overview", query: { id } };
		case "0105": {
			const segs = id
				.split("/")
				.map((s) => s.trim())
				.filter(Boolean);
			if (segs.length >= 2) {
				return { name: "InnovativeInstitutions", params: { id: segs[0], type: segs[1] } };
			}
			return { name: "InnovativeInstitutions", params: { id, type: "0" } };
		}
		case "0106":
			return { path: "/cooperationRestrictions/detail", query: { id } };
		case "0107":
			return { path: "/exportControl/researchfunding", query: { id } };
		case "0108":
			return { path: "/exportControl/ruledetail", query: { id } };
		case "0109":
			return { path: "/finance", query: { id } };
		case "01031":
			return { path: "/exportControl/entityList", query: { sanTypeId: id } };
		case "01032":
			return { path: "/exportControl/commercialControlList", query: { sanTypeId: id } };
		case "01091":
			return { path: "/finance/singleSanction", query: { id } };
		case "01092":
			return { path: "/finance/cmccontrolList", query: { sanTypeId: id } };
		default:
			return null;
	}
}

/** 与详情弹窗标题区等级色块一致 */
export function getRiskDetailLevelModifier(level) {
	const t = String(level ?? "").trim();
	if (t === "status" || t.length <= 1) {
		return "lv4";
	}
	if (t.includes("特别重大")) {
		return "lv1";
	}
	if (t === "重大风险" || (t.includes("重大") && !t.includes("较大") && !t.includes("特别"))) {
		return "lv2";
	}
	if (t === "较大风险" || t.includes("较大")) {
		return "lv3";
	}
	if (t === "低风险") {
		return "lv5";
	}
	if (t === "一般风险" || !t || t === "暂无数据") {
		return "lv4";
	}
	return "lv4";
}

/** 与 `@/components/base/riskSignal` 左侧等级一致：空 / null 等展示「暂无数据」 */
export const RISK_SIGNAL_LIST_LEVEL_EMPTY_TEXT = "暂无数据";

/**
 * 列表行风险等级 → 弹窗标题区文案（null、空串与「暂无数值」等与列表「暂无数据」对齐）
 * @param {unknown} raw
 */
export function normalizeRiskSignalListLevelText(raw) {
	if (raw == null) {
		return RISK_SIGNAL_LIST_LEVEL_EMPTY_TEXT;
	}
	const s = String(raw).trim();
	if (s === "" || s === "null" || s === "undefined" || s === "暂无数值") {
		return RISK_SIGNAL_LIST_LEVEL_EMPTY_TEXT;
	}
	return s;
}

/**
 * 将概览页原始行转为详情接口合并用的兜底对象（优先已映射字段 title/time/risktype，再用字段别名）
 * @param {Record<string, unknown>} row
 * @param {{ nameField?: string; postDateField?: string; riskLevelField?: string }} fields
 */
export function buildListRowFallbackFromRawRow(row, fields) {
	if (!row || typeof row !== "object") {
		return {};
	}
	const nameField = fields?.nameField ?? "name";
	const postDateField = fields?.postDateField ?? "postDate";
	const riskLevelField = fields?.riskLevelField ?? "riskLevel";
	let title = "";
	if (row.title != null && String(row.title).trim() !== "") {
		title = String(row.title);
	} else if (row.titleZh != null && String(row.titleZh).trim() !== "") {
		title = String(row.titleZh);
	} else if (row[nameField] != null) {
		title = String(row[nameField]);
	}
	const time = String(row.time ?? row[postDateField] ?? row.postDate ?? "").trim();
	const risktype = String(row.risktype ?? row[riskLevelField] ?? row.riskLevel ?? "").trim();
	const origin = String(row.orgName ?? row.origin ?? "").trim();
	const dsc = String(row.summary ?? row.contentZh ?? row.description ?? row.dsc ?? row.content ?? "").trim();
	const category = String(row.typeName ?? row.module ?? row.category ?? "").trim();
	const direction = row.direction != null && row.direction !== "" ? row.direction : "";
	return {
		title,
		time,
		risktype,
		origin,
		dsc,
		tag: parseRiskSignalTagList(row),
		category,
		direction
	};
}

/**
 * 将 getRiskSignalInfoById 返回 data 转为详情 payload（listRow 为列表行兜底，形状同 buildListRowFallbackFromRawRow）
 * @param {Record<string, unknown>} data
 * @param {Record<string, unknown>} listRow
 */
export function buildRiskDetailPayloadFromApi(data, listRow) {
	if (!data || typeof data !== "object") {
		return getEmptyRiskDetailPayload();
	}
	const list = listRow && typeof listRow === "object" ? listRow : {};
	const postRaw = data.postDate ?? data.publishDate ?? data.time ?? "";
	const category =
		data.typeName ?? data.module ?? data.modle ?? data.riskCategory ?? "";
	const org = data.orgName != null && String(data.orgName).trim() !== "" ? String(data.orgName).trim() : "";
	// 相关模块类型：严格使用 data.model（0100/0101/0103...），与风险动向类型 data.direction(0100~0103) 语义不同
	const modelCode = data.model != null ? String(data.model).trim() : "";
	const referedRaw = data.referedId ?? data.referredId;
	const relationReferedId = referedRaw != null ? String(referedRaw).trim() : "";
	const modelLabel = getRiskSignalModelLabel(modelCode);
	const relationType = modelLabel ? `${modelLabel}-` : modelCode ? `${modelCode}-` : "";
	const relationTitle =
		data.modelTitle != null && String(data.modelTitle).trim() !== ""
			? String(data.modelTitle).trim()
			: "";
	const detailTags = parseRiskSignalTagList(data);
	const apiCategory = String(category).trim();
	const apiTime = formatRiskPublishDisplay(postRaw) || String(postRaw || "").trim();
	// 风险动向类型：严格使用 direction（0100~0103），支持多值
	const directionCodes = [
		...parseRiskSignalDirectionCodes(data.direction),
		...parseRiskSignalDirectionCodes(list.direction)
	];
	const directionLabels = buildRiskSignalDirectionLabels(directionCodes);
	return {
		title: data.title ?? list.title ?? "",
		category: apiCategory || String(list.category ?? "").trim(),
		directionLabels,
		time: apiTime || String(list.time ?? "").trim(),
		origin: org || list.origin || "",
		dsc: data.description ?? data.contentZh ?? data.summary ?? list.dsc ?? "",
		tag: detailTags.length ? detailTags : Array.isArray(list.tag) ? [...list.tag] : [],
		risktype: String(list.risktype ?? "").trim(),
		relationType,
		relationTitle,
		relationModelCode: modelCode,
		relationReferedId: relationReferedId
	};
}
