<template>
	<view :class="sheetRootClass">
		<view v-if="!embedded" class="fe-sheet-handle" />
		<view v-if="!embedded" class="fe-sheet-header">
			<view class="fe-sheet-title">
				{{ sheetTitle }}
				<text class="fe-draft-card-status" :class="'fe-draft-card-status--' + statusBadgeTone">{{ statusBadge }}</text>
			</view>
		</view>
		<view class="fe-sheet-source">{{ sourceText }}</view>
		<scroll-view
			scroll-y
			class="fe-sheet-body"
			:class="{ 'fe-draft-sheet-body--embedded': embedded }"
			:style="embeddedBodyStyle"
			:show-scrollbar="false"
		>
			<view class="fe-sheet-body__inner">
				<view class="fe-form-section">
					<view class="fe-form-section__title">
						<text>基础信息</text>
					</view>
					<!-- 与草稿卡片一致：按工种列表展示（工种1、工种2…） -->
					<view v-if="workerGroupRows.length" class="fe-draft-groups">
						<view
							v-for="(g, gIdx) in workerGroupRows"
							:key="gIdx"
							class="fe-draft-group"
						>
							<view class="fe-draft-group__title">工种 {{ gIdx + 1 }}</view>
							<view class="fe-info-row">
								<text class="fe-info-row__label">岗位类型</text>
								<text class="fe-info-row__value">{{ g.workType }}</text>
							</view>
							<view class="fe-info-row">
								<text class="fe-info-row__label">工作地点</text>
								<text class="fe-info-row__value">{{ g.workLocation }}</text>
							</view>
							<view class="fe-info-row">
								<text class="fe-info-row__label">用工人数</text>
								<text class="fe-info-row__value">{{ g.headcountText }}</text>
							</view>
						</view>
					</view>
					<view v-else class="fe-form-section__empty">待补充</view>
					<text v-if="canEdit" class="fe-biz-card__hint fe-draft-sheet-hint">
						如需修改草稿，请直接在对话中说明
					</text>
				</view>
				<view class="fe-form-section" :class="{ 'fe-form-section--editing': requirementsEditing }">
					<view class="fe-form-section__title">
						<text>岗位要求</text>
						<text
							v-if="canEdit"
							class="fe-form-section__edit"
							:class="{ 'fe-form-section__edit--disabled': saving }"
							@tap="toggleRequirementsEdit"
						>{{ requirementsEditing ? (saving ? '保存中...' : '保存') : '编辑' }}</text>
					</view>
					<textarea
						v-if="requirementsEditing"
						class="fe-form-section__textarea"
						v-model="form.requirements"
						:auto-height="true"
						:disabled="saving"
						placeholder="每行一条要求"
					/>
					<view v-else class="fe-form-section__desc">
						<text v-if="!requirementLines.length" class="fe-form-section__empty">待补充</text>
						<text v-for="(line, i) in requirementLines" :key="i">{{ line }}</text>
					</view>
				</view>
				<view class="fe-form-section fe-form-section--cost">
					<view class="fe-form-section__title">
						<text>成本对比</text>
						<view v-if="costPlans.length > 1 && !isConfirmed" class="fe-swipe-indicator">
							<text class="fe-swipe-indicator__arrow">‹</text>
							<text>滑动切换方案</text>
							<text class="fe-swipe-indicator__arrow">›</text>
						</view>
						<text v-else-if="isConfirmed" class="fe-form-section__tip">已确认方案</text>
					</view>
					<!-- <view class="fe-form-section__tip fe-form-section__tip--block">{{ costSceneText }}</view> -->

					<view v-if="costLoading" class="fe-cost-status">
						<text class="fe-cost-status__text">正在测算成本方案...</text>
					</view>
					<view v-else-if="isIncomplete" class="fe-cost-status">
						<text class="fe-cost-status__text">请先补全草稿必填信息后再测算成本</text>
						<text v-if="missingFieldsText" class="fe-cost-status__sub">待补充：{{ missingFieldsText }}</text>
					</view>
					<view v-else-if="costError" class="fe-cost-status">
						<text class="fe-cost-status__text">{{ costError }}</text>
						<view
							v-if="canLoadCost"
							class="fe-biz-btn fe-biz-btn--primary fe-cost-status__btn"
							@tap="loadCostComparison"
						>重新测算</view>
					</view>
					<view v-else-if="!costPlans.length" class="fe-cost-status">
						<text class="fe-cost-status__text">{{ isConfirmed ? '方案已确认' : '暂无成本方案' }}</text>
					</view>
					<template v-else>
						<!-- catchtouchmove：嵌入外层草稿 swiper 时不误触草稿切换；已确认仅一张且禁滑 -->
						<view catchtouchmove="true">
						<swiper
							class="fe-draft-cost-swiper"
							:style="{ height: costSwiperHeight + 'px' }"
							:current="currentCostIndex"
							:disable-touch="isConfirmed || costPlans.length <= 1"
							@change="onCostSwiperChange"
						>
							<swiper-item
								v-for="(plan, planIndex) in costPlans"
								:key="plan.id"
								class="fe-draft-cost-swiper__item"
							>
								<view class="fe-draft-cost-swiper__inner" :id="costPanelId(planIndex)">
									<view
										class="fe-cost-card"
										:class="{ 'fe-cost-card--recommended': plan.recommended || currentCostIndex === planIndex }"
									>
										<view v-if="plan.recommended" class="fe-cost-card__tag">推荐</view>
										<view class="fe-cost-card__head">
											<view class="fe-cost-card__name">
												<text>{{ plan.icon }}</text>
												<text>{{ plan.title }}</text>
											</view>
											<view class="fe-cost-card__toggle" @tap.stop="toggleCostExpandByIndex(planIndex)">
												<view
													class="fe-cost-card__chevron"
													:class="{ 'fe-cost-card__chevron--up': isCostExpandedByIndex(planIndex) }"
												/>
											</view>
										</view>
										<view class="fe-cost-total">{{ plan.total }}</view>
										<text class="fe-cost-total-label">企业总支出</text>
										<!-- 按工种：标题后带企业成本，默认折叠可展开 -->
										<view
											v-if="plan.groupRows && plan.groupRows.length"
											class="fe-cost-groups"
										>
											<view
												v-for="(g, gIdx) in plan.groupRows"
												:key="gIdx"
												class="fe-cost-group"
											>
												<view
													class="fe-cost-group__head"
													@tap.stop="toggleCostGroupByIndex(planIndex, gIdx)"
												>
													<view class="fe-cost-group__title-row">
														<text class="fe-cost-group__title">{{ g.title }} · {{ g.jobType }}</text>
														<text class="fe-cost-group__cost">{{ g.costText }}</text>
													</view>
													<view class="fe-cost-card__chevron" :class="g.chevronClass" />
												</view>
												<view v-if="g.expanded" class="fe-cost-group__body">
													<view class="fe-info-row">
														<text class="fe-info-row__label">人数</text>
														<text class="fe-info-row__value">{{ g.countText }} · {{ g.settlementLabel }}</text>
													</view>
													<view class="fe-info-row">
														<text class="fe-info-row__label">{{ g.avgCostLabel }}</text>
														<text class="fe-info-row__value">{{ g.avgCostText }}</text>
													</view>
													<view class="fe-info-row">
														<text class="fe-info-row__label">{{ g.unitNetLabel }}</text>
														<text class="fe-info-row__value">{{ g.unitNetText }}</text>
													</view>
													<view class="fe-info-row">
														<text class="fe-info-row__label">到手合计</text>
														<text class="fe-info-row__value">{{ g.netText }}</text>
													</view>
													<view
														v-if="g.feeRows && g.feeRows.length"
														class="fe-cost-group__fees"
													>
														<text class="fe-cost-group__fees-title">费用明细</text>
														<view
															v-for="(fee, fIdx) in g.feeRows"
															:key="fIdx"
															class="fe-info-row"
														>
															<text class="fe-info-row__label">{{ fee.label }}</text>
															<text class="fe-info-row__value">{{ fee.value }}</text>
														</view>
													</view>
												</view>
											</view>
										</view>
										<view v-else class="fe-info-row">
											<text class="fe-info-row__label">人均成本</text>
											<text class="fe-info-row__value">{{ plan.avgCost }}</text>
										</view>
										<view v-if="isCostExpandedByIndex(planIndex)" class="fe-cost-card__detail">
											<view
												v-for="(row, rowIdx) in plan.rows"
												:key="rowIdx"
												class="fe-info-row"
											>
												<text class="fe-info-row__label">{{ row.label }}</text>
												<text class="fe-info-row__value">{{ row.value }}</text>
											</view>
											<view v-if="plan.breakdown && plan.breakdown.length" class="fe-cost-card__breakdown">
												<view
													v-for="(row, bdIdx) in plan.breakdown"
													:key="bdIdx"
													class="fe-info-row"
												>
													<text class="fe-info-row__label">{{ row.label }}</text>
													<text class="fe-info-row__value">{{ row.value }}</text>
												</view>
											</view>
											<view v-if="plan.compliance && plan.compliance.length" class="fe-compliance">
												<text
													v-for="(badge, cmIdx) in plan.compliance"
													:key="cmIdx"
													class="fe-compliance-badge"
												>✓ {{ badge }}</text>
											</view>
										</view>
									</view>
								</view>
							</swiper-item>
						</swiper>
						</view>

						<view v-if="costPlans.length > 1 && !isConfirmed" class="fe-dot-indicator">
							<view
								v-for="(plan, i) in costPlans"
								:key="plan.id"
								class="fe-dot-indicator__dot"
								:class="{ 'fe-dot-indicator__dot--active': currentCostIndex === i }"
							/>
						</view>
					</template>
				</view>
			</view>
		</scroll-view>
		<view v-if="embedded && pagerCount > 1" class="fe-progress-dots">
			<view
				v-for="(dot, di) in pagerDots"
				:key="di"
				class="fe-progress-dot"
				:class="{ 'fe-progress-dot--active': di === pagerIndex }"
			/>
		</view>
		<view class="fe-sheet-footer">
			<view
				v-if="isConfirmed"
				class="fe-btn fe-btn--secondary fe-btn--lg"
				@tap="onViewQr"
			>分享</view>
			<view
				class="fe-btn fe-btn--primary fe-btn--lg"
				:class="{ 'fe-btn--disabled': !canConfirmScheme }"
				@tap="onConfirmScheme"
			>{{ confirmButtonText }}</view>
		</view>
	</view>
