<template>
	<view class="fe-page">
		<FeMpNavBar title="企业登记" @back="handleBack" />

		<!-- 横向进度条 -->
		<view class="reg-progress">
			<view class="reg-progress__item" :class="{ 'reg-progress__item--active': step >= 1, 'reg-progress__item--done': step > 1 }">
				<view class="reg-progress__dot">{{ step > 1 ? '✓' : '1' }}</view>
				<text class="reg-progress__label">企业绑定</text>
			</view>
			<view class="reg-progress__track">
				<view class="reg-progress__fill" :style="{ width: step >= 2 ? '100%' : '0%' }" />
			</view>
			<view class="reg-progress__item" :class="{ 'reg-progress__item--active': step >= 2 }">
				<view class="reg-progress__dot">2</view>
				<text class="reg-progress__label">法人绑定</text>
			</view>
		</view>

		<scroll-view scroll-y class="page-scroll" :show-scrollbar="false">
			<view class="page-body">
				<!-- 第一步：企业绑定 -->
				<view v-if="step === 1" class="reg-panel">
					<text class="license-upload__tip">请上传营业执照，我们将自动识别信息</text>
					<view class="license-upload" @tap="chooseLicense">
						<image
							v-if="licenseImage"
							class="license-upload__preview"
							:src="licenseImage"
							mode="aspectFill"
						/>
						<view v-else class="license-upload__placeholder">
							<view class="license-upload__icon">
								<text class="license-upload__icon-text">📷</text>
							</view>
							<text class="license-upload__title">点击拍照或上传营业执照</text>
							<text class="license-upload__hint">支持 JPG、PNG 格式</text>
						</view>
					</view>
					<text v-if="licenseImage" class="license-upload__change" @tap.stop="chooseLicense">重新上传</text>

					<view class="reg-divider">
						<view class="reg-divider__line" />
						<text class="reg-divider__text">或手动填报</text>
						<view class="reg-divider__line" />
					</view>

					<view class="fe-form-group">
						<text class="fe-form-label">企业名称 <text class="reg-required">*</text></text>
						<input class="fe-form-input" v-model="form.name" placeholder="请输入企业全称" />
					</view>
					<view class="fe-form-group">
						<text class="fe-form-label">统一社会信用代码 <text class="reg-required">*</text></text>
						<input
							class="fe-form-input"
							v-model="form.creditCode"
							placeholder="请输入18位统一社会信用代码"
						/>
					</view>
				</view>

				<!-- 第二步：法人绑定 -->
				<view v-else class="reg-panel">
					<view class="reg-panel__title">法人信息</view>
					<view class="reg-panel__desc">请填写法人真实信息，用于企业认证</view>

					<view class="fe-form-group">
						<text class="fe-form-label">法人姓名 <text class="reg-required">*</text></text>
						<input class="fe-form-input" v-model="form.legalPersonName" placeholder="请输入法人姓名" />
					</view>
					<view class="fe-form-group">
						<text class="fe-form-label">法人身份证号 <text class="reg-required">*</text></text>
						<input class="fe-form-input" v-model="form.legalPersonIdCard" placeholder="请输入18位身份证号码" />
					</view>
					<view class="fe-form-group">
						<text class="fe-form-label">法人手机号 <text class="reg-required">*</text></text>
						<input
							class="fe-form-input"
							v-model="form.legalPersonMobile"
							type="number"
							maxlength="11"
							placeholder="请输入法人手机号"
						/>
					</view>
					<view class="fe-form-group">
						<text class="fe-form-label">经营地址 <text class="reg-required">*</text></text>
						<textarea
							class="reg-textarea"
							v-model="form.businessAddress"
							placeholder="请输入企业经营地址"
							:maxlength="500"
							auto-height
						/>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部固定按钮 -->
		<view class="reg-footer">
			<view v-if="step === 1" class="reg-footer__single">
				<view class="fe-btn fe-btn--primary fe-btn--lg fe-btn--full" @tap="nextStep">下一步</view>
			</view>
			<view v-else class="reg-footer__row">
				<view class="fe-btn fe-btn--secondary fe-btn--lg reg-footer__btn" @tap="prevStep">上一步</view>
				<view
					class="fe-btn fe-btn--primary fe-btn--lg reg-footer__btn"
					:class="{ 'fe-btn--disabled': submitting }"
					@tap="submit"
				>{{ submitting ? '提交中...' : '提交' }}</view>
			</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 { registerEnterprise } from '@/api/enterprise.js'
