<template>
	<view class="fe-page job-offer-page">
		<FeMpNavBar title="用工邀请" @back="goBack" />

		<scroll-view scroll-y class="page-scroll" :show-scrollbar="false">
			<view class="page-body">
				<view v-if="loading" class="offer-status">
					<text class="offer-status__text">正在加载用工信息...</text>
				</view>
				<template v-else>
					<view class="offer-hero">
						<text class="offer-hero__eyebrow">扫码登记</text>
						<text class="offer-hero__title">{{ offer.title }}</text>
						<text v-if="offer.enterpriseName" class="offer-hero__corp">{{ offer.enterpriseName }}</text>
						<text v-if="offer.batchId" class="offer-hero__batch">批次 {{ offer.batchId }}</text>
					</view>

					<!-- 多工种：用户自选 -->
					<view v-if="needSelectWorkType" class="offer-section">
						<view class="offer-section__title">选择工种</view>
						<text class="offer-section__hint">本邀请含多个工种，请选择您要申请的岗位</text>
						<view
							v-for="(opt, oIdx) in workTypeOptions"
							:key="opt.optKey"
							:class="opt.optionClass"
							@tap="selectWorkTypeByIndex(oIdx)"
						>
							<view class="offer-type-opt__main">
								<text class="offer-type-opt__name">{{ opt.workType }}</text>
								<text v-if="opt.headcountText" class="offer-type-opt__meta">{{ opt.headcountText }}</text>
								<text v-if="opt.workLocation" class="offer-type-opt__meta">{{ opt.workLocation }}</text>
							</view>
							<view class="offer-type-opt__side">
								<text class="offer-type-opt__wage">{{ opt.wageText }}</text>
								<text class="offer-type-opt__check">{{ opt.selected ? '✓' : '' }}</text>
							</view>
						</view>
					</view>

					<view class="offer-section">
						<view class="offer-section__title">用工信息</view>
						<view class="offer-row">
							<text class="offer-row__label">岗位类型</text>
							<text class="offer-row__value">{{ displayWorkType }}</text>
						</view>
						<view class="offer-row">
							<text class="offer-row__label">工作地点</text>
							<text class="offer-row__value">{{ offer.workLocation }}</text>
						</view>
						<view class="offer-row">
							<text class="offer-row__label">{{ workDurationLabel }}</text>
							<text class="offer-row__value">{{ workDaysText }}</text>
						</view>
						<view class="offer-row">
							<text class="offer-row__label">计划人数</text>
							<text class="offer-row__value">{{ workerCountText }}</text>
						</view>
						<view class="offer-row">
							<text class="offer-row__label">日薪标准</text>
							<text class="offer-row__value">{{ dailyWageText }}</text>
						</view>
						<view class="offer-row">
							<text class="offer-row__label">结算方式</text>
							<text class="offer-row__value">{{ offer.settlementModeLabel || '待确认' }}</text>
						</view>
					</view>

					<view class="offer-pay">
						<text class="offer-pay__label">预估到手</text>
						<text class="offer-pay__amount">{{ offer.netPayText || '—' }}</text>
						<text class="offer-pay__hint">{{ offer.hint }}</text>
						<text v-if="offer.schemeTitle" class="offer-pay__scheme">结算方案：{{ offer.schemeTitle }}</text>
					</view>

					<view class="offer-tips">
						<text class="offer-tips__title">申请说明</text>
						<text class="offer-tips__item">1. 需使用临时工账号登录，并完成实名档案登记</text>
						<text class="offer-tips__item">2. 多工种邀请须先选择工种，再点击「申请加入」</text>
						<text class="offer-tips__item">3. 请确保本人信息真实有效，便于结算到账</text>
					</view>
				</template>
			</view>
		</scroll-view>

		<view class="offer-footer">
			<view
				class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full"
				:class="{ 'fe-btn--disabled': applying || loading }"
				@tap="onApply"
			>{{ applying ? '处理中...' : '申请加入' }}</view>
		</view>
	</view>
</template>

<script>
import FeMpNavBar from '@/components/FeMpNavBar.vue'
import store from '@/common/store.js'
import { showToast } from '@/common/chat-data.js'
import { getPublicDraftDetail } from '@/api/draft.js'
import { applyWorkerRegistration } from '@/api/worker-registration.js'
import {
	loadJobOffer,
	parseJobOfferQuery,
	mergeJobOffer,
	getDemoJobOffer,
	saveJobOffer,
	resolveDraftIdFromQuery,
	resolveSceneFromQuery,
	buildJobOfferFromDraftDetail,
	buildJobOfferShareMessage,
	buildJobOfferPageUrl
} from '@/utils/job-offer.js'
import { formatWorkDurationUnit } from '@/utils/draft.js'