</template>

<script>
import { showToast } from '@/common/chat-data.js'
import { updateDraft, getDraftCostComparison, confirmDraft, getDraftDetail } from '@/api/draft.js'
import {
	formatSettlementMode,
	mapDraftDetailToCard,
	mapCostSchemesToPlans,
	normalizeWorkerGroups,
	resolveWorkerGroupRows,
	isDraftReadyForCost,
	isDraftIncomplete,
	getDraftStatus,
	buildConfirmedCostPlans,
	pickDraftQrCodeUrl,
	pickDraftQrToken
} from '@/utils/draft.js'

const DEFAULT_FORM = {
	workers: '',
	days: '',
	jobType: '',
	location: '',
	dailyWage: '',
	settlementMode: '',
	requirements: ''
}

const SETTLEMENT_OPTIONS = [
	{ value: 'daily', label: '日结' },
	{ value: 'piece', label: '计件' },
	{ value: 'monthly', label: '月结' }
]

function formFromDraft(draft) {
	if (!draft) return { ...DEFAULT_FORM }
	const detail = draft.detail || {}
	return {
		workers: draft.workerCount != null ? String(draft.workerCount) : '',
		days: draft.workDays != null ? String(draft.workDays) : '',
		jobType: draft.workType && draft.workType !== '待补充' ? draft.workType : '',
		location: draft.workLocation && draft.workLocation !== '待补充' ? draft.workLocation : '',
		dailyWage: draft.dailyWage != null ? String(draft.dailyWage) : (detail.dailyWage != null ? String(detail.dailyWage) : ''),
		settlementMode: draft.settlementMode || detail.settlementMode || '',
		requirements: detail.jobRequirements || ''
	}
}