import { validateForm } from '@/utils/formRules.js'

export default {
	components: { FeMpNavBar },
	data() {
		return {
			step: 1,
			submitting: false,
			licenseImage: '',
			/** 后端 register 必填：认证成功后回填草稿/订单 enterprise_id */
			draftId: null,
			form: {
				name: '',
				creditCode: '',
				legalPersonName: '',
				legalPersonIdCard: '',
				legalPersonMobile: '',
				businessAddress: ''
			}
		}
	},
	onLoad(options) {
		const raw = options && (options.draftId != null ? options.draftId : options.draft_id)
		if (raw != null && raw !== '') {
			const n = Number(raw)
			this.draftId = Number.isNaN(n) ? raw : n
		}
	},
	onShow() {
		const s = store.getState()
		if (!s.loggedIn || s.role !== 'enterprise') {
			uni.redirectTo({ url: '/packageA/auth/login' })
			return
		}
		if (store.isEnterpriseRegistered()) {
			uni.reLaunch({ url: store.getHomeUrl() })
		}
	},
	methods: {
		handleBack() {
			if (this.step === 2) {
				this.step = 1
				return
			}
			store.logout()
			uni.redirectTo({ url: '/packageA/auth/login' })
		},
		chooseLicense() {
			uni.showActionSheet({
				itemList: ['拍照', '从相册选择'],
				success: (res) => {
					const sourceType = res.tapIndex === 0 ? ['camera'] : ['album']
					uni.chooseImage({
						count: 1,
						sizeType: ['compressed'],
						sourceType,
						success: (imgRes) => {
							this.licenseImage = imgRes.tempFilePaths[0]
							showToast('营业执照识别待接入，请手动填报')
						}
					})
				}
			})
		},
		nextStep() {
			const validation = validateForm(this.form, {
				name: { label: '企业名称', rules: ['required'] },
				creditCode: { label: '统一社会信用代码', rules: ['creditCode'] }
			})
			if (!validation.valid) {
				showToast(validation.message)
				return
			}
			this.step = 2
		},
		prevStep() {
			this.step = 1
		},
		submit() {
			if (this.submitting) return

			const validation = validateForm(this.form, {
				legalPersonName: { label: '法人姓名', rules: ['realName'] },
				legalPersonIdCard: { label: '法人身份证号', rules: ['idCard'] },
				legalPersonMobile: { label: '法人手机号', rules: ['mobile'] },
				businessAddress: { label: '经营地址', rules: ['required'] }
			})
			if (!validation.valid) {
				showToast(validation.message)
				return
			}

			if (this.draftId == null || this.draftId === '') {
				showToast('缺少关联草稿，请从办理进度进入企业认证')
				return
			}

			const legalName = this.form.legalPersonName.trim()
			const payload = {
				draftId: Number(this.draftId),
				name: this.form.name.trim(),
				creditCode: this.form.creditCode.trim().toUpperCase(),
				legalPerson: legalName,
				registeredAddress: this.form.businessAddress.trim(),
				contactName: legalName,
				contactMobile: this.form.legalPersonMobile.trim()
			}

			this.submitting = true
			registerEnterprise(payload)
				.then((res) => {
					store.registerEnterprise({
						name: (res && res.name) || payload.name,
						code: (res && res.creditCode) || payload.creditCode,
						creditCode: (res && res.creditCode) || payload.creditCode,
						legalPerson: (res && res.legalPerson) || payload.legalPerson,
						registeredAddress: (res && res.registeredAddress) || payload.registeredAddress,
						contactName: (res && res.contactName) || payload.contactName,
						contactMobileMask: res && res.contactMobileMask,
						enterpriseId: res && res.enterpriseId,
						enterpriseCode: res && res.enterpriseCode,
						authStatus: res && res.authStatus
					})
					showToast('登记成功！')
					setTimeout(() => {
						uni.reLaunch({ url: store.getHomeUrl() })
					}, 800)
				})
				.catch(() => {})
				.finally(() => {
					this.submitting = false
				})
		}
	}
}
</script>

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

.reg-progress {
	display: flex;
	align-items: center;
	padding: 32rpx 48rpx 24rpx;
	background: $fe-surface;
}