export default {
	components: { FeMpNavBar },
	data() {
		return {
			offer: getDemoJobOffer(),
			loading: false,
			applying: false,
			pageQuery: {}
		}
	},
	computed: {
		workTypeOptions() {
			return (this.offer && Array.isArray(this.offer.workTypeOptions))
				? this.offer.workTypeOptions
				: []
		},
		needSelectWorkType() {
			return !!(this.offer && this.offer.needSelectWorkType && this.workTypeOptions.length > 1)
		},
		displayWorkType() {
			const selected = this.offer && this.offer.selectedWorkType
			if (selected) return selected
			if (this.needSelectWorkType) return '请选择工种'
			return (this.offer && this.offer.workType) || '待确认'
		},
		workDurationUnit() {
			return formatWorkDurationUnit(this.offer && this.offer.settlementMode)
		},
		workDurationLabel() {
			return this.workDurationUnit === '月' ? '工作月数' : '工作天数'
		},
		workDaysText() {
			return this.offer.workDays != null
				? `${this.offer.workDays} ${this.workDurationUnit}`
				: '待确认'
		},
		workerCountText() {
			return this.offer.workerCount != null ? `${this.offer.workerCount} 人` : '待确认'
		},
		dailyWageText() {
			if (this.offer.dailyWage == null) return '待确认'
			const unit = this.workDurationUnit === '月' ? '月' : '天'
			return `${this.offer.dailyWage} 元/${unit}`
		},
		/** 申请 / 公开查询用的 scene（qrToken） */
		applyScene() {
			const o = this.offer || {}
			const raw = o.qrToken || o.scene || o.orderId || ''
			return raw == null ? '' : String(raw).trim()
		}
	},
	onLoad(options) {
		this.pageQuery = options || {}
		this.hydrateOffer(this.pageQuery)
	},
	onShareAppMessage() {
		return buildJobOfferShareMessage(this.offer)
	},
	methods: {
		syncWorkTypeOptionClasses() {
			const list = this.workTypeOptions
			const selected = (this.offer && this.offer.selectedWorkType) || ''
			for (let i = 0; i < list.length; i++) {
				const opt = list[i]
				const on = !!(selected && opt.workType === selected)
				this.$set(opt, 'selected', on)
				this.$set(opt, 'optionClass', on ? 'offer-type-opt offer-type-opt--on' : 'offer-type-opt')
			}
		},
		applySelectedWorkType(opt) {
			if (!opt || !this.offer) return
			this.$set(this.offer, 'selectedWorkType', opt.workType)
			this.$set(this.offer, 'workType', opt.workType)
			if (opt.workLocation) this.$set(this.offer, 'workLocation', opt.workLocation)
			if (opt.workDays != null) this.$set(this.offer, 'workDays', opt.workDays)
			if (opt.workerCount != null) this.$set(this.offer, 'workerCount', opt.workerCount)
			if (opt.dailyWage != null) this.$set(this.offer, 'dailyWage', opt.dailyWage)
			if (opt.settlementMode) {
				this.$set(this.offer, 'settlementMode', opt.settlementMode)
				this.$set(this.offer, 'settlementModeLabel', opt.settlementModeLabel || this.offer.settlementModeLabel)
			}
			if (opt.netPayText) this.$set(this.offer, 'netPayText', opt.netPayText)
			this.syncWorkTypeOptionClasses()
			saveJobOffer(this.offer)
		},
		selectWorkTypeByIndex(oIdx) {
			const opt = this.workTypeOptions[oIdx]
			if (!opt) return
			this.applySelectedWorkType(opt)
		},
		/** 单工种自动选中；多工种恢复已选或保持待选 */
		ensureWorkTypeSelection() {
			const list = this.workTypeOptions
			if (!list.length) return
			if (list.length === 1) {
				this.applySelectedWorkType(list[0])
				return
			}
			const prev = (this.offer && this.offer.selectedWorkType) || ''
			if (prev) {
				const hit = list.find((o) => o && o.workType === prev)
				if (hit) {
					this.applySelectedWorkType(hit)
					return
				}
			}
			this.$set(this.offer, 'selectedWorkType', '')
			this.$set(this.offer, 'workType', '请选择工种')
			this.syncWorkTypeOptionClasses()
		},
		async hydrateOffer(query) {
			const scene = resolveSceneFromQuery(query)
			const fromQuery = parseJobOfferQuery(query)
			const draftId = resolveDraftIdFromQuery(query)
			const cached = loadJobOffer(draftId)
			const demo = getDemoJobOffer(draftId)
			this.offer = mergeJobOffer(demo, cached, fromQuery, scene ? { scene, qrToken: scene } : null)

			if (!scene) {
				this.ensureWorkTypeSelection()
				saveJobOffer(this.offer)
				return
			}

			this.loading = true
			try {
				const detail = await getPublicDraftDetail(scene, { showError: false, auth: false })
				const fromApi = buildJobOfferFromDraftDetail(detail, {
					enterpriseName: (store.getState().enterprise && store.getState().enterprise.name) || '',
					scene,
					qrToken: scene,
					orderId: scene
				})
				if (fromApi) {
					this.offer = mergeJobOffer(this.offer, fromApi, {
						draftId: fromApi.draftId != null ? fromApi.draftId : draftId,
						scene,
						qrToken: scene,
						orderId: scene
					})
				}
				this.ensureWorkTypeSelection()
				saveJobOffer(this.offer)
			} catch (e) {
				showToast((e && (e.msg || e.message)) || '用工信息加载失败')
				this.ensureWorkTypeSelection()
			} finally {
				this.loading = false
			}
		},
		goBack() {
			const pages = getCurrentPages()
			if (pages.length > 1) {
				uni.navigateBack()
				return
			}
			uni.reLaunch({ url: '/packageA/auth/login?role=worker' })
		},
		buildReturnUrl() {
			return buildJobOfferPageUrl(this.offer)
		},
		goWorkerLogin(returnUrl) {
			uni.navigateTo({
				url: `/packageA/auth/login?role=worker&redirect=${encodeURIComponent(returnUrl)}`
			})
		},
		goWorkerRegister(returnUrl) {
			const draftId = this.offer.draftId != null ? this.offer.draftId : ''
			uni.navigateTo({
				url: `/packageA/worker/register?draftId=${encodeURIComponent(draftId)}&redirect=${encodeURIComponent(returnUrl)}`
			})
		},
		async onApply() {
			if (this.applying || this.loading) return

			const scene = this.applyScene
			if (!scene) {
				showToast('缺少邀请参数，请重新扫码或从分享链接进入')
				return
			}

			const confirmedWorkType = String(
				(this.offer && this.offer.selectedWorkType) || ''
			).trim()
			if (this.needSelectWorkType && !confirmedWorkType) {
				showToast('请先选择工种')
				return
			}
			if (!confirmedWorkType) {
				const fallback = String((this.offer && this.offer.workType) || '').trim()
				if (!fallback || fallback === '待确认' || fallback === '请选择工种') {
					showToast('请先选择工种')
					return
				}
			}

			this.applying = true
			try {
				saveJobOffer(this.offer)
				const draftId = this.offer.draftId != null ? this.offer.draftId : ''
				uni.setStorageSync('fe_pending_job_offer_id', draftId)
				const returnUrl = this.buildReturnUrl()
				const s = store.getState()

				if (!s.loggedIn || s.role !== 'worker') {
					showToast('请先登录临时工账号')
					setTimeout(() => this.goWorkerLogin(returnUrl), 300)
					return
				}
				if (!store.isWorkerRegistered()) {
					showToast('请先完成档案登记')
					setTimeout(() => this.goWorkerRegister(returnUrl), 300)
					return
				}

				const workType = confirmedWorkType
					|| String((this.offer && this.offer.workType) || '').trim()
				const res = await applyWorkerRegistration({
					scene,
					confirmedWorkType: workType
				})
				const msg = (res && res.message)
					|| (res && res.status === 'already_applied'
						? '您已申请加入该用工，请等待企业确认'
						: '申请已提交，请等待企业确认')
				showToast(msg)
				setTimeout(() => {
					uni.reLaunch({ url: store.getHomeUrl() })
				}, 600)
			} catch (e) {
				const msg = (e && (e.msg || e.message)) || ''
				if (msg.indexOf('档案登记') >= 0) {
					setTimeout(() => this.goWorkerRegister(this.buildReturnUrl()), 400)
				}
			} finally {
				this.applying = false
			}
		}
	}
}
</script>

