<script setup>
	// 支付密码
	import {
		computed,
		defineExpose,
		ref,
		getCurrentInstance,
		defineEmits
	} from 'vue';
	import {
		useStore
	} from 'vuex'
	// 工具库
	import util from '@/common/js/util.js'
	// api
	import api from '@/api/index.js'
	// 加密
	import CryptoJS from 'crypto-js';
	// 
	const props = defineProps({
		// 是否验证
		check: {
			type: Boolean,
			default: false
		}
	})

	// 
	const {
		proxy
	} = getCurrentInstance()
	// 触发父组件事件
	const emits = defineEmits(['confirm'])
	// 仓库
	const store = useStore()
	// 密码
	const pwd = ref('')
	// 用户信息
	const userinfo = computed(() => store.state.userinfo)

	// 打开弹窗
	function open() {
		// 如果用户没有二级密码
		if (userinfo.value.hasSecondCipher) {
			proxy.$refs.pwdRef.open()
		} else {
			uni.navigateTo({
				url: '/pages/mine/setting/secondPwd'
			})
		}
	}

	// 关闭弹窗
	function close() {
		proxy.$refs.pwdRef.close()

		setTimeout(() => {
			// 清空二级密码
			pwd.value = ''
		}, 500)
	}

	// 确认
	function handleConfirm() {
		if (!/^\d{6}$/.test(pwd.value)) {
			util.alert('二级密码不正确')
			return
		}
		// 加密后的密码
		let password = CryptoJS.MD5(pwd.value).toString()
		// 
		if (!props.check) {
			// 验证
			emits('confirm', password)
			close()
			return
		}
		// 验证二级密码
		api.mine.checkSecondLevelCipher({
			data: {
				secondLevelCipher: password,
			}
		}).then(rs => {
			if (rs.code == 200) {
				emits('confirm', password)
				close()
				return
			}
			util.alert({
				content: rs.msg,
				showCancel: false,
			})
		})
	}

	// 
	defineExpose({
		open,
		close,
	})
</script>

<template>
	<uni-popup ref="pwdRef" type="center">
		<view class="pwdAlt popMid plr30 bfff">
			<view class="title mtb30 f30">验证二级密码</view>

			<view class="inputBox mtb20 plr30">
				<input v-model="pwd" :maxlength="6" type="number" placeholder="输入二级密码" />
			</view>

			<view class="btns mtb30 rows">
				<view class="btn lg cancel plr40 f1" @click="$refs.pwd.close()">取消</view>
				<view class="btn lg black plr40 f1" @click="handleConfirm">验证</view>
			</view>
		</view>
	</uni-popup>
</template>

<style>
</style>