<template>
	<view class="fe-bottom-sheet fe-bottom-sheet--draft" :class="{ 'fe-bottom-sheet--active': active }">
		<view class="fe-sheet-handle" />
		<view class="fe-sheet-header">
			<view class="fe-sheet-title">
				💰 成本测算
				<text
					v-if="currentDraft"
					class="fe-draft-card-status"
					:class="'fe-draft-card-status--' + currentStatusTone"
				>{{ currentStatusBadge }}</text>
				<text v-if="draftItems.length > 1" class="fe-conv-cost-hint">左右滑动切换草稿</text>
			</view>
		</view>

		<view v-if="loading" class="fe-conv-cost-empty">
			<text class="fe-conv-cost-empty__text">正在加载会话草稿...</text>
		</view>
		<view v-else-if="loadError" class="fe-conv-cost-empty">
			<text class="fe-conv-cost-empty__text">{{ loadError }}</text>
			<view class="fe-biz-btn fe-biz-btn--primary fe-conv-cost-empty__btn" @tap="loadData">重新加载</view>
		</view>
		<view v-else-if="!draftItems.length" class="fe-conv-cost-empty">
			<text class="fe-conv-cost-empty__text">当前会话暂无用工草稿</text>
			<text class="fe-conv-cost-empty__sub">请先通过对话创建用工需求后再试</text>
		</view>
		<block v-else>
			<view class="fe-sheet-source">{{ currentDraftSubtitle }}</view>
			<swiper
				class="fe-conv-cost-swiper"
				:style="{ height: swiperHeight + 'px' }"
				:current="draftIndex"
				:indicator-dots="false"
				@change="onDraftSwiperChange"
			>
				<swiper-item v-for="(item, dIdx) in draftItems" :key="item.msgKey">
					<FeDraftSheet
						embedded
						:active="active && dIdx === draftIndex"
						:draft="item.draft"
						:body-height="panelBodyHeight"
						:pager-count="draftItems.length"
						:pager-index="draftIndex"
						@confirm="onDraftConfirm"
						@updated="onDraftUpdatedByIndex(dIdx, $event)"
						@view-qr="onViewQr"
					/>
				</swiper-item>
			</swiper>
		</block>
	</view>
</template>

<script>
import { showToast } from '@/common/chat-data.js'
import { listConversationDraftCostComparisons } from '@/api/conversation.js'
import { mapDraftDetailToCard, getDraftStatus } from '@/utils/draft.js'
import FeDraftSheet from '@/packageA/components/chat/FeDraftSheet.vue'

