<template>
	<view class="fe-bottom-sheet fe-bottom-sheet--cert" :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">{{ sourceText }}</view>

		<!-- 两步进度 -->
		<view class="cert-progress">
			<view
				class="cert-progress__item"
				:class="{
					'cert-progress__item--active': readonly || step >= 1,
					'cert-progress__item--done': readonly || step > 1
				}"
			>
				<view class="cert-progress__dot">{{ (readonly || step > 1) ? '✓' : '1' }}</view>
				<text class="cert-progress__label">企业绑定</text>
			</view>
			<view class="cert-progress__track">
				<view class="cert-progress__fill" :style="{ width: (readonly || step >= 2) ? '100%' : '0%' }" />
			</view>
			<view
				class="cert-progress__item"
				:class="{
					'cert-progress__item--active': readonly || step >= 2,
					'cert-progress__item--done': readonly
				}"
			>
				<view class="cert-progress__dot">{{ readonly ? '✓' : '2' }}</view>
				<text class="cert-progress__label">法人绑定</text>
			</view>
		</view>

		<scroll-view scroll-y class="fe-sheet-body fe-sheet-body--cert" :show-scrollbar="false">
			<view class="fe-sheet-body__inner">
				<!-- 只读：一页展示全部已认证信息 -->
				<view v-if="readonly">
					<view v-if="loadingDetail" class="cert-readonly-loading">
						<text class="cert-readonly-loading__text">加载认证信息中...</text>
					</view>
					<template v-else>
						<view class="cert-readonly-badge">✓ 已完成企业认证（仅查看）</view>
						<view v-if="loadError" class="cert-prefill-tip">
							<text class="cert-prefill-tip__text">{{ loadError }}</text>
						</view>
						<view class="fe-form-group">
							<text class="fe-form-label">企业名称</text>
							<input class="fe-form-input fe-form-input--readonly" :value="form.name" disabled />
						</view>
						<view class="fe-form-group">
							<text class="fe-form-label">统一社会信用代码</text>
							<input class="fe-form-input fe-form-input--readonly" :value="form.creditCode" disabled />
						</view>
						<view class="fe-form-group">
							<text class="fe-form-label">法人姓名</text>
							<input class="fe-form-input fe-form-input--readonly" :value="form.legalPersonName" disabled />
						</view>
						<view class="fe-form-group">
							<text class="fe-form-label">法人身份证号</text>
							<input class="fe-form-input fe-form-input--readonly" :value="form.legalPersonIdCard" disabled />
						</view>
						<view class="fe-form-group">
							<text class="fe-form-label">联系人手机号</text>
							<input class="fe-form-input fe-form-input--readonly" :value="form.legalPersonMobile" disabled />
						</view>
						<view class="fe-form-group">
							<text class="fe-form-label">经营地址</text>
							<textarea
								class="cert-textarea cert-textarea--readonly"
								:value="form.businessAddress"
								disabled
								:maxlength="500"
								auto-height
							/>
						</view>
					</template>
				</view>

				<!-- 可编辑：两步填报（流程 active：需提交；有 getInfo 历史则预填） -->
				<view v-else-if="step === 1">
					<view v-if="profilePrefill" class="cert-prefill-tip">
						<text class="cert-prefill-tip__text">已带入上次认证信息，请核对后提交本单认证</text>
					</view>
					<text class="cert-tip">请上传营业执照，我们将自动识别信息</text>
					<view class="cert-license" @tap="chooseLicense">
						<image
							v-if="licenseImage"
							class="cert-license__preview"
							:src="licenseImage"
							mode="aspectFill"
						/>
						<view v-else class="cert-license__placeholder">
							<text class="cert-license__icon">📷</text>
							<text class="cert-license__title">点击拍照或上传营业执照</text>
							<text class="cert-license__hint">支持 JPG、PNG 格式</text>
						</view>
					</view>
					<text v-if="licenseImage" class="cert-license__change" @tap.stop="chooseLicense">重新上传</text>

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

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

				<view v-else>
					<view class="cert-section-title">法人信息</view>
					<view class="cert-section-desc">请填写法人真实信息，用于企业认证</view>
					<view class="fe-form-group">
						<text class="fe-form-label">法人姓名 <text class="cert-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="cert-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="cert-required">*</text></text>
						<input
							class="fe-form-input"
							v-model="form.legalPersonMobile"
							type="number"
							maxlength="11"
							:placeholder="mobilePlaceholder"
						/>
						<text v-if="mobileNeedReenter" class="cert-field-hint">账号手机为脱敏号，请重新输入完整手机号</text>
					</view>
					<view class="fe-form-group">
						<text class="fe-form-label">经营地址 <text class="cert-required">*</text></text>
						<textarea
							class="cert-textarea"
							v-model="form.businessAddress"
							placeholder="请输入企业经营地址"
							:maxlength="500"
							auto-height
						/>
					</view>
				</view>
			</view>
		</scroll-view>

		<view class="fe-sheet-footer">
			<template v-if="readonly">
				<view class="fe-btn fe-btn--primary fe-btn--lg" @tap="onClose">关闭</view>
			</template>
			<template v-else-if="step === 1">
				<view class="fe-btn fe-btn--secondary fe-btn--lg" @tap="onClose">取消</view>
				<view class="fe-btn fe-btn--primary fe-btn--lg" @tap="nextStep">下一步</view>
			</template>
			<template v-else>
				<view class="fe-btn fe-btn--secondary fe-btn--lg" @tap="prevStep">上一步</view>
				<view
					class="fe-btn fe-btn--primary fe-btn--lg"
					:class="{ 'fe-btn--disabled': submitting }"
					@tap="submit"
				>{{ submitting ? '提交中...' : '提交认证' }}</view>
			</template>
		</view>
	</view>
