<template>
	<view class="fe-bottom-sheet fe-bottom-sheet--recruit" :class="{ 'fe-bottom-sheet--active': active }">
		<view class="fe-sheet-handle" />
		<view class="fe-sheet-header">
			<view class="fe-sheet-title">🔍 临时工招聘</view>
			<view class="fe-sheet-close" @tap="onClose">✕</view>
		</view>
		<view class="fe-sheet-source recruit-source">🔗 正在从第三方人力资源平台匹配...</view>

		<view v-if="loading" class="recruit-empty">
			<text class="recruit-empty__text">匹配临时工中...</text>
		</view>
		<view v-else-if="loadError && !matchGroups.length" class="recruit-empty">
			<text class="recruit-empty__text">{{ loadError }}</text>
			<view class="fe-btn fe-btn--primary fe-btn--sm" @tap="loadData">重试</view>
		</view>
		<template v-else>
			<scroll-view scroll-y class="fe-sheet-body recruit-body" :show-scrollbar="false">
				<view class="fe-sheet-body__inner">
					<view class="recruit-hero">
						<view class="recruit-hero__icon">
							<text class="recruit-hero__icon-text">🔍</text>
						</view>
						<text class="recruit-hero__title">匹配临时工</text>
						<text class="recruit-hero__desc">已为您找到以下符合条件的临时工</text>
					</view>

					<!-- 搜索条件 -->
					<view class="recruit-section">
						<text class="recruit-section__title">搜索条件</text>
						<view class="recruit-criteria">
							<view class="recruit-criteria__row">
								<view class="recruit-criteria__cell">
									<text class="recruit-criteria__label">岗位类型</text>
									<text class="recruit-criteria__value">{{ criteria.jobTypeText }}</text>
								</view>
								<view class="recruit-criteria__cell">
									<text class="recruit-criteria__label">需求人数</text>
									<text class="recruit-criteria__value">{{ criteria.needCountText }}</text>
								</view>
							</view>
							<view class="recruit-criteria__row">
								<view class="recruit-criteria__cell">
									<text class="recruit-criteria__label">工作地点</text>
									<text class="recruit-criteria__value">{{ criteria.locationText }}</text>
								</view>
								<view class="recruit-criteria__cell">
									<text class="recruit-criteria__label">工作天数</text>
									<text class="recruit-criteria__value">{{ criteria.daysText }}</text>
								</view>
							</view>
						</view>
					</view>

					<!-- 匹配结果：按工种折叠 -->
					<view class="recruit-section">
						<text class="recruit-section__title">{{ resultTitle }}</text>
						<view
							v-for="(group, gIdx) in matchGroups"
							:key="group.msgKey"
							class="recruit-group"
						>
							<view class="recruit-group__head" @tap="toggleGroupByIndex(gIdx)">
								<text class="recruit-group__chevron">{{ group.chevronText }}</text>
								<text class="recruit-group__name">{{ group.workType }}</text>
								<text class="recruit-group__count">{{ group.countText }}</text>
							</view>
							<view v-if="group.expanded" class="recruit-group__body">
								<view
									v-for="(w, wIdx) in group.workers"
									:key="w.msgKey"
									class="recruit-worker"
									@tap="toggleWorkerByIndex(gIdx, wIdx)"
								>
									<view class="recruit-worker__avatar">
										<text class="recruit-worker__avatar-text">{{ w.avatarText }}</text>
									</view>
									<view class="recruit-worker__main">
										<text class="recruit-worker__name">{{ w.name }}</text>
										<text class="recruit-worker__meta" user-select>{{ w.metaText }}</text>
									</view>
									<view :class="w.checkClass">
										<text v-if="w.selected" class="recruit-check__mark">✓</text>
									</view>
								</view>
								<view v-if="!group.workers || !group.workers.length" class="recruit-group__empty">
									<text class="recruit-group__empty-text">暂无匹配人员</text>
								</view>
							</view>
						</view>
						<view v-if="!matchGroups.length" class="recruit-empty recruit-empty--inline">
							<text class="recruit-empty__text">暂无匹配结果</text>
						</view>
					</view>
				</view>
			</scroll-view>

			<view class="fe-sheet-footer recruit-footer">
				<template v-if="readonly">
					<view class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full" @tap="onClose">已确认 · 关闭</view>
				</template>
				<template v-else>
					<view class="fe-btn fe-btn--secondary fe-btn--lg" @tap="onRefresh">
						<text>↻ 刷新</text>
					</view>
					<view
						v-if="submitting"
						class="fe-btn fe-btn--primary fe-btn--lg fe-btn--disabled-look"
					>提交中...</view>
					<view
						v-else-if="confirmDisabled"
						class="fe-btn fe-btn--primary fe-btn--lg fe-btn--disabled-look"
					>确认选择</view>
					<view
						v-else
						class="fe-btn fe-btn--primary fe-btn--lg"
						@tap="onConfirm"
					>确认选择</view>
				</template>
			</view>
		</template>
	</view>
