<template>
	<view class="hazard-process-chain-panel">
		<view v-if="loading" class="loading-wrap">
			<text class="loading-text">{{ labels.loading }}</text>
		</view>

		<view v-else-if="historyList.length === 0" class="empty-wrap">
			<text class="empty-text">{{ labels.empty }}</text>
		</view>

		<view v-else class="detail-body" :style="detailBodyStyle">
			<scroll-view
				class="steps-card"
				scroll-y
				:style="scrollAreaStyle"
				:show-scrollbar="false"
				:scroll-into-view="stepScrollIntoView"
				:scroll-with-animation="true"
			>
				<view
					v-for="(item, index) in historyList"
					:key="'step-' + index"
					:id="'process-step-' + index"
					class="step-item"
					:class="{ 'step-item--active': activeIndex === index }"
					@tap="scrollToNode(index)"
				>
					<view class="step-track">
						<view
							class="step-dot"
							:class="{ 'step-dot--active': activeIndex === index }"
						>
							<image
								class="step-icon"
								:src="getProcessStepIconPath(item, activeIndex === index)"
								mode="aspectFit"
							/>
						</view>
						<text
							class="step-label"
							:class="{ 'step-label--active': activeIndex === index }"
						>{{ item.nodeName }}</text>
						<view v-if="index < historyList.length - 1" class="step-line"></view>
					</view>
				</view>
			</scroll-view>

			<scroll-view
				class="content-column content-scroll"
				scroll-y
				:style="scrollAreaStyle"
				:show-scrollbar="false"
				:scroll-into-view="contentScrollIntoView"
				:scroll-with-animation="scrollWithAnimation"
				@scroll="onContentScroll"
				@scrolltolower="onScrollToLower"
			>
				<view
					v-for="(item, index) in historyList"
					:key="'node-' + index"
					:id="'process-node-' + index"
					class="node-section"
					:class="{ 'node-section--last': index === historyList.length - 1 }"
				>
					<view
						class="detail-card-shell"
						:class="{ 'detail-card-shell--active': activeIndex === index }"
					>
					<view class="detail-card">
						<view class="card-header-v2">
							<view class="card-header-main">
								<template v-if="item.completed">
									<text class="operator">{{ item.titlePrefix }}{{ labels.personnelSuffix }}{{ fieldText(item, item.operator) }}</text>
									<text class="time">{{ fieldText(item, item.time) }}</text>
								</template>
								<template v-else>
									<text class="operator">{{ labels.nextHandlerLabel }}{{ fieldText(item, item.currentHandlerName) }}</text>
									<text class="time status-pending">{{ labels.statusSuffix }}{{ PENDING_LABEL }}</text>
								</template>
							</view>
							<view
								v-if="item.completed && item.type === 'add' && item.content.levelName"
								:class="['level-badge', getLevelTagClass(item.content)]"
							>
								{{ item.content.levelName }}
							</view>
						</view>
						<view v-if="item.completed" class="card-divider"></view>

						<view v-if="item.completed" class="card-body">
							<block v-if="item.type === 'add'">
								<view class="detail-row-v2">
									<text class="label">{{ labels.hazardCode }}</text>
									<text class="value">{{ fieldText(item, item.content.code) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.hazardTitle }}</text>
									<text class="value">{{ fieldText(item, item.content.title) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.checkSource }}</text>
									<text class="value">{{ fieldText(item, item.content.source) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.hazardSource }}</text>
									<text class="value">{{ fieldText(item, item.content.hazardSourceName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.hazardArea }}</text>
									<text class="value">{{ fieldText(item, item.content.areaName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.address }}</text>
									<text class="value">{{ fieldText(item, item.content.address) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.hazardLevel }}</text>
									<view class="value">
										<view :class="['level-tag', getLevelTagClass(item.content)]">
											{{ fieldText(item, item.content.levelName) }}
										</view>
									</view>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.hazardTag }}</text>
									<text class="value">{{ fieldText(item, item.content.tagName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.description }}</text>
									<text class="value">{{ fieldText(item, item.content.description) }}</text>
								</view>
								<view
									v-if="(item.content.attachments && item.content.attachments.length) || !item.completed"
									class="detail-row-v2 detail-row-v2--block"
								>
									<text class="label">{{ labels.hazardAttachments }}</text>
									<view v-if="item.content.attachments && item.content.attachments.length" class="attachment-list">
										<image
											v-for="(file, idx) in item.content.attachments"
											:key="idx"
											class="attachment-img"
											:src="resolveFileUrl(file.filePath)"
											mode="aspectFill"
											@tap="previewImages(item.content.attachments, idx)"
											@load="scheduleMeasureLayout"
										/>
									</view>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.legalBasis }}</text>
									<text class="value">{{ fieldText(item, item.content.legalBasis) }}</text>
								</view>
							</block>

							<block v-else-if="item.type === 'assign'">
								<view class="detail-row-v2">
									<text class="label">{{ labels.assigneeName }}</text>
									<text class="value">{{ fieldText(item, item.content.assigneeName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.assignDeadline }}</text>
									<text class="value">{{ fieldText(item, item.content.deadline) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.assignStatus }}</text>
									<text class="value">{{ fieldText(item, item.content.assignStatusName) }}</text>
								</view>
							</block>

							<block v-else-if="item.type === 'rectify'">
								<view class="detail-row-v2">
									<text class="label">{{ labels.rectifyStatus }}</text>
									<text class="value">{{ fieldText(item, item.content.rectifyStatusName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.rectifyPlan }}</text>
									<text class="value">{{ fieldText(item, item.content.rectifyPlan) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.rectifyResult }}</text>
									<text class="value">{{ fieldText(item, item.content.rectifyResult) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.rectifyMeasures }}</text>
									<text class="value">{{ fieldText(item, item.content.rectificationMeasures) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.controlMeasures }}</text>
									<text class="value">{{ fieldText(item, item.content.controlMeasures) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.rectifierName }}</text>
									<text class="value">{{ fieldText(item, item.content.rectifierName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.managerNames }}</text>
									<text class="value">{{ fieldText(item, item.content.managerNames) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.memberNames }}</text>
									<text class="value">{{ fieldText(item, item.content.memberNames) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.planCost }}</text>
									<text class="value">{{ formatCost(item.content.planCost, item.completed) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.actualCost }}</text>
									<text class="value">{{ formatCost(item.content.actualCost, item.completed) }}</text>
								</view>
								<view
									v-if="(item.content.attachments && item.content.attachments.length) || !item.completed"
									class="detail-row-v2 detail-row-v2--block"
								>
									<text class="label">{{ labels.rectifyAttachments }}</text>
									<view v-if="item.content.attachments && item.content.attachments.length" class="attachment-list">
										<template v-for="(file, idx) in item.content.attachments" :key="idx">
											<image
												v-if="file.fileType === 'image' || !file.fileType"
												class="attachment-img"
												:src="resolveFileUrl(file.filePath)"
												mode="aspectFill"
												@tap="previewImages(item.content.attachments, idx)"
												@load="scheduleMeasureLayout"
											/>
											<text v-else class="file-link">{{ file.fileName || labels.attachmentFallback }}</text>
										</template>
									</view>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
								<view v-if="item.content.signPath || !item.completed" class="detail-row-v2 detail-row-v2--block">
									<text class="label">{{ labels.rectifySign }}</text>
									<image
										v-if="item.content.signPath"
										class="sign-img"
										:src="resolveFileUrl(item.content.signPath)"
										mode="aspectFit"
										@tap="previewSingle(item.content.signPath)"
										@load="scheduleMeasureLayout"
									/>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
							</block>

							<block v-else-if="item.type === 'verify' || item.type === 'writeoff_approve'">
								<view class="detail-row-v2">
									<text class="label">{{ labels.verifyResult }}</text>
									<text
										v-if="item.completed && item.content.resultName"
										class="result-tag"
										:class="item.content.resultName === labels.pass ? 'result-tag--pass' : 'result-tag--fail'"
									>
										{{ item.content.resultName }}
									</text>
									<text v-else class="value value--pending">{{ fieldText(item, item.content.resultName) }}</text>
								</view>
								<view v-if="item.content.remark || !item.completed" class="detail-row-v2">
									<text class="label">{{ labels.verifyRemark }}</text>
									<text class="value">{{ fieldText(item, item.content.remark) }}</text>
								</view>
								<view
									v-if="(item.content.attachments && item.content.attachments.length) || !item.completed"
									class="detail-row-v2 detail-row-v2--block"
								>
									<text class="label">{{ labels.verifyAttachments }}</text>
									<view v-if="item.content.attachments && item.content.attachments.length" class="attachment-list">
										<template v-for="(file, idx) in item.content.attachments" :key="idx">
											<image
												v-if="file.fileType === 'image' || !file.fileType"
												class="attachment-img"
												:src="resolveFileUrl(file.filePath)"
												mode="aspectFill"
												@tap="previewImages(item.content.attachments, idx)"
												@load="scheduleMeasureLayout"
											/>
											<text v-else class="file-link">{{ file.fileName || labels.attachmentFallback }}</text>
										</template>
									</view>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
								<view v-if="item.content.signPath || !item.completed" class="detail-row-v2 detail-row-v2--block">
									<text class="label">{{ labels.verifySign }}</text>
									<image
										v-if="item.content.signPath"
										class="sign-img"
										:src="resolveFileUrl(item.content.signPath)"
										mode="aspectFit"
										@tap="previewSingle(item.content.signPath)"
										@load="scheduleMeasureLayout"
									/>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
							</block>

							<block v-else-if="item.type === 'writeoff_apply'">
								<view class="detail-row-v2">
									<text class="label">{{ labels.writeoffDeadline }}</text>
									<text class="value">{{ fieldText(item, item.content.rectifyDeadline) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.responsibleDept }}</text>
									<text class="value">{{ fieldText(item, item.content.responsibleDeptName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.responsiblePerson }}</text>
									<text class="value">{{ fieldText(item, item.content.responsiblePerson) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.mainTreatment }}</text>
									<text class="value">{{ fieldText(item, item.content.mainTreatmentContent) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.treatmentResult }}</text>
									<text class="value">{{ fieldText(item, item.content.treatmentResult) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.selfVerify }}</text>
									<text class="value">{{ fieldText(item, item.content.selfVerifyContent) }}</text>
								</view>
								<view v-if="item.content.signPath || !item.completed" class="detail-row-v2 detail-row-v2--block">
									<text class="label">{{ labels.applySign }}</text>
									<image
										v-if="item.content.signPath"
										class="sign-img"
										:src="resolveFileUrl(item.content.signPath)"
										mode="aspectFit"
										@tap="previewSingle(item.content.signPath)"
										@load="scheduleMeasureLayout"
									/>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
							</block>

							<block v-else-if="item.type === 'approval'">
								<view class="detail-row-v2">
									<text class="label">{{ labels.approvalOpinion }}</text>
									<text
										v-if="item.completed && item.content.approveTypeName"
										class="result-tag"
										:class="item.content.pass ? 'result-tag--pass' : 'result-tag--fail'"
									>
										{{ item.content.approveTypeName }}
									</text>
									<text v-else class="value value--pending">{{ fieldText(item, item.content.approveTypeName) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.approvalComment }}</text>
									<text class="value" :class="{ 'value--pending': isPendingText(item, item.content.comment) }">{{ fieldText(item, item.content.comment) }}</text>
								</view>
								<view class="detail-row-v2">
									<text class="label">{{ labels.smsReminder }}</text>
									<text class="value">
										<template v-if="item.content.sendMsgFlag != null">{{ item.content.sendMsgFlag ? labels.yes : labels.no }}</template>
										<text v-else class="value--pending">{{ fieldText(item, '') }}</text>
									</text>
								</view>
								<view v-if="item.content.signPath || !item.completed" class="detail-row-v2 detail-row-v2--block">
									<text class="label">{{ labels.approvalSign }}</text>
									<image
										v-if="item.content.signPath"
										class="sign-img"
										:src="resolveFileUrl(item.content.signPath)"
										mode="aspectFit"
										@tap="previewSingle(item.content.signPath)"
										@load="scheduleMeasureLayout"
									/>
									<text v-else class="value value--pending">{{ fieldText(item, '') }}</text>
								</view>
							</block>
						</view>
					</view>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
</template>

<script setup>
import { computed, toRefs, watch } from 'vue';
import { toImageUrl } from '@/request/request.js';
import { getProcessStepIconPath, PENDING_LABEL, resolveFieldDisplay } from './processChain.js';
import { CHAIN_LABELS, LEVEL_NAME_CLASS_MAP } from './processChainLabels.js';
import { useProcessChainScroll } from './useProcessChainScroll.js';

const labels = CHAIN_LABELS;

const props = defineProps({
	chainData: {
		type: Object,
		default: () => ({})
	},
	loading: {
		type: Boolean,
		default: false
	},
	bodyHeight: {
		type: Number,
		default: 0
	}
});

const { chainData, loading } = toRefs(props);

const {
	historyList,
	activeIndex,
	contentScrollIntoView,
	stepScrollIntoView,
	scrollWithAnimation,
	onContentScroll,
	onScrollToLower,
	scrollToNode,
	scheduleMeasureLayout
} = useProcessChainScroll(chainData, loading);

const scrollAreaStyle = computed(() => {
	const height = props.bodyHeight > 0 ? props.bodyHeight : 400;
	return { height: `${height}px` };
});

const detailBodyStyle = computed(() => {
	const height = props.bodyHeight > 0 ? props.bodyHeight : 400;
	return { height: `${height}px` };
});

watch(
	() => props.bodyHeight,
	(height) => {
		if (height > 0) {
			scheduleMeasureLayout();
			setTimeout(scheduleMeasureLayout, 100);
		}
	}
);

const LEVEL_CLASS_MAP = {
	2: 'level-normal',
	3: 'level-major'
};

const getLevelTagClass = (content) => {
	const level = content?.level;
	const levelName = content?.levelName;
	if (level != null && LEVEL_CLASS_MAP[level]) {
		return LEVEL_CLASS_MAP[level];
	}
	if (levelName && LEVEL_NAME_CLASS_MAP[levelName]) {
		return LEVEL_NAME_CLASS_MAP[levelName];
	}
	return '';
};

const resolveFileUrl = (path) => toImageUrl(path);

const fieldText = (item, value) => resolveFieldDisplay(value, item.completed);

const isPendingText = (item, value) => fieldText(item, value) === PENDING_LABEL;

const formatCost = (cost, completed = true) => {
	if (cost == null || cost === '') return resolveFieldDisplay('', completed);
	const num = Number(cost);
	if (Number.isNaN(num)) return resolveFieldDisplay('', completed);
	return `${num} ${labels.yuan}`;
};

const previewSingle = (path) => {
	const url = resolveFileUrl(path);
	if (!url) return;
	uni.previewImage({ current: url, urls: [url] });
};

const previewImages = (attachments, index) => {
	const urls = (attachments || [])
		.filter((f) => f.fileType === 'image' || !f.fileType)
		.map((f) => resolveFileUrl(f.filePath))
		.filter(Boolean);
	if (!urls.length) return;
	uni.previewImage({ current: urls[index] || urls[0], urls });
};
</script>

<style lang="scss" scoped>
.hazard-process-chain-panel {
	flex: 1;
	min-height: 0;
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	overflow: hidden;
}

.loading-wrap,
.empty-wrap {
	flex: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	min-height: 0;
}

.loading-text,
.empty-text {
	font-size: 28rpx;
	color: #909399;
}

.detail-body {
	display: flex;
	gap: 20rpx;
	align-items: stretch;
	overflow: hidden;
	box-sizing: border-box;
}

.steps-card {
	width: 148rpx;
	flex-shrink: 0;
	background: #fff;
	border-radius: 20rpx;
	box-sizing: border-box;
}

.step-item {
	padding: 0 8rpx;
}

.step-track {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 24rpx 0 0;
}

.step-dot {
	width: 66rpx;
	height: 66rpx;
	border-radius: 50%;
	background: #f3f3f3;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: background 0.2s;
}

.step-dot--active {
	background: #2667e9;
}

.step-icon {
	width: 36rpx;
	height: 36rpx;
}

.step-label {
	margin-top: 10rpx;
	font-size: 20rpx;
	color: #999;
	line-height: 1.3;
	text-align: center;
	word-break: break-all;
}

.step-label--active {
	color: #2667e9;
	font-weight: 600;
}

.step-line {
	width: 0;
	height: 36rpx;
	margin: 8rpx 0;
	border-left: 2rpx dashed #dcdfe6;
}

.content-column {
	flex: 1;
	width: 0;
	min-height: 0;
	box-sizing: border-box;
}

.content-scroll {
	width: 100%;
	box-sizing: border-box;
}

.node-section {
	box-sizing: border-box;
	padding: 0;
	margin-bottom: 24rpx;
}

.node-section--last {
	padding-bottom: 40rpx;
	margin-bottom: 0;
}

.detail-card-shell {
	border-radius: 22rpx;
	padding: 2rpx;
	background: transparent;
	transition: background 0.3s ease, box-shadow 0.3s ease;
}

.detail-card-shell--active {
	background: linear-gradient(
		145deg,
		rgba(4, 108, 234, 0.48) 0%,
		rgba(38, 103, 233, 0.3) 50%,
		rgba(33, 88, 200, 0.16) 100%
	);
	box-shadow: 0 8rpx 24rpx rgba(38, 103, 233, 0.12);
}

.detail-card {
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	padding: 28rpx 38rpx;
	box-sizing: border-box;
}

.card-header-v2 {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 16rpx;
	padding: 0;
}

.card-header-main {
	flex: 1;
	min-width: 0;
}

.operator {
	font-size: 28rpx;
	font-weight: 600;
	color: #303133;
	line-height: 1.5;
	word-break: break-all;
}

.time {
	display: block;
	margin-top: 8rpx;
	font-size: 24rpx;
	color: #999;
	line-height: 1.4;
}

.time.status-pending {
	color: #e6a23c;
}

.level-badge {
	flex-shrink: 0;
	padding: 6rpx 16rpx;
	border-radius: 8rpx;
	font-size: 22rpx;
	font-weight: 500;
	white-space: nowrap;
}

.level-badge.level-normal {
	background: #fff7e6;
	border: 2rpx solid #ffd591;
	color: #fa8c16;
}

.level-badge.level-major {
	background: #fff1f0;
	border: 2rpx solid #ffa39e;
	color: #f5222d;
}

.card-divider {
	height: 0;
	margin: 20rpx 0;
	border-top: 2rpx dashed #eee;
}

.card-body {
	padding: 0;
}

.detail-row-v2 {
	display: flex;
	align-items: flex-start;
	justify-content: flex-start;
	gap: 24rpx;
	padding: 18rpx 0;
}

.detail-row-v2--block {
	flex-wrap: wrap;
}

.label {
	flex-shrink: 0;
	font-size: 26rpx;
	color: #999;
	line-height: 1.5;
}

.value {
	flex: 1;
	min-width: 0;
	font-size: 26rpx;
	color: #333;
	line-height: 1.6;
	text-align: left;
	word-break: break-all;
}

.value--pending {
	color: #e6a23c;
}

.level-tag {
	display: inline-flex;
	align-items: center;
	padding: 4rpx 16rpx;
	border-radius: 8rpx;
	font-size: 24rpx;
	font-weight: 500;
	line-height: 1.4;
	white-space: nowrap;
}

.level-normal {
	background: #fff7e6;
	border: 2rpx solid #ffd591;
	color: #fa8c16;
}

.level-major {
	background: #fff1f0;
	border: 2rpx solid #ffa39e;
	color: #f5222d;
}

.attachment-list {
	display: flex;
	flex-wrap: wrap;
	gap: 16rpx;
	flex: 1;
	min-width: 0;
}

.attachment-img {
	width: 160rpx;
	height: 160rpx;
	border-radius: 12rpx;
	background: #f5f7fa;
}

.sign-img {
	width: 300rpx;
	height: 160rpx;
	border: 1rpx solid #e4e7ed;
	border-radius: 8rpx;
	background: #fafafa;
	flex: 1;
	min-width: 0;
	max-width: 100%;
}

.file-link {
	display: inline-block;
	padding: 12rpx 20rpx;
	background: #f5f7fa;
	border: 1rpx solid #e4e7ed;
	border-radius: 8rpx;
	color: #2667e9;
	font-size: 24rpx;
}

.result-tag {
	padding: 6rpx 16rpx;
	border-radius: 6rpx;
	font-size: 24rpx;
}

.result-tag--pass {
	background: #f0f9eb;
	color: #67c23a;
}

.result-tag--fail {
	background: #fef0f0;
	color: #f56c6c;
}
</style>
