<template>
	<view class="acct-pwd-page">
		<view class="acct-pwd-nav" :style="{ paddingTop: statusBar + 'px' }">
			<view class="acct-pwd-nav-row">
				<view class="acct-pwd-back" @tap="goBack">
					<text class="acct-pwd-back-icon">←</text>
				</view>
				<text class="acct-pwd-nav-title">{{ copy.pageTitle }}</text>
				<view class="acct-pwd-nav-placeholder" />
			</view>
		</view>

		<scroll-view
			scroll-y
			class="acct-pwd-scroll"
			:style="{ height: scrollHeight + 'px' }"
		>
			<view class="acct-pwd-body" :style="{ paddingBottom: safeBottom + 'px' }">
				<view class="acct-pwd-hero">
					<view class="acct-pwd-hero-icon-wrap">
						<text class="acct-pwd-hero-icon">🪪</text>
					</view>
					<text class="acct-pwd-hero-title">{{ copy.heroTitle }}</text>
					<text class="acct-pwd-hero-desc">{{ copy.heroDesc }}</text>
				</view>

				<view class="acct-pwd-card">
					<view class="rn-field">
						<text class="rn-field__label">{{ copy.nameLabel }}</text>
						<input
							v-model="form.realname"
							class="rn-field__input"
							:placeholder="copy.namePlaceholder"
							placeholder-class="rn-field__placeholder"
							maxlength="40"
						/>
					</view>
					<view class="rn-field rn-field--last">
						<text class="rn-field__label">{{ copy.idLabel }}</text>
						<input
							v-model="form.idcard"
							class="rn-field__input"
							:placeholder="copy.idPlaceholder"
							placeholder-class="rn-field__placeholder"
							maxlength="48"
						/>
					</view>
				</view>

				<text class="rn-hint">{{ copy.uploadHint }}</text>

				<view class="acct-pwd-card">
					<view class="rn-upload" @tap="pickImage('front')">
						<view class="rn-upload__main">
							<text class="rn-upload__label">{{ copy.docFront }}</text>
							<text class="rn-upload__tip">{{ copy.uploadTap }}</text>
						</view>
						<view class="rn-upload__thumb-wrap">
							<image
								v-if="form.idcard_front"
								class="rn-upload__thumb"
								:src="thumb(form.idcard_front)"
								mode="aspectFill"
							/>
							<text v-else class="rn-upload__plus">+</text>
						</view>
					</view>
					<view class="rn-divider" />
					<view class="rn-upload" @tap="pickImage('back')">
						<view class="rn-upload__main">
							<text class="rn-upload__label">{{ copy.docBack }}</text>
							<text class="rn-upload__tip">{{ copy.uploadTap }}</text>
						</view>
						<view class="rn-upload__thumb-wrap">
							<image
								v-if="form.idcard_back"
								class="rn-upload__thumb"
								:src="thumb(form.idcard_back)"
								mode="aspectFill"
							/>
							<text v-else class="rn-upload__plus">+</text>
						</view>
					</view>
				</view>

				<button
					class="acct-pwd-submit"
					:disabled="submitting"
					:loading="submitting"
					:class="{ 'acct-pwd-submit--busy': submitting }"
					@tap="submit"
				>
					<text class="acct-pwd-submit__text">{{ submitting ? copy.submitting : copy.submit }}</text>
				</button>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import {
	fetchRealnameStatus,
	submitRealnameApplication,
	uploadRealnameImage,
	pickRealnameFieldsFromPayload,
	isValidIdDocumentNumber
} from '@/features/account/realname-gateway'
import { shouldOpenRealnameDetail } from '@/features/mine-panel/realname-bridge'