</template>

<script>
import store from '@/common/store.js'
import { showToast } from '@/common/chat-data.js'
import { getEnterpriseByDraft, registerEnterprise } from '@/api/enterprise.js'
import { validateForm } from '@/utils/formRules.js'
import {
	loadEnterpriseCertForm,
	saveEnterpriseCertForm
} from '@/utils/enterprise-cert-cache.js'

export default {
	name: 'FeEnterpriseCertSheet',
	props: {
		active: { type: Boolean, default: false },
		draftId: { type: [Number, String], default: null },
		readonly: { type: Boolean, default: false }
	},
	data() {
		return {
			step: 1,
			submitting: false,
			loadingDetail: false,
			loadError: '',
			licenseImage: '',
			/** 是否从 getInfo 带回了历史企业信息 */
			profilePrefill: false,
			/** 手机号为脱敏，提交前需重填 */
			mobileNeedReenter: false,
			maskedMobileHint: '',
			form: {
				name: '',
				creditCode: '',
				legalPersonName: '',
				legalPersonIdCard: '',
				legalPersonMobile: '',
				businessAddress: ''
			}
		}
	},
	computed: {
		sourceText() {
			if (this.readonly) return '认证信息仅供查看，不可修改'
			if (this.profilePrefill) return '已带入上次认证信息，核对后提交即可'
			if (this.draftId != null && this.draftId !== '') {
				return `关联草稿 #${this.draftId} · 请完成企业认证`
			}
			return '完成认证后可继续办理流程'
		},
		mobilePlaceholder() {
			if (this.mobileNeedReenter && this.maskedMobileHint) {
				return `原号码 ${this.maskedMobileHint}，请重新输入`
			}
			return '请输入法人手机号'
		}
	},
	watch: {
		active(val) {
			if (val) this.initSheet()
		},
		draftId() {
			if (this.active) this.initSheet()
		},
		readonly() {
			if (this.active) this.initSheet()
		}
	},
	methods: {
		emptyForm() {
			return {
				name: '',
				creditCode: '',
				legalPersonName: '',
				legalPersonIdCard: '',
				legalPersonMobile: '',
				businessAddress: ''
			}
		},
		pickField(raw, camel, snake) {
			if (!raw || typeof raw !== 'object') return ''
			if (raw[camel] != null && raw[camel] !== '') return raw[camel]
			if (raw[snake] != null && raw[snake] !== '') return raw[snake]
			return ''
		},
		isMaskedValue(value) {
			return value != null && value !== '' && /\*/.test(String(value))
		},
		async initSheet() {
			this.step = 1
			this.submitting = false
			this.loadingDetail = false
			this.loadError = ''
			this.licenseImage = ''
			this.profilePrefill = false
			this.mobileNeedReenter = false
			this.maskedMobileHint = ''
			this.form = this.emptyForm()
			// 查看认证：按草稿 ID 查企业信息
			if (this.readonly) {
				await this.loadByDraft()
				return
			}
			// 去认证：优先用上次提交保存在本地的表单；没有再回退 getInfo
			if (this.fillFromStorage()) return
			try {
				await store.syncProfile({ showError: false })
			} catch (e) {
				// 忽略：仍尝试用本地缓存回填
			}
			this.fillFromProfile()
		},
		/** GET /enterprise/by-draft/{draftId} */
		async loadByDraft() {
			if (this.draftId == null || this.draftId === '') {
				this.loadError = '缺少草稿信息'
				return
			}
			this.loadingDetail = true
			this.loadError = ''
			try {
				const raw = await getEnterpriseByDraft(this.draftId, { showError: false })
				this.applyEnterpriseInfo(raw || {})
				if (!this.form.name && !this.form.creditCode) {
					this.loadError = '暂无本单关联的企业认证信息'
				}
			} catch (e) {
				this.loadError = (e && (e.msg || e.message)) || '企业信息加载失败'
				showToast(this.loadError)
			} finally {
				this.loadingDetail = false
			}
		},
		applyEnterpriseInfo(raw) {
			const name = this.pickField(raw, 'name', 'name')
			const creditCode = this.pickField(raw, 'creditCode', 'credit_code')
			const legalPerson = this.pickField(raw, 'legalPerson', 'legal_person')
				|| this.pickField(raw, 'contactName', 'contact_name')
			const address = this.pickField(raw, 'registeredAddress', 'registered_address')
			const mobilePlain = this.pickField(raw, 'contactMobile', 'contact_mobile')
			const mobileMask = this.pickField(raw, 'contactMobileMask', 'contact_mobile_mask')
			const idCardPlain = this.pickField(raw, 'legalPersonIdCard', 'legal_person_id_card')
			const idCardMask = this.pickField(raw, 'legalPersonIdCardMask', 'legal_person_id_card_mask')
			this.form = {
				name,
				creditCode,
				legalPersonName: legalPerson,
				legalPersonIdCard: idCardPlain || idCardMask || '',
				legalPersonMobile: mobilePlain || mobileMask || '',
				businessAddress: address
			}
		},
		/** 从本地存储回填上次提交的认证数据 */
		fillFromStorage() {
			const cached = loadEnterpriseCertForm()
			if (!cached) return false
			this.profilePrefill = true
			this.mobileNeedReenter = false
			this.maskedMobileHint = ''
			this.form = {
				name: cached.name || '',
				creditCode: cached.creditCode || '',
				legalPersonName: cached.legalPersonName || '',
				legalPersonIdCard: cached.legalPersonIdCard || '',
				legalPersonMobile: cached.legalPersonMobile || '',
				businessAddress: cached.businessAddress || ''
			}
			return true
		},
		fillFromProfile() {
			const s = store.getState()
			const ent = (s && s.enterprise) || {}
			const name = ent.name || ''
			const creditCode = ent.creditCode || ent.code || ''
			const legalPerson = ent.legalPerson || ent.contactName || ''
			const address = ent.registeredAddress || ''
			// 优先明文：contactMobile / legalPersonIdCard；无明文再用脱敏展示
			const mobilePlain = ent.contactMobile || ent.contact_mobile || ''
			const mobileMask = ent.contactMobileMask || ent.contact_mobile_mask || ''
			const idCardPlain = ent.legalPersonIdCard || ent.legal_person_id_card || ''
			const idCardMask = ent.legalPersonIdCardMask || ent.legal_person_id_card_mask || ''
			const hasProfile = !!(
				name || creditCode || legalPerson || address
				|| mobilePlain || mobileMask || idCardPlain || idCardMask
			)
			if (!hasProfile) return

			const mobileForEdit = mobilePlain || ''
			const idCardForEdit = idCardPlain || ''
			const mobileMaskedOnly = !mobilePlain && this.isMaskedValue(mobileMask)

			this.profilePrefill = true
			this.mobileNeedReenter = mobileMaskedOnly
			this.maskedMobileHint = mobileMaskedOnly ? String(mobileMask) : ''

			this.form = {
				name,
				creditCode,
				legalPersonName: legalPerson,
				legalPersonIdCard: idCardForEdit,
				legalPersonMobile: mobileForEdit,
				businessAddress: address
			}
		},
		onClose() {
			this.$emit('close')
		},
		chooseLicense() {
			if (this.readonly) return
			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() {
			if (this.readonly) return
			const validation = validateForm(this.form, {
				name: { label: '企业名称', rules: ['required'] },
				creditCode: { label: '统一社会信用代码', rules: ['creditCode'] }
			})
			if (!validation.valid) {
				showToast(validation.message)
				return
			}
			this.step = 2
		},
		prevStep() {
			if (this.readonly) return
			this.step = 1
		},
		submit() {
			if (this.readonly || this.submitting) return
			if (this.draftId == null || this.draftId === '') {
				showToast('缺少关联草稿，请从办理进度进入认证')
				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
			}

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

			this.submitting = true
			registerEnterprise(payload)
				.then((res) => {
					// 提交成功：整份替换本地认证表单缓存，供下次去认证回填
					saveEnterpriseCertForm({
						name: payload.name,
						creditCode: payload.creditCode,
						legalPersonName: legalName,
						legalPersonIdCard: idCard,
						legalPersonMobile: mobile,
						businessAddress: payload.registeredAddress
					})
					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,
						legalPersonIdCard: payload.legalPersonIdCard,
						registeredAddress: (res && res.registeredAddress) || payload.registeredAddress,
						contactName: (res && res.contactName) || payload.contactName,
						contactMobile: payload.contactMobile,
						contactMobileMask: res && res.contactMobileMask,
						enterpriseId: res && res.enterpriseId,
						enterpriseCode: res && res.enterpriseCode,
						authStatus: res && res.authStatus
					})
					showToast('认证成功！')
					this.$emit('success', {
						draftId: payload.draftId,
						result: res
					})
				})
				.catch(() => {})
				.finally(() => {
					this.submitting = false
				})
		}
	}
}
</script>

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

