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

		<scroll-view
			scroll-y
			class="acct-sec-scroll"
			:style="{ height: scrollHeight + 'px' }"
		>
			<view class="acct-sec-body" :style="{ paddingBottom: safeBottom + 'px' }">
				<view class="acct-sec-card">
					<view
						class="acct-sec-row"
						hover-class="acct-sec-row--press"
						@tap="openPasswordReset"
					>
						<text class="acct-sec-row-label">{{ copy.changePassword }}</text>
						<text class="acct-sec-chevron">›</text>
					</view>
				</view>

				<view class="acct-sec-card acct-sec-card--danger">
					<view
						class="acct-sec-row acct-sec-row--last"
						hover-class="acct-sec-row--press"
						@tap="confirmRemoveAccount"
					>
						<text class="acct-sec-row-label acct-sec-row-label--danger">{{ copy.cancelAccount }}</text>
						<text class="acct-sec-chevron">›</text>
					</view>
				</view>

				<text class="acct-sec-hint">{{ copy.cancelHint }}</text>
			</view>
		</scroll-view>
	</view>
</template>

<script>
import { mapState } from 'vuex'
import { looksLikeHandset, trimHandset } from '@/features/passport/form-rules'
import { removeAccount } from '@/features/account/account-security-gateway'
import { buildRestPath } from '@/core/config/api-paths'
import { post } from '@/core/http/http-client'

export default {
	data() {
		return {
			statusBar: 0,
			scrollHeight: 600,
			safeBottom: 0,
			removing: false
		}
	},
	computed: {
		...mapState('user', {
			profile: (state) => state
		}),
		copy() {
			const t = this.$t.bind(this)
			return {
				title: t('user.securityTitle'),
				changePassword: t('user.securityChangePassword'),
				cancelAccount: t('user.securityCancelAccount'),
				cancelHint: t('user.securityCancelHint'),
				cancelTitle: t('user.securityCancelTitle'),
				cancelMessage: t('user.securityCancelMessage'),
				cancelConfirm: t('user.securityCancelConfirm'),
				cancelKeep: t('user.securityCancelKeep'),
				cancelOk: t('user.securityCancelOk'),
				prompt: t('user.panelPrompt'),
				noMobile: t('user.securityNoMobile'),
				network: t('user.realnameNetworkError')
			}
		}
	},
	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
	},
	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' })
		},
		handsetDigits() {
			return trimHandset(this.profile.mobile || '')
		},
		regionDigits() {
			return String(this.profile.area_code || '852').replace(/^\+/, '')
		},
		openPasswordReset() {
			const params = []
			const handset = this.handsetDigits()
			const region = this.regionDigits()
			if (looksLikeHandset(handset)) {
				params.push(`handset=${encodeURIComponent(handset)}`)
				params.push(`region=${encodeURIComponent(region)}`)
				if (this.profile && this.profile.isLogin) {
					params.push('lock=1')
				}
			}
			const url = params.length
				? `/pages/account/reset-password?${params.join('&')}`
				: '/pages/account/reset-password'
			uni.navigateTo({
				url,
				fail: () => this.$appKit && this.$appKit.to(url)
			})
		},
		confirmRemoveAccount() {
			uni.showModal({
				title: this.copy.cancelTitle,
				content: this.copy.cancelMessage,
				confirmText: this.copy.cancelConfirm,
				cancelText: this.copy.cancelKeep,
				confirmColor: '#ef4444',
				success: (res) => {
					if (res.confirm) this.removeAccountNow()
				}
			})
		},
		async removeAccountNow() {
			if (this.removing) return
			this.removing = true
			uni.showLoading({ mask: true })
			try {
				await removeAccount()
				try {
					await post(buildRestPath('user/logout'))
				} catch (_) {}
				try {
					await this.$store.dispatch('im/pause', true)
				} catch (_) {}
				await this.$store.dispatch('clearSession')
				this.toast(this.copy.cancelOk)
				uni.reLaunch({ url: '/pages/passport/signin?mode=secret' })
			} catch (err) {
				this.toast((err && err.message) || this.copy.network)
			} finally {
				this.removing = false
				uni.hideLoading()
			}
		}
	}
}
</script>

<style scoped>
.acct-sec-page {
	min-height: 100vh;
	background-color: #f4f6fb;
}

.acct-sec-nav {
	background-color: #ffffff;
	border-bottom: 1rpx solid #eef1f6;
}

.acct-sec-nav-row {
	display: flex;
	flex-direction: row;
	align-items: center;
	height: 88rpx;
	padding: 0 24rpx;
	box-sizing: border-box;
}

.acct-sec-back {
	width: 64rpx;
	height: 64rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.acct-sec-back-icon {
	font-size: 40rpx;
	color: #1a1d26;
	line-height: 1;
}

.acct-sec-nav-title {
	flex: 1;
	text-align: center;
	font-size: 32rpx;
	font-weight: 600;
	color: #1a1d26;
}

.acct-sec-nav-placeholder {
	width: 64rpx;
}

.acct-sec-body {
	padding: 24rpx 28rpx 0;
	box-sizing: border-box;
}

.acct-sec-card {
	background-color: #ffffff;
	border-radius: 24rpx;
	box-shadow: 0 6rpx 24rpx rgba(74, 140, 255, 0.06);
	overflow: hidden;
	margin-bottom: 24rpx;
}

.acct-sec-card--danger {
	margin-bottom: 16rpx;
}

.acct-sec-row {
	display: flex;
	flex-direction: row;
	align-items: center;
	justify-content: space-between;
	min-height: 104rpx;
	padding: 0 28rpx;
	border-bottom: 1rpx solid #f0f2f7;
	box-sizing: border-box;
}

.acct-sec-row--last {
	border-bottom-width: 0;
}

.acct-sec-row--press {
	background-color: #f7f9fc;
}

.acct-sec-row-label {
	font-size: 30rpx;
	color: #1a1d26;
}

.acct-sec-row-label--danger {
	color: #ef4444;
}

.acct-sec-chevron {
	font-size: 36rpx;
	color: #c5cad6;
	line-height: 1;
}

.acct-sec-hint {
	display: block;
	padding: 0 8rpx;
	font-size: 24rpx;
	line-height: 1.5;
	color: #8a8d9e;
}
</style>