</template>

<script>
import { showToast } from '@/common/chat-data.js'
import { getDraftDetail } from '@/api/draft.js'
import { listThirdPartyAvailableWorkers } from '@/api/worker.js'
import { addThirdPartyWorkers } from '@/api/worker-registration.js'
import { normalizeWorkerGroups, mapDraftDetailToCard } from '@/utils/draft.js'
import {
	buildRecruitCriteria,
	buildAvailableQueries,
	mapAvailableToRecruitGroups,
	buildThirdPartyAddWorkers,
	syncRecruitGroupMeta
} from '@/utils/recruit.js'

export default {
	name: 'FeRecruitSheet',
	props: {
		active: { type: Boolean, default: false },
		draftId: { type: [Number, String], default: null },
		/** 流程已完成：仅查看 */
		readonly: { type: Boolean, default: false }
	},
	data() {
		return {
			loading: false,
			loadError: '',
			submitting: false,
			batchId: null,
			draftGroups: [],
			criteria: {
				jobTypeText: '—',
				needCountText: '—',
				locationText: '—',
				daysText: '—'
			},
			matchGroups: [],
			matchedTotal: 0,
			resultTitle: '匹配结果（0人）'
		}
	},
	computed: {
		selectedTotal() {
			let n = 0
			const groups = this.matchGroups || []
			for (let i = 0; i < groups.length; i++) {
				n += Number(groups[i].selectedCount) || 0
			}
			return n
		},
		confirmDisabled() {
			return this.submitting || this.loading || this.selectedTotal <= 0
		}
	},
	watch: {
		active(val) {
			if (val) this.loadData()
		},
		draftId() {
			if (this.active) this.loadData()
		}
	},
	methods: {
		onClose() {
			this.$emit('close')
		},
		async loadData() {
			this.loading = true
			this.loadError = ''
			this.matchGroups = []
			this.matchedTotal = 0
			this.resultTitle = '匹配结果（0人）'
			this.batchId = null
			this.draftGroups = []
			try {
				if (this.draftId == null || this.draftId === '') {
					this.loadError = '缺少草稿信息'
					return
				}
				const draftRaw = await getDraftDetail(this.draftId, { showError: false })
				const card = mapDraftDetailToCard(draftRaw || {})
				let groups = normalizeWorkerGroups(draftRaw || {})
				if (!groups.length && card && card.workerGroups) {
					groups = card.workerGroups
				}
				this.draftGroups = groups
				this.batchId = draftRaw && (draftRaw.batchId != null && draftRaw.batchId !== ''
					? draftRaw.batchId
					: (draftRaw.batch_id != null && draftRaw.batch_id !== '' ? draftRaw.batch_id : null))
				this.criteria = buildRecruitCriteria(groups)

				await this.fetchAvailable(groups)
			} catch (e) {
				this.loadError = (e && (e.msg || e.message)) || '加载失败'
				showToast(this.loadError)
			} finally {
				this.loading = false
			}
		},
		async fetchAvailable(groups) {
			let queries = buildAvailableQueries(groups)
			if (!queries.length) {
				this.loadError = '草稿暂无工种信息，无法匹配'
				this.matchGroups = []
				this.matchedTotal = 0
				this.resultTitle = '匹配结果（0人）'
				return
			}
			let raw = await listThirdPartyAvailableWorkers(queries, { showError: false })
			let mapped = mapAvailableToRecruitGroups(raw || {}, groups)
			// 带地点无结果时，去掉地点再查一次（Mock 地点可能与草稿不一致）
			if (!mapped.matchedTotal) {
				const noLoc = queries.map((q) => ({
					jobType: q.jobType,
					job_type: q.jobType
				}))
				const retry = await listThirdPartyAvailableWorkers(noLoc, { showError: false })
				mapped = mapAvailableToRecruitGroups(retry || {}, groups)
			}
			this.matchGroups = mapped.matchGroups
			this.matchedTotal = mapped.matchedTotal
			this.resultTitle = mapped.resultTitle
			if (!mapped.matchedTotal) {
				this.loadError = mapped.message || '未匹配到可用临时工'
			} else {
				this.loadError = ''
			}
		},
		toggleGroupByIndex(gIdx) {
			const g = this.matchGroups[gIdx]
			if (!g) return
			this.$set(g, 'expanded', !g.expanded)
			syncRecruitGroupMeta(g)
			this.$set(this.matchGroups, gIdx, g)
		},
		toggleWorkerByIndex(gIdx, wIdx) {
			if (this.readonly) {
				showToast('招聘已确认，仅可查看')
				return
			}
			const g = this.matchGroups[gIdx]
			if (!g || !g.workers) return
			const w = g.workers[wIdx]
			if (!w) return
			// 勾选时校验：本工种已选不能超过需求人数
			if (!w.selected) {
				const need = Number(g.needCount) || 0
				const selected = Number(g.selectedCount) || 0
				if (need <= 0) {
					showToast(`${g.workType || '该工种'}需求人数为 0，无法选择`)
					return
				}
				if (selected >= need) {
					showToast(`${g.workType || '该工种'}最多选择 ${need} 人`)
					return
				}
			}
			this.$set(w, 'selected', !w.selected)
			syncRecruitGroupMeta(g)
			this.$set(this.matchGroups, gIdx, g)
		},
		async onRefresh() {
			if (this.readonly) {
				showToast('招聘已确认，仅可查看')
				return
			}
			if (this.loading) return
			this.loading = true
			this.loadError = ''
			try {
				await this.fetchAvailable(this.draftGroups)
				showToast(this.matchedTotal > 0 ? '已刷新匹配结果' : (this.loadError || '暂无匹配'))
			} catch (e) {
				this.loadError = (e && (e.msg || e.message)) || '刷新失败'
				showToast(this.loadError)
			} finally {
				this.loading = false
			}
		},
		async onConfirm() {
			if (this.readonly) {
				this.onClose()
				return
			}
			if (this.confirmDisabled) return
			if (this.batchId == null || this.batchId === '') {
				showToast('缺少登记批次，无法提交')
				return
			}
			const over = (this.matchGroups || []).find((g) => {
				const need = Number(g.needCount) || 0
				const selected = Number(g.selectedCount) || 0
				return need > 0 && selected > need
			})
			if (over) {
				showToast(`${over.workType || '该工种'}已选 ${over.selectedCount} 人，超过需求 ${over.needCount} 人`)
				return
			}
			const workers = buildThirdPartyAddWorkers(this.matchGroups)
			if (!workers.length) {
				showToast('请先选择临时工')
				return
			}
			this.submitting = true
			try {
				const res = await addThirdPartyWorkers({
					batchId: this.batchId,
					workers
				}, { showError: true })
				const added = res && (res.addedCount != null ? res.addedCount : res.added_count)
				const msg = (res && res.message)
					|| (added != null ? `已添加 ${added} 人` : '确认选择成功')
				showToast(msg)
				this.$emit('success', {
					draftId: this.draftId,
					batchId: this.batchId,
					result: res,
					selectedCount: workers.length
				})
				this.onClose()
			} catch (e) {
				if (e && e.__handled) return
			} finally {
				this.submitting = false
			}
		}
	}
}
</script>

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