<style lang="scss" scoped>
.job-offer-page {
	display: flex;
	flex-direction: column;
	height: 100vh;
	overflow: hidden;
	box-sizing: border-box;
	background: $fe-bg;
}

.page-scroll {
	flex: 1;
	height: 0;
}

.page-body {
	padding: 24rpx 40rpx 40rpx;
	padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
}

.offer-status {
	padding: 80rpx 24rpx;
	text-align: center;
}

.offer-status__text {
	font-size: 28rpx;
	color: $fe-muted;
}

.offer-hero {
	padding: 28rpx 8rpx 36rpx;
}

.offer-hero__eyebrow {
	display: block;
	font-size: 24rpx;
	font-weight: 600;
	color: $fe-primary;
	margin-bottom: 12rpx;
}

.offer-hero__title {
	display: block;
	font-size: 44rpx;
	font-weight: 700;
	color: $fe-foreground;
	line-height: 1.35;
	margin-bottom: 12rpx;
}

.offer-hero__corp,
.offer-hero__batch {
	display: block;
	font-size: 26rpx;
	color: $fe-muted;
	line-height: 1.5;
}

.offer-section {
	background: $fe-surface;
	border-radius: $fe-radius-lg;
	padding: 28rpx 32rpx;
	margin-bottom: 24rpx;
	border: 1rpx solid $fe-border-light;
}

