<template>
  <div class="qr-wrapper">
    <QrcodeVue v-if="qrcodeNo" :value="qrcodeNo" :size="200" class="qrcode" />
    <div v-if="qrTips" class="qr-tips">
      {{ qrTips }}
      <div class="tips-img">
        <img v-if="qrTips.includes('刷新')" src="@/assets/login/Refresh.svg" alt="" @click="qrRefresh">
        <img v-if="qrTips.includes('成功')" src="@/assets/login/success.svg" alt="">
      </div>
    </div>
    <div v-if="qrTips" class="qr-mantle" />
  </div>
  <div class="qr-footer">请使用商户通APP扫码登录</div>
</template>

<script setup>
import { getCurrentInstance, h, onBeforeUnmount, onMounted, ref } from 'vue'
// 导入全局函数
const { $infoBox } = getCurrentInstance().appContext.config.globalProperties
import { useUserStore } from '@/store/modules/user'
import router from '@/router'
import QrcodeVue from 'qrcode.vue'
import { timeFix } from '@/utils/util'
import { QrCodeLogin } from '@/api/login'

onMounted(() => {
	QrCode()
	createInterval()
})
let qrTips = ref('')
let qrcodeNo = ref('')
const qrStatus = {
	scaned: () => {
		qrTips.value = '扫码成功请确认登录'
	},
	expried: () => {
		qrTips.value = '二维码过期请刷新'
		clear()
	},
	canceled: () => {
		qrTips.value = '用户取消登录请刷新'
		clear()
	},
	confirmed: (res) => {
		login(res)
	}
}
const userStore = useUserStore()
let interval = null
const createInterval = () => {
	interval = setInterval(() => {
		QrCode()
	}, 2000)
}

const QrCode = () => {
	QrCodeLogin({ qrcodeNo: qrcodeNo.value }).then((res) => {
		const { qrcodeStatus, iToken } = res
		if (res.qrcodeNo) qrcodeNo.value = res.qrcodeNo

		if (qrcodeStatus && qrcodeStatus !== 'waiting') {
			qrStatus[qrcodeStatus](res)
		}
	})
}
//刷洗二维码
const qrRefresh = () => {
	qrTips.value = ''
	qrcodeNo.value = ''
	QrCode()
	createInterval()
}
//扫码成功登录函数
const login = (val) => {
	userStore.putToken(val['iToken'])
	router.push({ path: '/' })
	setTimeout(() => {
		let lastLoginTimeStr = val['lastLoginTime'] ? '上次登录时间：' + val['lastLoginTime'] : ''
		$infoBox.notification.success({
			message: '欢迎',
			description: [h('p', `${timeFix()}，欢迎回来`), h('p', lastLoginTimeStr)]
		})
	}, 1000)
}
const clear = () => {
	clearInterval(interval)
}
onBeforeUnmount(() => {
	clear()
})
</script>

<style lang="less" scoped>
.qr-wrapper {
	width: 200px;
	height: 200px;
	position: relative;
	border-radius: 5px;
	overflow: hidden;

	.qr-tips {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		z-index: 9999999999;
		font-size: 16px;
		white-space: nowrap;
		letter-spacing: 2px;
		padding: 10px 15px;
		border-radius: 5px;
		color: #fff;

		.tips-img {
			width: 30px;
			height: 30px;
			margin: 15px auto;

			img {
				width: 100%;
				height: 100%;
			}
		}
	}

	.qr-mantle {
		position: absolute;
		top: 0;
		left: 0;
		z-index: 999999;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.7);
	}
}

.qr-footer {
	margin: 15px 0;
	font-size: 16px;
	color: var(--ant-primary-color);
	text-align: center;
}
</style>