.fe-sheet-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
}

.fe-sheet-close {
	width: 56rpx;
	height: 56rpx;
	border-radius: 50%;
	background: $fe-gray-100;
	color: $fe-muted;
	font-size: 28rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.recruit-source {
	padding: 0 40rpx 8rpx;
}

.recruit-body {
	max-height: 64vh;
}

.recruit-empty {
	padding: 80rpx 32rpx;
	text-align: center;
}

.recruit-empty--inline {
	padding: 40rpx 16rpx;
}

.recruit-empty__text {
	font-size: 28rpx;
	color: #94A3B8;
}

.recruit-hero {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 12rpx 0 28rpx;
}

.recruit-hero__icon {
	width: 120rpx;
	height: 120rpx;
	border-radius: 50%;
	background: $fe-primary-bg;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-bottom: 16rpx;
}

.recruit-hero__icon-text {
	font-size: 56rpx;
	line-height: 1;
}

.recruit-hero__title {
	font-size: 34rpx;
	font-weight: 800;
	color: $fe-foreground;
	margin-bottom: 8rpx;
}

.recruit-hero__desc {
	font-size: 24rpx;
	color: $fe-muted;
	text-align: center;
}

.recruit-section {
	margin-bottom: 28rpx;
}

.recruit-section__title {
	display: block;
	font-size: 28rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 16rpx;
}

.recruit-criteria {
	background: $fe-gray-50;
	border-radius: $fe-radius-md;
	padding: 20rpx 24rpx;
	border: 1rpx solid $fe-border-light;
	box-sizing: border-box;
}

.recruit-criteria__row {
	display: flex;
	gap: 16rpx;
	margin-bottom: 16rpx;
}

.recruit-criteria__row:last-child {
	margin-bottom: 0;
}

.recruit-criteria__cell {
	flex: 1;
	min-width: 0;
	display: flex;
	flex-direction: column;
	gap: 6rpx;
}

.recruit-criteria__label {
	font-size: 22rpx;
	color: $fe-muted;
}

.recruit-criteria__value {
	font-size: 26rpx;
	font-weight: 700;
	color: $fe-foreground;
	word-break: break-all;
}

.recruit-group {
	margin-bottom: 16rpx;
	border-radius: $fe-radius-md;
	border: 1rpx solid $fe-border-light;
	overflow: hidden;
	background: #fff;
}

.recruit-group__head {
	display: flex;
	align-items: center;
	padding: 22rpx 24rpx;
	background: $fe-gray-50;
	gap: 12rpx;
}

.recruit-group__chevron {
	font-size: 22rpx;
	color: $fe-muted;
	width: 28rpx;
	flex-shrink: 0;
}

.recruit-group__name {
	flex: 1;
	min-width: 0;
	font-size: 28rpx;
	font-weight: 700;
	color: $fe-foreground;
}

.recruit-group__count {
	flex-shrink: 0;
	font-size: 26rpx;
	font-weight: 700;
	color: $fe-primary;
}

.recruit-group__body {
	padding: 0 8rpx 8rpx;
}

.recruit-worker {
	display: flex;
	align-items: center;
	gap: 16rpx;
	padding: 20rpx 16rpx;
	margin: 8rpx 8rpx 0;
	border-radius: $fe-radius-sm;
	background: #fff;
	border-left: 6rpx solid $fe-primary;
	box-sizing: border-box;
}

.recruit-worker__avatar {
	width: 72rpx;
	height: 72rpx;
	border-radius: $fe-radius-sm;
	background: $fe-primary-bg;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
}

.recruit-worker__avatar-text {
	font-size: 30rpx;
	font-weight: 800;
	color: $fe-primary;
}

.recruit-worker__main {
	flex: 1;
	min-width: 0;
	display: flex;
	flex-direction: column;
	gap: 6rpx;
}

.recruit-worker__name {
	font-size: 28rpx;
	font-weight: 700;
	color: $fe-foreground;
}

.recruit-worker__meta {
	font-size: 22rpx;
	color: $fe-muted;
	line-height: 1.4;
}

.recruit-check {
	width: 44rpx;
	height: 44rpx;
	border-radius: 50%;
	border: 2rpx solid $fe-border;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: center;
	flex-shrink: 0;
	background: #fff;
}

.recruit-check--on {
	border-color: $fe-primary;
	background: $fe-primary;
}

.recruit-check__mark {
	font-size: 24rpx;
	color: #fff;
	font-weight: 700;
	line-height: 1;
}

.recruit-group__empty {
	padding: 24rpx;
	text-align: center;
}

.recruit-group__empty-text {
	font-size: 24rpx;
	color: $fe-muted;
}

.recruit-footer {
	display: flex;
	gap: 16rpx;
}

.recruit-footer .fe-btn--secondary {
	flex: 0 0 200rpx;
}

.recruit-footer .fe-btn--primary,
.recruit-footer .fe-btn--disabled-look {
	flex: 1;
}

.fe-btn--disabled-look {
	opacity: 0.55;
}
</style>