export default {
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			safeBottom: 0,
			submitting: false,
			uploading: false,
			form: {
				realname: '',
				idcard: '',
				idcard_front: '',
				idcard_back: ''
			}
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				pageTitle: t('user.realnamePageAdd'),
				heroTitle: t('user.realnamePageAdd'),
				heroDesc: t('user.realnameUploadHint'),
				nameLabel: t('user.realnameName'),
				namePlaceholder: t('user.realnameNamePlaceholder'),
				idLabel: t('user.realnameIdLabel'),
				idPlaceholder: t('user.realnameIdPlaceholder'),
				uploadHint: t('user.realnameUploadHint'),
				docFront: t('user.realnameDocFront'),
				docBack: t('user.realnameDocBack'),
				uploadTap: t('user.realnameUploadTap'),
				submit: t('user.realnameSubmit'),
				submitting: t('user.realnameLoading')
			}
		}
	},
	onLoad() {
		const sys = uni.getSystemInfoSync()
		this.statusBar = sys.statusBarHeight || 0
		this.safeBottom = sys.safeAreaInsets ? sys.safeAreaInsets.bottom : 0
		const navH = this.statusBar + uni.upx2px(88)
		this.scrollHeight = (sys.windowHeight || 667) - navH
	},
	onShow() {
		this.refreshFromServer()
	},
	methods: {
		goBack() {
			if (getCurrentPages().length > 1) {
				uni.navigateBack({ delta: 1 })
			} else {
				uni.switchTab({
					url: '/pages/mine/index',
					fail: () => uni.reLaunch({ url: '/pages/mine/index' })
				})
			}
		},
		toast(msg) {
			if (this.$appKit && this.$appKit.msg) this.$appKit.msg(msg)
			else uni.showToast({ title: msg, icon: 'none' })
		},
		thumb(url) {
			if (!url) return ''
			if (this.$appKit && this.$appKit.oss) {
				return this.$appKit.oss(url, 200, 200, 2, '', 'jpg')
			}
			return url
		},
		resetSubmitState() {
			this.submitting = false
			this.uploading = false
			try {
				uni.hideLoading()
			} catch (_) {}
		},
		async refreshFromServer() {
			try {
				const r = await fetchRealnameStatus()
				if (!r.ok) return
				if (shouldOpenRealnameDetail(r.is_real)) {
					uni.redirectTo({ url: '/pages/account/realname-info' })
					return
				}
				const fields = pickRealnameFieldsFromPayload({
					is_real: r.is_real,
					info: r.info
				})
				if (fields.realname) this.form.realname = fields.realname
				if (fields.idcard) this.form.idcard = fields.idcard
				if (fields.idcard_front) this.form.idcard_front = fields.idcard_front
				if (fields.idcard_back) this.form.idcard_back = fields.idcard_back
			} catch (_) {}
		},
		pickImage(side) {
			if (this.uploading || this.submitting) return
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: async (res) => {
					const path = res.tempFilePaths && res.tempFilePaths[0]
					if (!path) return
					this.uploading = true
					uni.showLoading({ mask: true })
					try {
						const url = await uploadRealnameImage(path)
						if (side === 'front') {
							this.form.idcard_front = url
						} else {
							this.form.idcard_back = url
						}
					} catch (err) {
						const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
						if (!bizHandled) {
							this.toast((err && err.message) || this.$t('user.realnameUploadFailed'))
						}
					} finally {
						this.uploading = false
						uni.hideLoading()
					}
				}
			})
		},
		async submit() {
			if (this.submitting) return
			const name = (this.form.realname || '').trim()
			const idcard = (this.form.idcard || '').trim()
			if (!name) {
				this.toast(this.$t('user.realnameFillName'))
				return
			}
			if (!isValidIdDocumentNumber(idcard)) {
				this.toast(this.$t('user.realnameIdInvalid'))
				return
			}
			if (!this.form.idcard_front || !this.form.idcard_back) {
				this.toast(this.$t('user.realnameUploadBothPhotos'))
				return
			}
			this.submitting = true
			uni.showLoading({ mask: true })
			try {
				await submitRealnameApplication({
					realname: name,
					idcard,
					idcard_front: this.form.idcard_front,
					idcard_back: this.form.idcard_back
				})
				this.toast(this.$t('user.realnameSubmitOk'))
				uni.$emit('mine-panel-sync-realname')
				setTimeout(() => {
					uni.redirectTo({ url: '/pages/account/realname-info' })
				}, 400)
			} catch (err) {
				const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
				if (!bizHandled) {
					this.toast((err && err.message) || this.$t('user.realnameNetworkError'))
				}
			} finally {
				this.resetSubmitState()
			}
		}
	}
}
</script>

<style scoped>
@import './account-flow.css';

.rn-field {
	padding-bottom: 24rpx;
	margin-bottom: 24rpx;
	border-bottom: 1rpx solid #f0f2f7;
}

.rn-field--last {
	margin-bottom: 0;
	padding-bottom: 0;
	border-bottom-width: 0;
}

.rn-field__label {
	display: block;
	font-size: 26rpx;
	font-weight: 600;
	color: #4b5563;
	margin-bottom: 12rpx;
}

.rn-field__input {
	width: 100%;
	height: 80rpx;
	font-size: 30rpx;
	color: #1a1d26;
}

.rn-field__placeholder {
	color: #b8bcc8;
}

.rn-hint {
	display: block;
	padding: 0 8rpx 20rpx;
	font-size: 24rpx;
	line-height: 1.5;
	color: #8a8d9e;
}

.rn-upload {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	padding: 8rpx 0;
}

.rn-upload__main {
	flex: 1;
	min-width: 0;
	margin-right: 20rpx;
}

.rn-upload__label {
	display: block;
	font-size: 30rpx;
	color: #1a1d26;
	font-weight: 500;
}

.rn-upload__tip {
	display: block;
	margin-top: 8rpx;
	font-size: 24rpx;
	color: #8a8d9e;
}

.rn-upload__thumb-wrap {
	width: 160rpx;
	height: 100rpx;
	border-radius: 16rpx;
	background-color: #f7f9fc;
	border: 2rpx dashed #d5dbe8;
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: hidden;
	flex-shrink: 0;
}

.rn-upload__thumb {
	width: 100%;
	height: 100%;
}

.rn-upload__plus {
	font-size: 48rpx;
	color: #c5cad6;
	line-height: 1;
}

.rn-divider {
	height: 1rpx;
	background-color: #f0f2f7;
	margin: 20rpx 0;
}
</style>
