<template>
	<el-dialog v-model="visible" class="risk-signal-detail-dialog" modal-class="risk-signal-detail-modal" width="1280px"
		align-center :z-index="zIndex" :show-close="true" destroy-on-close @closed="handleClosed">
		<template #header>
			<img class="header-icon" :src="headerIconSrc" alt="" />
			<span v-if="listLevelText" class="risk-signal-detail-dialog__level" :class="listLevelModifierClass">{{
				listLevelText }}</span>
			<div v-if="bodyFromApi" class="risk-signal-detail-dialog__read-indicator">
				<el-icon v-if="riskDetailStatus === false" class="risk-signal-detail-dialog__header-badge-close">
					<Close />
				</el-icon>
				<img v-else-if="riskDetailStatus === true" class="risk-signal-detail-dialog__header-badge-read"
					:src="greenRightImg" alt="" />
				<span v-if="riskDetailStatus != null" class="read">{{ riskDetailStatus ? "已读" : "未读" }}</span>
			</div>
		</template>
		<div class="risk-signal-detail-dialog__main" v-loading="detailLoading">
			<div v-if="bodyFromApi">
				<div v-if="riskDetailItem.title" class="risk-signal-detail-dialog__body">
					<span class="risk-signal-detail-dialog__title">{{ riskDetailItem.title }}</span>
					<div v-if="riskDetailItem.directionLabels.length" class="risk-signal-detail-dialog__directions">
						<div v-for="(dirLabel, dirIndex) in riskDetailItem.directionLabels"
							:key="'overview-risk-detail-direction-' + dirIndex + '-' + dirLabel"
							class="risk-signal-detail-dialog__origin">{{ dirLabel }}</div>
					</div>
					<div class="risk-signal-detail-dialog__meta">
						<span>{{ metaLine }}</span>
						<div v-if="riskDetailItem.tag.length" class="risk-signal-detail-dialog__tags">
							<AreaTag v-for="(tag, index) in riskDetailItem.tag" :key="'overview-risk-detail-tag-' + index + '-' + tag"
								:tag-name="tag">{{ tag }}</AreaTag>
						</div>
					</div>
				</div>
				<div v-if="showRelationBar" class="risk-signal-detail-dialog_relation" @click="handleRelationClick">
					<div class="relation">
						<div class="logo">
							<img src="@/views/viewRiskSignal/assets/images/logo.png" alt="" />
						</div>
						<div class="name-text">{{ riskDetailItem.relationType }}</div>
						<div class="content-text">{{ riskDetailItem.relationTitle }}</div>
					</div>
					<div class="right-arrow">
						<img src="@/views/viewRiskSignal/assets/images/right-arrow.png" alt="" />
					</div>
				</div>
				<div class="risk-signal-detail-dialog__desc">{{ riskDetailItem.dsc }}</div>
			</div>
		</div>
		<template #footer>
			<el-button type="primary" class="risk-signal-detail-dialog__action-btn" :loading="confirmLoading"
				@click="handleConfirm">
				确定
			</el-button>
		</template>
	</el-dialog>
</template>