.offer-section__title {
	font-size: 30rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 8rpx;
}

.offer-section__hint {
	display: block;
	font-size: 24rpx;
	color: $fe-muted;
	line-height: 1.5;
	margin-bottom: 20rpx;
}

.offer-type-opt {
	display: flex;
	align-items: center;
	justify-content: space-between;
	gap: 20rpx;
	padding: 24rpx 22rpx;
	margin-bottom: 16rpx;
	border-radius: $fe-radius-md;
	border: 2rpx solid $fe-border-light;
	background: $fe-bg;
	box-sizing: border-box;
}

.offer-type-opt:last-child {
	margin-bottom: 0;
}

.offer-type-opt--on {
	border-color: $fe-primary;
	background: rgba(124, 58, 237, 0.06);
}

.offer-type-opt__main {
	flex: 1;
	min-width: 0;
}

.offer-type-opt__name {
	display: block;
	font-size: 30rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 6rpx;
}

.offer-type-opt__meta {
	display: block;
	font-size: 22rpx;
	color: $fe-muted;
	line-height: 1.45;
}

.offer-type-opt__side {
	flex-shrink: 0;
	display: flex;
	flex-direction: column;
	align-items: flex-end;
	gap: 8rpx;
}

.offer-type-opt__wage {
	font-size: 26rpx;
	font-weight: 700;
	color: $fe-primary-dark;
}

.offer-type-opt__check {
	width: 36rpx;
	height: 36rpx;
	line-height: 36rpx;
	text-align: center;
	font-size: 24rpx;
	font-weight: 700;
	color: $fe-primary;
}

.offer-row {
	display: flex;
	align-items: flex-start;
	justify-content: space-between;
	gap: 24rpx;
	padding: 18rpx 0;
	border-bottom: 1rpx solid $fe-border-light;
}

.offer-row:last-child {
	border-bottom: none;
}

.offer-row__label {
	flex-shrink: 0;
	font-size: 26rpx;
	color: $fe-muted;
}

.offer-row__value {
	flex: 1;
	text-align: right;
	font-size: 26rpx;
	font-weight: 600;
	color: $fe-foreground;
	word-break: break-all;
}

.offer-pay {
	background: linear-gradient(145deg, #F5F3FF 0%, #EEF2FF 100%);
	border: 1rpx solid $fe-primary-100;
	border-radius: $fe-radius-lg;
	padding: 36rpx 32rpx;
	margin-bottom: 24rpx;
	text-align: center;
}

.offer-pay__label {
	display: block;
	font-size: 26rpx;
	color: $fe-muted;
	margin-bottom: 8rpx;
}

.offer-pay__amount {
	display: block;
	font-size: 56rpx;
	font-weight: 700;
	color: $fe-primary-dark;
	line-height: 1.2;
	margin-bottom: 12rpx;
}

.offer-pay__hint,
.offer-pay__scheme {
	display: block;
	font-size: 22rpx;
	color: $fe-muted;
	line-height: 1.5;
}

.offer-pay__scheme {
	margin-top: 6rpx;
}

.offer-tips {
	padding: 8rpx 8rpx 24rpx;
}

.offer-tips__title {
	display: block;
	font-size: 26rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 12rpx;
}

.offer-tips__item {
	display: block;
	font-size: 24rpx;
	color: $fe-muted;
	line-height: 1.7;
}

.offer-footer {
	flex-shrink: 0;
	padding: 20rpx 40rpx calc(20rpx + env(safe-area-inset-bottom));
	background: $fe-surface;
	border-top: 1rpx solid $fe-border-light;
	box-sizing: border-box;
}
</style>