.fe-sheet-close {
	font-size: 32rpx;
	color: $fe-muted;
	padding: 8rpx 12rpx;
	line-height: 1;
}

.fe-sheet-body--cert {
	flex: 1;
	min-height: 0;
	height: 0;
}

.cert-progress {
	display: flex;
	align-items: center;
	padding: 8rpx 40rpx 20rpx;
	flex-shrink: 0;
}

.cert-progress__item {
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 8rpx;
	flex-shrink: 0;
	width: 120rpx;
}

.cert-progress__dot {
	width: 40rpx;
	height: 40rpx;
	border-radius: 50%;
	background: $fe-gray-200;
	color: $fe-muted;
	font-size: 22rpx;
	font-weight: 700;
	display: flex;
	align-items: center;
	justify-content: center;
}

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

.cert-progress__label {
	font-size: 22rpx;
	color: $fe-muted;
}

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

.cert-progress__track {
	flex: 1;
	height: 4rpx;
	background: $fe-border-light;
	border-radius: 2rpx;
	overflow: hidden;
	margin: 0 8rpx 28rpx;
}

.cert-progress__fill {
	height: 100%;
	background: $fe-primary;
	transition: width 0.2s;
}

.cert-readonly-badge {
	margin-bottom: 24rpx;
	padding: 16rpx 20rpx;
	border-radius: $fe-radius-sm;
	background: $fe-success-light;
	color: $fe-success;
	font-size: 24rpx;
	font-weight: 600;
}

