<template>
	<layout-page>
		<view class="defaultBgc" style="height: 100vh;">
			<view class="logo">
				<image src="https://minio.menduner.com/dev/19cce88e87fb8e895fbbe4418a937d610b2c20b8f87c6705569a096aca0a91b0.png"></image>
			</view>

			<button v-if="useUserStore.isLogin" class="recomm-button MiSans-Medium" @click="handleTokenLogin">一键登录（有token）</button>
			<button v-else class="recomm-button MiSans-Medium" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">一键登录（无token）</button>
			
			<view class="agreement-box ss-flex ss-row-center">
				<uni-icons size="20" :type="protocol ? 'checkbox-filled' : 'circle'" :color="protocol ? '#00B760' : '#ccc'" @tap="protocol = !protocol"></uni-icons>
				<view class="color-999 ss-flex ss-col-center ss-m-l-8 font-size-13">
					<span class="MiSans-Normal">我已阅读并遵守</span>
					<view class="color-primary MiSans-Medium" @tap.stop="handleToDetail('user')">
						《用户协议》
					</view>
					<view class="agreement-text MiSans-Normal">和</view>
					<view class="color-primary MiSans-Medium" @tap.stop="handleToDetail('privacy')">
						《隐私协议》
					</view>
				</view>
			</view>
		</view>
	</layout-page>
</template>

<script setup>
import { ref } from 'vue'
import layoutPage from '@/layout'
import { userStore } from '@/store/user'
import { onLoad } from '@dcloudio/uni-app'
import { weixinLoginAuthorize } from '@/api/qrcodeLogin.js'
import { checkPersonBaseInfo } from '@/utils/check'
import { showAuthModal, closeAuthModal } from '@/hooks/useModal'

const useUserStore = userStore()
const protocol = ref(true)

onLoad((options) => {
	if (!useUserStore.isLogin) {
		console.log('没登录时不需要弹窗');
		closeAuthModal()
	}
	console.log(options?.scene, '===========options')
	if (options?.scene) {
		uni.setStorageSync('wxLoginCode', options.scene)
	}
})

// 查看协议详情
const handleToDetail = (type) => {
  const url = type === 'user' ? '/pagesB/agreement/user' : '/pagesB/agreement/privacy'
  uni.navigateTo({
    url
  })
}

const handleRemove = () => {
  uni.removeStorageSync('wxLoginCode')
  setTimeout(() => {
		uni.switchTab({
			url: '/pages/index/my'
		})
	}, 2000)
}

// 已登录的授权给网页
const handleTokenLogin = async () => {
	if (!protocol.value) return uni.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none', duration: 2000 })
	const data = useUserStore.baseInfo
	if (!data || !Object.keys(data).length || data.type === undefined || data.type === null) {
		console.log('需要完善基本信息')
    showAuthModal('selectUserType')
    return
  }
  const necessaryInfoReady = checkPersonBaseInfo(data)
	console.log(necessaryInfoReady, '基本信息是否填写完善', data)
  if (necessaryInfoReady) {
	  console.log('信息填写完善-授权网页登录')
		closeAuthModal()

		if (!uni.getStorageSync('wxLoginCode')) {
			return uni.showToast({ title: '请重新扫码进行授权', icon: 'none', duration: 2000 })
		}
		try {
			await weixinLoginAuthorize({ uuid: uni.getStorageSync('wxLoginCode') })
			uni.showToast({ title: '授权网页登录成功', duration: 2000, icon: 'none' })
			handleRemove()
		} catch (error) {
			console.log(error, '授权接口error')
			handleRemove()
		}
	}
  else showAuthModal('necessaryInfo')
  uni.setStorageSync('necessaryInfoReady', necessaryInfoReady ? 'ready' : 'fddeaddc47868b')
}

// 微信登录
const getPhoneNumber = async (e) => {
	if (!protocol.value) return uni.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none', duration: 2000 })
  if (e?.detail?.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({ title: '微信登录失败', icon: 'none' })
    return
  }
  wx.login({
    success: async (result) => {
      const query = {
        loginCode: result?.code || '',
        phoneCode: e.detail.code,
        state: e.detail.encryptedData,
				autoRegister: true
      }
      await useUserStore.handleSmsLogin(query, 0)

			handleTokenLogin()
    },
    fail:(res)=> { console.log("获取登录凭证code失败！", res) }
  })
}
</script>

<style scoped lang="scss">
	.logo {
		display: flex;
		align-items: center;
		image {
			width: 85px;
			height: 85px;
			border-radius: 6px;
			margin: 20vh auto 8vh auto;
		}
	}
</style>