<script setup>
import { computed, nextTick, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import AreaTag from "@/components/base/AreaTag/index.vue";
import { ElMessage } from "element-plus";
import { Close } from "@element-plus/icons-vue";
import greenRightImg from "@/views/viewRiskSignal/assets/images/green-right.png";
import riskIconRed from "@/views/viewRiskSignal/assets/images/risk-icon-red.png";
import riskIconOrange from "@/views/viewRiskSignal/assets/images/risk-icon-orange.png";
import riskIconYellow from "@/views/viewRiskSignal/assets/images/risk-icon-yellow.png";
import riskIconGreen from "@/views/viewRiskSignal/assets/images/risk-icon-green.png";
import riskIconBlue from "@/views/viewRiskSignal/assets/images/risk-icon-blue.png";
import { getRiskSignalInfoById, updateRiskSignalStatus } from "@/api/riskSignal/index.js";
import {
	buildListRowFallbackFromRawRow,
	buildRiskDetailPayloadFromApi,
	getEmptyRiskDetailPayload,
	getRiskDetailLevelModifier,
	normalizeRiskSignalListLevelText,
	resolveRiskSignalRelationRoute,
	resolveRiskSignalRowId
} from "@/utils/riskSignalOverviewDetailHelpers.js";

const props = defineProps({
	/** 当前点击的列表行（建议先赋值再打开 v-model） */
	row: {
		type: Object,
		default: null
	},
	/** 与 RiskSignal 组件 name 一致 */
	nameField: {
		type: String,
		default: "name"
	},
	/** 与 RiskSignal 组件 postDate 一致 */
	postDateField: {
		type: String,
		default: "postDate"
	},
	/** 与 RiskSignal 组件 riskLevel 一致 */
	riskLevelField: {
		type: String,
		default: "riskLevel"
	},
	/** 与遮罩、弹窗层级一致，避免被大屏/轮播盖住 */
	zIndex: {
		type: Number,
		default: 20000
	}
});

const emit = defineEmits(["closed", "confirmed"]);

const visible = defineModel({ type: Boolean, default: false });

const router = useRouter();

const listLevelText = ref("");
const bodyFromApi = ref(false);
const detailLoading = ref(false);
const confirmLoading = ref(false);
const riskDetailCurrentId = ref(null);
const riskDetailStatus = ref(null);

const riskDetailItem = reactive(getEmptyRiskDetailPayload());

const assignRiskDetail = (val) => {
	riskDetailItem.title = val.title ?? "";
	riskDetailItem.origin = val.origin ?? "";
	riskDetailItem.time = val.time ?? "";
	riskDetailItem.dsc = val.dsc ?? "";
	riskDetailItem.tag = Array.isArray(val.tag) ? [...val.tag] : [];
	riskDetailItem.risktype = val.risktype ?? "";
	riskDetailItem.category = val.category ?? "";
	riskDetailItem.directionLabels = Array.isArray(val.directionLabels) ? [...val.directionLabels] : [];
	riskDetailItem.relationType = val.relationType ?? "";
	riskDetailItem.relationTitle = val.relationTitle ?? "";
	riskDetailItem.relationModelCode = val.relationModelCode ?? "";
	riskDetailItem.relationReferedId = val.relationReferedId ?? "";
};

const metaLine = computed(() => {
	const t = String(riskDetailItem.time ?? "").trim();
	const o = String(riskDetailItem.origin ?? "").trim();
	if (t && o) {
		return `${t}·${o}`;
	}
	return t || o;
});

const showRelationBar = computed(() => {
	const ti = String(riskDetailItem.relationTitle ?? "").trim();
	const ty = String(riskDetailItem.relationType ?? "").trim();
	const id = String(riskDetailItem.relationReferedId ?? "").trim();
	return Boolean(ti || ty || id);
});

const listLevelModifierClass = computed(
	() => `risk-signal-detail-dialog__level--${getRiskDetailLevelModifier(listLevelText.value)}`
);

const headerIconSrc = computed(() => {
	const lv = getRiskDetailLevelModifier(listLevelText.value);
	if (lv === "lv1") return riskIconRed;
	if (lv === "lv2") return riskIconOrange;
	if (lv === "lv3") return riskIconYellow;
	if (lv === "lv4") return riskIconGreen;
	return riskIconBlue;
});

const fieldMap = computed(() => ({
	nameField: props.nameField,
	postDateField: props.postDateField,
	riskLevelField: props.riskLevelField
}));

const resetState = () => {
	listLevelText.value = "";
	bodyFromApi.value = false;
	detailLoading.value = false;
	confirmLoading.value = false;
	riskDetailCurrentId.value = null;
	riskDetailStatus.value = null;
	assignRiskDetail(getEmptyRiskDetailPayload());
};

/** 拉取详情：标题区等级来自列表行；正文区仅接口成功后展示 */
const loadDetail = async () => {
	if (!visible.value || !props.row) {
		return;
	}
	const listFallback = buildListRowFallbackFromRawRow(props.row, fieldMap.value);
	listLevelText.value = normalizeRiskSignalListLevelText(listFallback.risktype);
	riskDetailCurrentId.value = null;
	riskDetailStatus.value = null;
	assignRiskDetail(getEmptyRiskDetailPayload());
	bodyFromApi.value = false;
	detailLoading.value = false;
	const id = resolveRiskSignalRowId(props.row);
	if (!id) {
		return;
	}
	detailLoading.value = true;
	try {
		const res = await getRiskSignalInfoById(id);
		if (res.code === 200 && res.data) {
			riskDetailCurrentId.value = id;
			riskDetailStatus.value = Boolean(res.data.status);
			assignRiskDetail(buildRiskDetailPayloadFromApi(res.data, listFallback));
			bodyFromApi.value = true;
		}
	} catch (error) {
		console.error("获取风险信号详情 error", error);
	} finally {
		detailLoading.value = false;
	}
};

watch(
	() => [visible.value, props.row],
	async () => {
		if (!visible.value) {
			resetState();
			return;
		}
		await nextTick();
		await loadDetail();
	}
);

const handleRelationClick = () => {
	const loc = resolveRiskSignalRelationRoute(
		riskDetailItem.relationModelCode,
		riskDetailItem.relationReferedId
	);
	if (!loc) {
		return;
	}
	const href = router.resolve(loc).href;
	window.open(href, "_blank");
};

const handleConfirm = async () => {
	const id = riskDetailCurrentId.value;
	if (id == null || id === "") {
		visible.value = false;
		return;
	}
	confirmLoading.value = true;
	try {
		const res = await updateRiskSignalStatus(String(id));
		if (res.code === 200) {
			ElMessage.success(typeof res.msg === "string" && res.msg.trim() ? res.msg : "操作成功");
			visible.value = false;
			emit("confirmed", { id: String(id) });
		} else {
			ElMessage.warning(typeof res.msg === "string" && res.msg.trim() ? res.msg : "操作失败");
		}
	} catch (error) {
		console.error("确定风险 UpdateStatu error", error);
		ElMessage.error("操作失败");
	} finally {
		confirmLoading.value = false;
	}
};

function handleClosed() {
	resetState();
	emit("closed");
}
</script>

<style lang="scss" src="./risk-signal-overview-detail-dialog.scss"></style>