export default {
	name: 'FeDraftSheet',
	props: {
		active: { type: Boolean, default: false },
		draft: { type: Object, default: null },
		/** 嵌入会话成本列表等场景：不渲染底部弹层外壳 */
		embedded: { type: Boolean, default: false },
		/** 嵌入时由父级指定内容区高度（px） */
		bodyHeight: { type: Number, default: 0 },
		/** 嵌入多草稿切换时展示底部紫色小点 */
		pagerCount: { type: Number, default: 0 },
		pagerIndex: { type: Number, default: 0 },
		sheetTitle: { type: String, default: '📄 用工草稿' }
	},
	data() {
		return {
			basicEditing: false,
			requirementsEditing: false,
			saving: false,
			form: { ...DEFAULT_FORM },
			settlementOptions: SETTLEMENT_OPTIONS,
			costPlans: [],
			expandedCostPlans: {},
			currentCostIndex: 0,
			costSwiperHeight: uni.upx2px(360),
			costLoading: false,
			costError: '',
			costRequestSeq: 0,
			confirming: false
		}
	},
	computed: {
		pagerDots() {
			const n = Number(this.pagerCount) || 0
			const list = []
			for (let i = 0; i < n; i++) list.push(i)
			return list
		},
		/**
		 * 小程序上对象形式 :class 易丢类名，弹层会一直盖在页面上；这里用字符串保证 inactive 时带 translateY(100%)
		 */
		sheetRootClass() {
			if (this.embedded) {
				return 'fe-draft-sheet-root fe-draft-sheet-root--embedded'
			}
			return this.active
				? 'fe-bottom-sheet fe-bottom-sheet--draft fe-bottom-sheet--active'
				: 'fe-bottom-sheet fe-bottom-sheet--draft'
		},
		embeddedBodyStyle() {
			if (!this.embedded || !this.bodyHeight) return {}
			return { height: this.bodyHeight + 'px' }
		},
		draftId() {
			if (!this.draft) return null
			return this.draft.draftId != null ? this.draft.draftId : (this.draft.detail && this.draft.detail.id)
		},
		canEdit() {
			return !!this.draftId && getDraftStatus(this.draft) === 'pending'
		},
		workerGroupRows() {
			return resolveWorkerGroupRows(this.draft)
		},
		isConfirmed() {
			return getDraftStatus(this.draft) === 'confirmed'
		},
		isIncomplete() {
			return isDraftIncomplete(this.draft)
		},
		canLoadCost() {
			return !!this.draftId && isDraftReadyForCost(this.draft)
		},
		canConfirmScheme() {
			return (
				this.canLoadCost &&
				!this.costLoading &&
				!this.costError &&
				this.costPlans.length > 0 &&
				!this.confirming
			)
		},
		confirmButtonText() {
			if (this.isConfirmed) return '已确认此方案'
			if (this.confirming) return '确认中...'
			return '确认此方案'
		},
		currentScheme() {
			return this.costPlans[this.currentCostIndex] || null
		},
		missingFieldsText() {
			const missing = (this.draft && this.draft.missingFields) || []
			return Array.isArray(missing) ? missing.join('、') : ''
		},
		requirementLines() {
			return this.form.requirements
				.split('\n')
				.map((line) => line.trim())
				.filter(Boolean)
		},
		statusBadge() {
			const status = getDraftStatus(this.draft)
			if (status === 'confirmed') return '已确认'
			if (status === 'cancelled') return '已取消'
			return '未确认'
		},
		statusBadgeTone() {
			const status = getDraftStatus(this.draft)
			if (status === 'confirmed') return 'confirmed'
			if (status === 'cancelled') return 'cancelled'
			return 'pending'
		},
		sourceText() {
			const loc = this.draft && this.draft.workLocation
			if (loc && loc !== '待补充') return `来源：AI对话 · ${loc}`
			return '来源：AI对话'
		},
		costSceneText() {
			const parts = []
			if (this.form.jobType) parts.push(this.form.jobType)
			if (this.form.location) parts.push(this.form.location)
			if (this.form.workers && this.form.days) {
				parts.push(`${this.form.workers}人×${this.form.days}天`)
			} else if (this.form.workers) {
				parts.push(`${this.form.workers}人`)
			}
			if (this.isConfirmed) {
				return (parts.length ? parts.join(' · ') + ' · ' : '') + '方案已确认'
			}
			return parts.length ? parts.join(' · ') : '成本方案对比'
		},
		displayWorkers() {
			return this.form.workers ? `${this.form.workers} 人` : '待补充'
		},
		displayDays() {
			return this.form.days ? `${this.form.days} 天` : '待补充'
		},
		displayDailyWage() {
			if (!this.form.dailyWage) return '待补充'
			return `${this.form.dailyWage} 元/天`
		},
		displaySettlement() {
			return formatSettlementMode(this.form.settlementMode)
		}
	},
	watch: {
		active(val) {
			if (this.embedded) return
			if (!val) {
				this.basicEditing = false
				this.requirementsEditing = false
				this.saving = false
				this.confirming = false
				return
			}
			this.applyDraft()
		},
		draft: {
			handler() {
				const shouldApply = this.embedded
					? (!this.basicEditing && !this.requirementsEditing && !this.saving && !this.confirming)
					: (this.active && !this.basicEditing && !this.requirementsEditing && !this.saving && !this.confirming)
				if (shouldApply) this.applyDraft()
			},
			deep: true,
			immediate: false
		}
	},
	mounted() {
		if (this.embedded && this.draft) this.applyDraft()
	},
	methods: {
		toast: showToast,
		costPanelId(planIndex) {
			const id = this.draftId != null ? this.draftId : 'x'
			return `draft-cost-panel-${id}-${planIndex}`
		},
		displayText(val) {
			return val && String(val).trim() ? val : '待补充'
		},
		applyDraft() {
			this.form = formFromDraft(this.draft)
			this.basicEditing = false
			this.requirementsEditing = false
			this.saving = false
			this.expandedCostPlans = {}
			this.currentCostIndex = 0
			this.costError = ''
			this.confirming = false
			this.loadCostComparison()
		},
		async loadCostComparison(draftOverride) {
			const draft = draftOverride || this.draft
			const draftId = draft
				? (draft.draftId != null ? draft.draftId : (draft.detail && draft.detail.id))
				: this.draftId
			if (!draftId) {
				this.costPlans = []
				this.costError = ''
				this.costLoading = false
				return
			}

			// 已确认：不可再调测算接口，展示已选方案快照
			if (getDraftStatus(draft) === 'confirmed') {
				this.applyConfirmedCostView(draft)
				return
			}

			if (!isDraftReadyForCost(draft)) {
				this.costPlans = []
				this.costError = ''
				this.costLoading = false
				this.updateCostSwiperHeight()
				return
			}

			// 会话成本列表接口已内嵌 cost_comparison 时优先使用，避免重复请求
			const inline = this.pickInlineCostComparison(draft)
			if (inline && Array.isArray(inline.schemes)) {
				this.costPlans = mapCostSchemesToPlans(inline.schemes, this.buildCostMapCtx(draft))
				const recommendIdx = this.costPlans.findIndex((p) => p.recommended)
				this.currentCostIndex = recommendIdx >= 0 ? recommendIdx : 0
				this.expandedCostPlans = {}
				this.costLoading = false
				this.costError = ''
				this.updateCostSwiperHeight()
				return
			}

			const seq = ++this.costRequestSeq
			this.costLoading = true
			this.costError = ''
			try {
				const data = await getDraftCostComparison(draftId, { showError: false })
				if (seq !== this.costRequestSeq) return
				const schemes = (data && data.schemes) || []
				const plans = mapCostSchemesToPlans(schemes, this.buildCostMapCtx(draft))
				this.costPlans = plans
				const recommendIdx = this.costPlans.findIndex((p) => p.recommended)
				this.currentCostIndex = recommendIdx >= 0 ? recommendIdx : 0
				this.expandedCostPlans = {}
				this.updateCostSwiperHeight()
			} catch (e) {
				if (seq !== this.costRequestSeq) return
				this.costPlans = []
				this.costError = (e && (e.msg || e.message)) || '成本测算失败，请稍后重试'
			} finally {
				if (seq === this.costRequestSeq) this.costLoading = false
			}
		},
		buildCostMapCtx(draft) {
			const workers = draft && draft.workerCount != null
				? draft.workerCount
				: Number(this.form.workers) || 1
			let workerGroups = (draft && Array.isArray(draft.workerGroups) && draft.workerGroups.length)
				? draft.workerGroups
				: []
			if (!workerGroups.length && draft) {
				workerGroups = normalizeWorkerGroups(draft.detail || draft)
			}
			return { workerCount: workers, workerGroups }
		},
		pickInlineCostComparison(draft) {
			if (!draft || typeof draft !== 'object') return null
			const detail = draft.detail && typeof draft.detail === 'object' ? draft.detail : null
			return draft.costComparison
				|| draft.cost_comparison
				|| (detail && (detail.costComparison || detail.cost_comparison))
				|| null
		},
		pickSelectedSchemeCode(draft) {
			if (!draft || typeof draft !== 'object') return ''
			const detail = draft.detail && typeof draft.detail === 'object' ? draft.detail : null
			return draft.selectedSchemeCode
				|| draft.selected_scheme_code
				|| (detail && (detail.selectedSchemeCode || detail.selected_scheme_code))
				|| (draft.confirmedPlan && draft.confirmedPlan.code)
				|| ''
		},
		/**
		 * 已确认草稿只保留一个方案卡片（不可再左右滑动对比）
		 */
		pickConfirmedDisplayPlans(plans, draft) {
			const list = Array.isArray(plans) ? plans.slice() : []
			if (!list.length) return []
			if (list.length === 1) {
				list[0] = Object.assign({}, list[0], { recommended: true })
				return list
			}
			const selectedCode = this.pickSelectedSchemeCode(draft)
			let matched = []
			if (selectedCode) {
				matched = list.filter((p) => p && p.code === selectedCode)
			}
			if (!matched.length) {
				matched = list.filter((p) => p && p.recommended)
			}
			const one = matched.length ? matched[0] : list[0]
			return [Object.assign({}, one, { recommended: true })]
		},
		applyConfirmedCostView(draft) {
			this.costLoading = false
			this.costError = ''
			const inline = this.pickInlineCostComparison(draft)
			let plans = []
			if (inline && Array.isArray(inline.schemes) && inline.schemes.length) {
				plans = mapCostSchemesToPlans(inline.schemes, this.buildCostMapCtx(draft))
			} else {
				plans = buildConfirmedCostPlans(draft)
			}
			this.costPlans = this.pickConfirmedDisplayPlans(plans, draft)
			this.currentCostIndex = 0
			this.expandedCostPlans = {}
			this.updateCostSwiperHeight()
		},
		onViewQr() {
			if (!this.isConfirmed) return
			this.$emit('view-qr', {
				draftId: this.draftId,
				selectedSchemeCode: this.draft && this.draft.selectedSchemeCode,
				orderId: this.draft && this.draft.detail && this.draft.detail.orderId
			})
		},
		onCostSwiperChange(e) {
			if (this.isConfirmed) {
				this.currentCostIndex = 0
				return
			}
			this.currentCostIndex = e.detail.current
			this.updateCostSwiperHeight()
		},
		updateCostSwiperHeight() {
			this.$nextTick(() => {
				setTimeout(() => {
					const selector = `#${this.costPanelId(this.currentCostIndex)}`
					uni.createSelectorQuery()
						.in(this)
						.select(selector)
						.boundingClientRect((rect) => {
							if (rect && rect.height > 0) {
								this.costSwiperHeight = Math.ceil(rect.height)
							}
						})
						.exec()
				}, 50)
			})
		},
		isCostExpanded(id) {
			// 方案费用明细默认折叠
			if (this.expandedCostPlans[id] === undefined) return false
			return !!this.expandedCostPlans[id]
		},
		isCostExpandedByIndex(index) {
			const plan = this.costPlans[index]
			return plan ? this.isCostExpanded(plan.id) : false
		},
		toggleCostExpandByIndex(index) {
			const plan = this.costPlans[index]
			if (!plan) return
			const id = plan.id
			this.$set(this.expandedCostPlans, id, !this.isCostExpanded(id))
			this.updateCostSwiperHeight()
		},
		toggleCostGroupByIndex(planIndex, gIdx) {
			const plan = this.costPlans[planIndex]
			if (!plan || !Array.isArray(plan.groupRows) || !plan.groupRows[gIdx]) return
			const row = plan.groupRows[gIdx]
			const next = !row.expanded
			this.$set(plan.groupRows[gIdx], 'expanded', next)
			this.$set(plan.groupRows[gIdx], 'chevronClass', next ? 'fe-cost-card__chevron--up' : '')
			this.updateCostSwiperHeight()
		},
		selectSettlementByIndex(idx) {
			if (this.saving) return
			const opt = this.settlementOptions[idx]
			if (!opt) return
			this.form.settlementMode = opt.value
		},
		toggleBasicEdit() {
			if (!this.canEdit || this.saving) return
			if (this.basicEditing) {
				this.saveBasicInfo()
				return
			}
			this.requirementsEditing = false
			this.basicEditing = true
		},
		toggleRequirementsEdit() {
			if (!this.canEdit || this.saving) return
			if (this.requirementsEditing) {
				this.saveRequirements()
				return
			}
			this.basicEditing = false
			this.requirementsEditing = true
		},
		buildBasicPayload() {
			const workers = Number(this.form.workers)
			const days = Number(this.form.days)
			if (!this.form.workers.trim() || Number.isNaN(workers) || workers < 1) {
				this.toast('请填写有效的用工人数')
				return null
			}
			if (!this.form.days.trim() || Number.isNaN(days) || days < 1) {
				this.toast('请填写有效的工作天数')
				return null
			}
			if (!this.form.jobType.trim()) {
				this.toast('请填写岗位类型')
				return null
			}
			if (!this.form.location.trim()) {
				this.toast('请填写工作地点')
				return null
			}

			const payload = {
				workerCount: workers,
				workDays: days,
				workType: this.form.jobType.trim(),
				workLocation: this.form.location.trim()
			}

			if (this.form.settlementMode) {
				payload.settlementMode = this.form.settlementMode
			}

			if (this.form.dailyWage.trim()) {
				const wage = Number(this.form.dailyWage)
				if (Number.isNaN(wage) || wage <= 0) {
					this.toast('请填写有效的日薪标准')
					return null
				}
				payload.dailyWage = wage
			}

			return payload
		},
		async saveBasicInfo() {
			const payload = this.buildBasicPayload()
			if (!payload) return
			await this.submitUpdate(payload, () => {
				this.basicEditing = false
			})
		},
		async saveRequirements() {
			const text = this.form.requirements.trim()
			await this.submitUpdate({ jobRequirements: text || '' }, () => {
				this.requirementsEditing = false
			})
		},
		async submitUpdate(payload, onSuccess) {
			if (!this.draftId) {
				this.toast('草稿信息缺失')
				return
			}
			if (this.saving) return
			this.saving = true
			try {
				const detail = await updateDraft(this.draftId, payload, { showError: true })
				const card = mapDraftDetailToCard(detail)
				this.$emit('updated', card)
				this.form = formFromDraft(card)
				if (typeof onSuccess === 'function') onSuccess()
				this.toast('草稿已保存')
				await this.loadCostComparison(card)
			} catch (e) {
				// 错误提示由 request.js 统一处理
			} finally {
				this.saving = false
			}
		},
		async onConfirmScheme() {
			if (this.confirming) return
			if (!this.canConfirmScheme) {
				if (!this.canLoadCost) {
					this.toast('请先补全草稿必填信息')
					return
				}
				if (this.costLoading) {
					this.toast('正在测算，请稍候')
					return
				}
				this.toast('请先完成成本测算')
				return
			}
			const scheme = this.currentScheme
			const schemeCode = scheme && scheme.code
			if (!schemeCode) {
				this.toast('请选择成本方案')
				return
			}

			this.confirming = true
			try {
				const result = await confirmDraft(this.draftId, schemeCode, { showError: true })
				const draftStatus = (result && (result.draftStatus || result.draft_status)) || 'confirmed'
				const confirmedPlan = {
					id: scheme.id || schemeCode,
					code: schemeCode,
					recommended: true,
					icon: scheme.icon,
					title: scheme.title,
					total: scheme.total,
					avgCost: scheme.avgCost,
					rows: Array.isArray(scheme.rows) ? scheme.rows.slice() : [],
					breakdown: Array.isArray(scheme.breakdown) ? scheme.breakdown.slice() : [],
					compliance: Array.isArray(scheme.compliance) ? scheme.compliance.slice() : ['已确认']
				}
				const costPlansSnapshot = this.costPlans.map((p) => ({
					id: p.id,
					code: p.code,
					recommended: p.recommended,
					icon: p.icon,
					title: p.title,
					total: p.total,
					avgCost: p.avgCost,
					rows: Array.isArray(p.rows) ? p.rows.slice() : [],
					breakdown: Array.isArray(p.breakdown) ? p.breakdown.slice() : [],
					compliance: Array.isArray(p.compliance) ? p.compliance.slice() : []
				}))
				const orderId = (result && (result.orderId || result.order_id)) || ''
				const qrTokenFromResult = pickDraftQrToken(result)
				// 二维码 / qrToken 从草稿详情读取；确认响应作兜底
				let qrCodeUrl = ''
				let qrToken = qrTokenFromResult
				try {
					const detail = await getDraftDetail(this.draftId, { showError: false })
					if (detail) {
						qrCodeUrl = pickDraftQrCodeUrl(detail)
						const fromDetail = pickDraftQrToken(detail)
						if (fromDetail) qrToken = fromDetail
					}
				} catch (e) {
					// 静默：确认成功即可，二维码可在分享时再拉详情
				}
				const scene = qrToken || orderId || ''
				const nextDraft = Object.assign({}, this.draft || {}, {
					status: draftStatus,
					missingFields: [],
					selectedSchemeCode: schemeCode,
					confirmedPlan,
					confirmedPlanTitle: scheme.title,
					costPlans: costPlansSnapshot,
					orderId,
					qrToken: qrToken || '',
					scene,
					qrCodeUrl,
					estimatedTotal: scheme.raw && scheme.raw.cost
						? (scheme.raw.cost.total_cost || scheme.raw.cost.totalCost)
						: (this.draft && this.draft.estimatedTotal)
				})
				if (nextDraft.detail && typeof nextDraft.detail === 'object') {
					nextDraft.detail = Object.assign({}, nextDraft.detail, {
						status: draftStatus,
						selectedSchemeCode: schemeCode,
						orderId,
						qrToken: qrToken || '',
						scene,
						qrCodeUrl
					})
				}
				this.$emit('updated', nextDraft)
				this.applyConfirmedCostView(nextDraft)
				this.$emit('confirm', {
					draftId: this.draftId,
					schemeCode,
					scheme,
					result: result || {}
				})
				this.toast('方案已确认')
			} catch (e) {
				// 错误提示由 request.js 统一处理
			} finally {
				this.confirming = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.fe-draft-sheet-root--embedded {
	display: flex;
	flex-direction: column;
	height: 100%;
	min-height: 0;
	box-sizing: border-box;
	background: #fff;
}

.fe-draft-sheet-body--embedded {
	flex: 1;
	min-height: 0;
	height: auto;
	max-height: none;
}

.fe-draft-sheet-root--embedded .fe-sheet-footer {
	flex-shrink: 0;
}

.fe-progress-dots {
	display: flex;
	justify-content: center;
	align-items: center;
	gap: 12rpx;
	padding: 8rpx 0 4rpx;
	flex-shrink: 0;
}

.fe-progress-dot {
	width: 12rpx;
	height: 12rpx;
	border-radius: 50%;
	background: #E2E8F0;
}

.fe-progress-dot--active {
	width: 28rpx;
	border-radius: 999rpx;
	background: $fe-primary;
}

.fe-bottom-sheet--draft {
	max-height: 92vh;
	height: 92vh;
}

.fe-bottom-sheet--draft .fe-sheet-body {
	flex: 1;
	min-height: 0;
	max-height: none;
	height: 0;
}

.fe-bottom-sheet--draft .fe-sheet-footer {
	flex-shrink: 0;
}

.fe-form-section--editing {
	border-color: $fe-primary-light;
	background: $fe-primary-bg;
}

.fe-form-section__edit--disabled {
	opacity: 0.5;
}

.fe-form-section__empty {
	color: $fe-gray-400;
}

.fe-info-row__field {
	display: flex;
	align-items: center;
	justify-content: flex-end;
	gap: 8rpx;
	flex: 1;
	min-width: 0;
}

.fe-info-row__input {
	width: 120rpx;
	height: 64rpx;
	padding: 0 16rpx;
	border: 1rpx solid $fe-primary-light;
	border-radius: $fe-radius-sm;
	font-size: 28rpx;
	font-weight: 600;
	text-align: right;
	background: #fff;
	box-sizing: border-box;
}

.fe-info-row__input--full {
	width: 100%;
	flex: 1;
	text-align: right;
}

.fe-info-row__suffix {
	font-size: 28rpx;
	font-weight: 600;
	color: $fe-foreground;
	flex-shrink: 0;
}

.fe-settlement-options {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	justify-content: flex-end;
	gap: 12rpx;
	flex: 1;
}

.fe-settlement-option {
	padding: 8rpx 20rpx;
	border-radius: $fe-radius-full;
	border: 1rpx solid $fe-border;
	font-size: 24rpx;
	color: $fe-muted;
	background: #fff;
}

.fe-settlement-option--active {
	border-color: $fe-primary;
	color: $fe-primary;
	background: $fe-primary-bg;
	font-weight: 600;
}

.fe-form-section__textarea {
	width: 100%;
	min-height: 160rpx;
	padding: 20rpx;
	border: 1rpx solid $fe-primary-light;
	border-radius: $fe-radius-sm;
	font-size: 26rpx;
	line-height: 1.6;
	color: $fe-muted;
	background: #fff;
	box-sizing: border-box;
}

.fe-form-section--cost {
	padding-bottom: 8rpx;
	padding-left: 0;
	padding-right: 0;
}

.fe-form-section--cost > .fe-form-section__title,
.fe-form-section--cost > .fe-form-section__tip--block {
	padding-left: 28rpx;
	padding-right: 28rpx;
}

.fe-form-section__tip {
	font-size: 22rpx;
	font-weight: 500;
	color: $fe-muted;
	max-width: 360rpx;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.fe-form-section__tip--block {
	display: block;
	max-width: none;
	margin: -8rpx 0 12rpx;
}

.fe-draft-cost-swiper {
	width: 100%;
}

.fe-draft-cost-swiper__item {
	height: 100%;
	box-sizing: border-box;
}

.fe-draft-cost-swiper__inner {
	padding: 4rpx 28rpx 8rpx;
	box-sizing: border-box;
}

.fe-draft-cost-swiper__inner .fe-cost-card {
	padding: 20rpx 24rpx;
	margin-bottom: 16rpx;
}

.fe-draft-cost-swiper__inner .fe-cost-total {
	font-size: 48rpx;
	margin-bottom: 4rpx;
}

.fe-draft-cost-swiper__inner .fe-info-row {
	padding: 8rpx 0;
}

.fe-draft-cost-swiper__inner .fe-compliance {
	margin-top: 12rpx;
	padding-top: 12rpx;
}

.fe-form-section--cost > .fe-dot-indicator {
	padding: 8rpx 28rpx 12rpx;
}

.fe-cost-card__head {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 16rpx;
	margin-bottom: 12rpx;
}

.fe-cost-card__name {
	display: flex;
	align-items: center;
	gap: 12rpx;
	font-size: 28rpx;
	font-weight: 700;
	flex: 1;
	min-width: 0;
}

.fe-cost-card__toggle {
	width: 48rpx;
	height: 48rpx;
	border-radius: 50%;
	background: rgba(124, 58, 237, 0.1);
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.fe-cost-card__chevron {
	width: 16rpx;
	height: 16rpx;
	border-right: 4rpx solid $fe-primary;
	border-bottom: 4rpx solid $fe-primary;
	transform: rotate(45deg);
	margin-top: -6rpx;
	transition: transform 0.2s ease;
}

.fe-cost-card__chevron--up {
	transform: rotate(-135deg);
	margin-top: 6rpx;
}

.fe-cost-card__breakdown {
	border-top: 1rpx solid #F1F5F9;
	margin-top: 8rpx;
	padding-top: 8rpx;
}

.fe-cost-card__detail {
	width: 100%;
}

.fe-cost-status {
	padding: 32rpx 28rpx 24rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;
}

.fe-cost-status__text {
	font-size: 26rpx;
	color: $fe-muted;
	text-align: center;
	line-height: 1.5;
}

.fe-cost-status__sub {
	font-size: 22rpx;
	color: $fe-primary;
	text-align: center;
	line-height: 1.5;
}

.fe-cost-status__btn {
	margin-top: 8rpx;
	min-width: 200rpx;
}

.fe-btn--disabled {
	opacity: 0.45;
	pointer-events: none;
}
</style>