.reg-progress__item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 12rpx;
	flex-shrink: 0;
	width: 140rpx;
}

.reg-progress__dot {
	width: 48rpx;
	height: 48rpx;
	border-radius: 50%;
	background: $fe-gray-200;
	color: $fe-gray-500;
	font-size: 24rpx;
	font-weight: 700;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: all 0.2s;
}

.reg-progress__label {
	font-size: 24rpx;
	color: $fe-gray-500;
	white-space: nowrap;
}

.reg-progress__item--active .reg-progress__dot {
	background: $fe-primary;
	color: #fff;
}

.reg-progress__item--active .reg-progress__label {
	color: $fe-primary;
	font-weight: 600;
}

.reg-progress__item--done .reg-progress__dot {
	background: $fe-primary-bg;
	color: $fe-primary;
}

.reg-progress__track {
	flex: 1;
	height: 4rpx;
	background: $fe-gray-200;
	border-radius: 9999rpx;
	margin: 0 16rpx;
	margin-bottom: 36rpx;
	overflow: hidden;
}

.reg-progress__fill {
	height: 100%;
	background: $fe-primary;
	border-radius: 9999rpx;
	transition: width 0.25s ease;
}

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

.page-body {
	padding: 24rpx 32rpx 32rpx;
}

.reg-panel {
	background: $fe-surface;
	border-radius: $fe-radius-xl;
	padding: 40rpx 32rpx;
	box-shadow: 0 8rpx 24rpx rgba(15, 23, 42, 0.06);
}

.reg-panel__title {
	font-size: 32rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 8rpx;
}

.reg-panel__desc {
	font-size: 26rpx;
	color: $fe-gray-500;
	margin-bottom: 32rpx;
}

.reg-required {
	color: #EF4444;
}

.license-upload__tip {
	display: block;
	font-size: 28rpx;
	font-weight: 600;
	color: $fe-gray-700;
	margin-bottom: 24rpx;
	line-height: 1.5;
}

.license-upload {
	width: 100%;
	height: 360rpx;
	border: 2rpx dashed $fe-gray-300;
	border-radius: $fe-radius-lg;
	background: #FAFAFC;
	overflow: hidden;
	box-sizing: border-box;
}

.license-upload__placeholder {
	height: 100%;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	gap: 16rpx;
	padding: 32rpx;
}

.license-upload__icon {
	width: 112rpx;
	height: 112rpx;
	border-radius: 50%;
	background: $fe-primary-bg;
	display: flex;
	align-items: center;
	justify-content: center;
}

.license-upload__icon-text {
	font-size: 52rpx;
	line-height: 1;
}

.license-upload__title {
	font-size: 28rpx;
	font-weight: 600;
	color: $fe-gray-700;
}

.license-upload__hint {
	font-size: 24rpx;
	color: $fe-gray-400;
}

.license-upload__preview {
	width: 100%;
	height: 100%;
}

.license-upload__change {
	display: block;
	text-align: center;
	margin-top: 16rpx;
	font-size: 26rpx;
	color: $fe-primary;
	font-weight: 500;
}

.reg-divider {
	display: flex;
	align-items: center;
	gap: 24rpx;
	margin: 40rpx 0 32rpx;
}

.reg-divider__line {
	flex: 1;
	height: 1rpx;
	background: $fe-gray-200;
}

.reg-divider__text {
	font-size: 24rpx;
	color: $fe-gray-400;
	white-space: nowrap;
}

.reg-textarea {
	width: 100%;
	min-height: 180rpx;
	padding: 24rpx 32rpx;
	border: 1rpx solid $fe-gray-300;
	border-radius: $fe-radius-md;
	font-size: 30rpx;
	background: $fe-surface;
	color: $fe-foreground;
	box-sizing: border-box;
	line-height: 1.5;
}

.reg-footer {
	flex-shrink: 0;
	padding: 24rpx 32rpx;
	padding-bottom: calc(24rpx + #{$fe-h-safe-bottom});
	background: $fe-surface;
	border-top: 1rpx solid $fe-gray-200;
	box-shadow: 0 -8rpx 24rpx rgba(15, 23, 42, 0.04);
}

.reg-footer__single {
	width: 100%;
}

.reg-footer__row {
	display: flex;
	gap: 24rpx;
}

.reg-footer__btn {
	flex: 1;
}

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