<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 v-if="loading" class="rn-loading">
					<text class="rn-loading__txt">{{ copy.loading }}</text>
				</view>

				<template v-else>
					<view class="acct-pwd-card rn-status-card">
						<text class="rn-status-card__label">{{ copy.statusTitle }}</text>
						<text class="rn-status-card__badge" :class="statusBadgeClass">{{ statusLabel }}</text>
					</view>

					<view class="acct-pwd-card">
						<view class="rn-info-row">
							<text class="rn-info-row__label">{{ copy.nameLabel }}</text>
							<text class="rn-info-row__value">{{ info.realname || '-' }}</text>
						</view>
						<view class="rn-info-row rn-info-row--last">
							<text class="rn-info-row__label">{{ copy.idLabel }}</text>
							<text class="rn-info-row__value">{{ maskedId }}</text>
						</view>
					</view>

					<view class="acct-pwd-card">
						<view class="rn-photo-block" @tap="preview('front')">
							<text class="rn-photo-block__label">{{ copy.docFront }}</text>
							<image
								v-if="info.idcard_front"
								class="rn-photo-block__img"
								:src="img(info.idcard_front)"
								mode="widthFix"
							/>
							<text v-else class="rn-photo-block__empty">-</text>
						</view>
						<view class="rn-divider" />
						<view class="rn-photo-block" @tap="preview('back')">
							<text class="rn-photo-block__label">{{ copy.docBack }}</text>
							<image
								v-if="info.idcard_back"
								class="rn-photo-block__img"
								:src="img(info.idcard_back)"
								mode="widthFix"
							/>
							<text v-else class="rn-photo-block__empty">-</text>
						</view>
					</view>

					<button
						v-if="is_real === REALNAME_REJECTED"
						class="acct-pwd-submit"
						@tap="goReapply"
					>
						<text class="acct-pwd-submit__text">{{ copy.reapply }}</text>
					</button>

					<button
						v-if="canDelete"
						class="rn-delete-btn"
						:disabled="deleting"
						:loading="deleting"
						@tap="confirmDelete"
					>
						<text class="rn-delete-btn__text">{{ copy.delete }}</text>
					</button>
				</template>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import {
	fetchRealnameStatus,
	removeRealnameRecord,
	pickRealnameFieldsFromPayload,
	maskIdCard
} from '@/features/account/realname-gateway'
import {
	REALNAME_NONE,
	REALNAME_REJECTED,
	realnameBadgeI18nKey,
	realnameStatusTone
} from '@/features/mine-panel/realname-bridge'