.cert-readonly-loading {
	padding: 80rpx 24rpx;
	text-align: center;
}

.cert-readonly-loading__text {
	font-size: 28rpx;
	color: $fe-muted;
}

.fe-form-input--readonly,
.cert-textarea--readonly {
	background: $fe-gray-100;
	color: $fe-gray-700;
	opacity: 1;
}

.cert-prefill-tip {
	margin-bottom: 16rpx;
	padding: 16rpx 20rpx;
	border-radius: $fe-radius-sm;
	background: rgba(124, 58, 237, 0.08);
}

.cert-prefill-tip__text {
	font-size: 24rpx;
	color: $fe-primary;
	line-height: 1.45;
	font-weight: 600;
}

.cert-tip {
	display: block;
	font-size: 24rpx;
	color: $fe-muted;
	margin-bottom: 16rpx;
}

.cert-field-hint {
	display: block;
	margin-top: 8rpx;
	font-size: 22rpx;
	color: #B45309;
	line-height: 1.4;
}

.cert-license {
	border: 2rpx dashed $fe-border;
	border-radius: $fe-radius-md;
	background: $fe-gray-50;
	overflow: hidden;
	min-height: 220rpx;
}

.cert-license__preview {
	width: 100%;
	height: 280rpx;
}

.cert-license__placeholder {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 48rpx 24rpx;
	gap: 8rpx;
}

.cert-license__icon {
	font-size: 48rpx;
	line-height: 1.2;
}

.cert-license__title {
	font-size: 26rpx;
	font-weight: 600;
	color: $fe-foreground;
}

.cert-license__hint {
	font-size: 22rpx;
	color: $fe-muted-light;
}

.cert-license__change {
	display: block;
	margin-top: 12rpx;
	font-size: 24rpx;
	color: $fe-primary;
	text-align: center;
}

.cert-divider {
	display: flex;
	align-items: center;
	gap: 16rpx;
	margin: 28rpx 0 20rpx;
}

.cert-divider__line {
	flex: 1;
	height: 1rpx;
	background: $fe-border-light;
}

.cert-divider__text {
	font-size: 22rpx;
	color: $fe-muted-light;
}

.cert-required {
	color: $fe-danger;
}

.cert-section-title {
	font-size: 30rpx;
	font-weight: 700;
	color: $fe-foreground;
	margin-bottom: 8rpx;
}

.cert-section-desc {
	font-size: 24rpx;
	color: $fe-muted;
	margin-bottom: 24rpx;
}

.cert-textarea {
	width: 100%;
	min-height: 140rpx;
	padding: 20rpx 24rpx;
	box-sizing: border-box;
	background: $fe-gray-50;
	border: 1rpx solid $fe-border;
	border-radius: $fe-radius-sm;
	font-size: 28rpx;
	color: $fe-foreground;
}

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