export default {
	name: 'FeConversationCostSheet',
	components: {
		FeDraftSheet
	},
	props: {
		active: { type: Boolean, default: false },
		conversationId: { type: [Number, String], default: null },
		draftMetas: {
			type: Array,
			default() {
				return []
			}
		}
	},
	data() {
		const winH = (uni.getSystemInfoSync().windowHeight || 600)
		const swiperHeight = Math.floor(winH * 0.72)
		return {
			loading: false,
			loadError: '',
			draftItems: [],
			draftIndex: 0,
			swiperHeight,
			panelBodyHeight: Math.max(280, swiperHeight - uni.upx2px(208))
		}
	},
	computed: {
		currentItem() {
			return this.draftItems[this.draftIndex] || null
		},
		currentDraft() {
			return this.currentItem && this.currentItem.draft
		},
		currentDraftSubtitle() {
			const item = this.currentItem
			if (!item || !item.draft) return ''
			const n = this.draftItems.length
			const pos = n > 1 ? `（${this.draftIndex + 1}/${n}）` : ''
			const title = item.draft.title || `用工草稿 #${item.draftId}`
			return `${title}${pos}`
		},
		currentStatusBadge() {
			const status = getDraftStatus(this.currentDraft)
			if (status === 'confirmed') return '已确认'
			if (status === 'cancelled') return '已取消'
			return '未确认'
		},
		currentStatusTone() {
			const status = getDraftStatus(this.currentDraft)
			if (status === 'confirmed') return 'confirmed'
			if (status === 'cancelled') return 'cancelled'
			return 'pending'
		}
	},
	watch: {
		active(val) {
			if (val) {
				this.syncHeights()
				this.loadData()
			}
		},
		conversationId() {
			if (this.active) this.loadData()
		}
	},
	methods: {
		syncHeights() {
			try {
				const winH = uni.getSystemInfoSync().windowHeight || 600
				this.swiperHeight = Math.floor(winH * 0.72)
				this.panelBodyHeight = Math.max(280, this.swiperHeight - uni.upx2px(208))
			} catch (e) {
				this.swiperHeight = 480
				this.panelBodyHeight = 360
			}
		},
		metaByDraftId(draftId) {
			const list = Array.isArray(this.draftMetas) ? this.draftMetas : []
			for (let i = 0; i < list.length; i++) {
				if (list[i] && String(list[i].draftId) === String(draftId)) return list[i]
			}
			return null
		},
		pickCostComparison(raw) {
			if (!raw || typeof raw !== 'object') return null
			return raw.costComparison || raw.cost_comparison || null
		},
		/**
		 * 新格式：DraftDetail + cost_comparison → 与用工草稿相同的 card 结构
		 */
		mapApiList(list) {
			const arr = Array.isArray(list) ? list : []
			const mapped = []
			for (let i = 0; i < arr.length; i++) {
				const raw = arr[i] || {}
				const draftId = raw.id != null ? raw.id : (raw.draftId != null ? raw.draftId : raw.draft_id)
				if (draftId == null) continue
				const meta = this.metaByDraftId(draftId) || {}
				const costComparison = this.pickCostComparison(raw)
				const card = mapDraftDetailToCard(raw)
				if (!card.title && meta.title) card.title = meta.title
				if (card.workerCount == null && meta.workerCount != null) card.workerCount = meta.workerCount
				if (costComparison) {
					card.costComparison = costComparison
					card.cost_comparison = costComparison
				}
				mapped.push({
					msgKey: draftId,
					draftId,
					draft: card
				})
			}
			this.draftItems = mapped
			this.draftIndex = 0
		},
		async loadData() {
			const conversationId = this.conversationId
			if (conversationId == null || conversationId === '') {
				this.draftItems = []
				this.loadError = '请先开启对话'
				return
			}
			this.loading = true
			this.loadError = ''
			try {
				const list = await listConversationDraftCostComparisons(conversationId, { showError: false })
				this.mapApiList(list)
			} catch (e) {
				this.draftItems = []
				this.loadError = (e && (e.msg || e.message)) || '成本测算加载失败'
				showToast(this.loadError)
			} finally {
				this.loading = false
			}
		},
		onDraftSwiperChange(e) {
			const idx = e && e.detail && e.detail.current != null ? e.detail.current : 0
			this.draftIndex = idx
		},
		onDraftUpdatedByIndex(dIdx, draftCard) {
			if (dIdx == null || !draftCard) return
			const item = this.draftItems[dIdx]
			if (!item) return
			this.$set(this.draftItems, dIdx, {
				msgKey: item.msgKey,
				draftId: draftCard.draftId != null ? draftCard.draftId : item.draftId,
				draft: draftCard
			})
			this.$emit('updated', draftCard)
		},
		onDraftConfirm(payload) {
			this.$emit('confirm', payload)
		},
		onViewQr(payload) {
			const item = this.currentItem
			if (item && item.draft) {
				this.$emit('updated', item.draft)
			}
			this.$emit('view-qr', payload)
		}
	}
}
</script>

<style lang="scss" scoped>
.fe-bottom-sheet--draft {
	max-height: 92vh;
	height: 92vh;
}

.fe-conv-cost-hint {
	margin-left: 12rpx;
	font-size: 22rpx;
	color: #94A3B8;
	font-weight: 500;
}

.fe-conv-cost-empty {
	flex: 1;
	padding: 80rpx 40rpx;
	text-align: center;
}

.fe-conv-cost-empty__text {
	display: block;
	font-size: 28rpx;
	color: #64748B;
	line-height: 1.5;
}

.fe-conv-cost-empty__sub {
	display: block;
	margin-top: 12rpx;
	font-size: 24rpx;
	color: #94A3B8;
}

.fe-conv-cost-empty__btn {
	margin: 28rpx auto 0;
	display: inline-flex;
}

.fe-conv-cost-swiper {
	width: 100%;
	flex: 1;
	min-height: 0;
	box-sizing: border-box;
}
</style>