export default {
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			safeBottom: 0,
			loading: true,
			deleting: false,
			is_real: REALNAME_NONE,
			info: {
				id: null,
				realname: '',
				idcard: '',
				idcard_front: '',
				idcard_back: ''
			},
			REALNAME_REJECTED
		}
	},
	computed: {
		copy() {
			const t = this.$t.bind(this)
			return {
				pageTitle: t('user.realnamePageInfo'),
				loading: t('user.realnameLoading'),
				statusTitle: t('user.realnameVerifyStatusTitle'),
				nameLabel: t('user.realnameName'),
				idLabel: t('user.realnameIdLabel'),
				docFront: t('user.realnameDocFront'),
				docBack: t('user.realnameDocBack'),
				reapply: t('user.realnameReapply'),
				delete: t('user.realnameDeleteRecord')
			}
		},
		canDelete() {
			return this.info && this.info.id != null && this.info.id !== ''
		},
		maskedId() {
			return maskIdCard(this.info.idcard)
		},
		statusLabel() {
			return this.$t(realnameBadgeI18nKey(this.is_real))
		},
		statusBadgeClass() {
			return `rn-status-card__badge--${realnameStatusTone(this.is_real)}`
		}
	},
	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.load()
	},
	onUnload() {
		uni.$emit('mine-panel-sync-realname')
	},
	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' })
		},
		img(url) {
			if (!url) return ''
			if (this.$appKit && this.$appKit.oss) {
				return this.$appKit.oss(url, 600, 0, 2, '', 'jpg')
			}
			return url
		},
		async load() {
			this.loading = true
			try {
				const r = await fetchRealnameStatus()
				if (!r.ok) {
					this.toast(this.$t('user.realnameStatusFetchError'))
					return
				}
				this.is_real = r.is_real
				if (r.is_real === REALNAME_NONE) {
					uni.redirectTo({ url: '/pages/account/realname-add' })
					return
				}
				this.info = pickRealnameFieldsFromPayload({
					is_real: r.is_real,
					info: r.info
				})
			} catch (err) {
				const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
				if (!bizHandled) {
					this.toast((err && err.message) || this.$t('user.realnameNetworkError'))
				}
			} finally {
				this.loading = false
			}
		},
		goReapply() {
			uni.redirectTo({ url: '/pages/account/realname-add' })
		},
		confirmDelete() {
			if (!this.canDelete || this.deleting) return
			uni.showModal({
				title: this.$t('user.panelPrompt'),
				content: this.$t('user.realnameDeleteConfirm'),
				confirmText: this.$t('user.realnameDeleteConfirmBtn'),
				cancelText: this.$t('user.realnameModalCancel'),
				confirmColor: '#ef4444',
				success: (m) => {
					if (m.confirm) this.deleteRecord()
				}
			})
		},
		async deleteRecord() {
			if (this.deleting) return
			this.deleting = true
			uni.showLoading({ mask: true })
			try {
				await removeRealnameRecord(this.info.id)
				this.toast(this.$t('user.realnameDeleteSuccess'))
				uni.$emit('mine-panel-sync-realname')
				setTimeout(() => {
					uni.navigateBack({
						fail: () => {
							uni.switchTab({
								url: '/pages/mine/index',
								fail: () => uni.reLaunch({ url: '/pages/mine/index' })
							})
						}
					})
				}, 300)
			} catch (err) {
				const bizHandled = err && (err.kind === 'BUSINESS' || err.kind === 'SILENT')
				if (!bizHandled) {
					this.toast((err && err.message) || this.$t('user.realnameNetworkError'))
				}
			} finally {
				this.deleting = false
				uni.hideLoading()
			}
		},
		preview(side) {
			const front = this.info.idcard_front
			const back = this.info.idcard_back
			const list = [front, back].filter(Boolean)
			if (!list.length) return
			const mapped = list.map((u) => this.img(u))
			const cur = side === 'front' ? front : back
			uni.previewImage({
				urls: mapped,
				current: cur ? this.img(cur) : mapped[0]
			})
		}
	}
}
</script>

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

.rn-loading {
	padding: 120rpx 0;
	text-align: center;
}

.rn-loading__txt {
	font-size: 28rpx;
	color: #8a8d9e;
}

.rn-status-card {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
}

.rn-status-card__label {
	font-size: 30rpx;
	font-weight: 600;
	color: #1a1d26;
}

.rn-status-card__badge {
	font-size: 26rpx;
	font-weight: 600;
	padding: 8rpx 20rpx;
	border-radius: 999rpx;
	background-color: #f3f4f6;
	color: #6b7280;
}

.rn-status-card__badge--pending {
	background-color: #fff7ed;
	color: #ea580c;
}

.rn-status-card__badge--rejected {
	background-color: #fef2f2;
	color: #ef4444;
}

.rn-status-card__badge--approved {
	background-color: #ecfdf5;
	color: #059669;
}

.rn-info-row {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f0f2f7;
}

.rn-info-row--last {
	border-bottom-width: 0;
	padding-bottom: 0;
}

.rn-info-row__label {
	font-size: 28rpx;
	color: #8a8d9e;
	flex-shrink: 0;
	margin-right: 24rpx;
}

.rn-info-row__value {
	flex: 1;
	text-align: right;
	font-size: 28rpx;
	color: #1a1d26;
	word-break: break-all;
}

.rn-photo-block {
	padding: 8rpx 0;
}

.rn-photo-block__label {
	display: block;
	font-size: 28rpx;
	color: #4b5563;
	margin-bottom: 16rpx;
}

.rn-photo-block__img {
	width: 100%;
	max-width: 520rpx;
	border-radius: 16rpx;
	background-color: #f7f9fc;
}

.rn-photo-block__empty {
	font-size: 28rpx;
	color: #c5cad6;
}

.rn-divider {
	height: 1rpx;
	background-color: #f0f2f7;
	margin: 24rpx 0;
}

.rn-delete-btn {
	margin-top: 20rpx;
	width: 100%;
	height: 96rpx;
	line-height: 96rpx;
	border-radius: 48rpx;
	border: 2rpx solid #fecaca;
	background-color: #ffffff;
}

.rn-delete-btn::after {
	border: none;
}

.rn-delete-btn__text {
	font-size: 30rpx;
	color: #ef4444;
	font-weight: 600;
}
</style>
