<route lang="json5" type="page">
{
  style: {
    navigationStyle: 'custom',
  },
}
</route>

<template>
  <view class="h-screen flex flex-col">
    <Navbar
      safeAreaInsetTop
      :bordered="false"
      :fixed="true"
      :placeholder="true"
      left-arrow
      bgColor="transparent"
      @click-left="handleClickLeft"
    >
      <template #title>
        <text class="text-[#1F2329] text-[36rpx] font-medium">授权登录</text>
      </template>
    </Navbar>
    <view class="flex flex-col justify-center items-center flex-1 pb-safe mt-[-100px]">
      <image
        class="w-[424rpx] h-[424rpx]"
        src="https://api.static.ycymedu.com/images/logo.png"
        mode="aspectFit"
      ></image>
      <button
        class="w-[493rpx]! mb-[40rpx] h-[88rpx]! rounded-[44rpx] text-[32rpx] text-white flex items-center justify-center"
        :class="checked.length > 0 ? 'bg-[#1580FF]' : 'bg-[#BFBFBF]'"
        @click.stop="handleClick"
        open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber"
        :disabled="checked.length === 0"
      >
        一键登录
      </button>

      <view class="flex items-center flex-nowrap">
        <CheckboxGroup v-model="checked" class="check-class mr-[10rpx]">
          <Checkbox name="1" cell shape="button" class="custom-checkbox"></Checkbox>
        </CheckboxGroup>

        <view class="flex items-center">
          <text class="text-[24rpx] whitespace-nowrap">
            已阅读并同意
            <text class="text-[#1580FF]" @click.stop="handleClickUserAgreement">
              <text>《用户协议》</text>
            </text>
            和
            <text class="text-[#1580FF]" @click.stop="handleClickPrivacyPolicy">
              <text>《隐私条款》</text>
            </text>
          </text>
        </view>
      </view>
    </view>
    <LoginMask v-model:show="show" @auth-ready="handleAuthReady" />
  </view>
</template>

<script setup lang="ts">
import LoginMask from './components/LoginMask.vue'
import Navbar from './components/navbar/Navbar.vue'
import { useUserStore } from '@/store/user'
import {
  getSessionKey,
  getVolunteerInitialization,
  getWxUserInfo,
  setWxInfo,
} from '@/service/index/api'
import { City } from '@/types/app-type'
import Checkbox from './components/check-group/Checkbox.vue'
import CheckboxGroup from './components/check-group/CheckboxGroup.vue'
import { useLogin } from '@/login-sub/hooks/useUserInfo'

const show = ref(false)

const checked = ref<any[]>([]) // 是否同意条款
const getPhoneInfo = ref<any>(null)

const scene = ref('')

const getPhoneNumber = async (e: any) => {
  if (e.detail.errMsg == 'getPhoneNumber:ok') {
    const detail = e.detail
    let _getPhoneInfo = {
      iv: detail.iv,
      encryptedData: detail.encryptedData,
      code: detail.code,
    }
    getPhoneInfo.value = _getPhoneInfo
    await getUserInfo(detail.code)
  } else if (e.detail.errMsg == 'getPhoneNumber:fail not login') {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    })
  } else {
    uni.showToast({
      title: '获取手机号失败',
      icon: 'none',
    })
  }
}

const handleClick = () => {
  if (!checked.value) {
    uni.showToast({
      title: '您需先同意《服务条款》和《隐私条款》',
      icon: 'none',
    })
    return
  }
}

// 授权完成之后返回到上一个目录去
const handleAuthReady = () => {
  uni.navigateBack()
}

const handleClickLeft = () => {
  uni.navigateBack()
}

const handleClickUserAgreement = () => {
  uni.navigateTo({
    url: '/login-sub/userAgreement',
  })
}

const handleClickPrivacyPolicy = () => {
  uni.navigateTo({
    url: '/login-sub/privacyPolicy',
  })
}

const userStore = useUserStore()

const getUserInfo = async (_code: string) => {
  let userInfo = (await useLogin()) as { code: string; errMsg: string }

  if (userInfo.errMsg == 'login:ok') {
    const resp = await getSessionKey({ JsCode: userInfo.code })
    if (resp.code == 200) {
      const result = resp.result as { accessToken: string; openId: string }
      userStore.setUserToken(result.accessToken)
      userStore.setUserOpenId(result.openId)

      setWxInfo({ code: _code, openId: result.openId })

      // 根据微信的信息获取用户信息
      getWxUserInfo().then((resp) => {
        const infoData = resp.result as unknown as {
          userExtend: { provinceCode: string; init: boolean }
          zyBatches: any[]
          batchDataUrl: string
          batchName: string
          avatar: string
          nickName: string
          mobile: string
          sex: number
        }
        userStore.setEstimatedAchievement(infoData.userExtend)
        userStore.setZyBatches(infoData.zyBatches)
        userStore.setBatchDataUrl(infoData.batchDataUrl)
        userStore.setBatchName(infoData.batchName)
        userStore.setUserAvatar(infoData.avatar)
        userStore.setUserNickName(infoData.nickName)
        userStore.setUserBaseInfo({ mobile: infoData.mobile, sex: infoData.sex })

        if (resp.code === 200) {
          // 根据用户信息中的城市设置对应城市的分数等信息
          getVolunteerInitialization()
            .then((res) => {
              let list = res.result as any[]
              let code = infoData.userExtend ? infoData.userExtend.provinceCode : ''
              let addressItem: City
              if (code !== '') {
                for (let i = 0; i < list.length; i++) {
                  if (list[i].code == code) {
                    addressItem = list[i]
                  }
                }
              }
              userStore.setUserCity(addressItem)
            })
            .then(() => {
              // 个人信息初始化
              if (infoData.userExtend && !infoData.userExtend.init) {
                uni.navigateTo({ url: '/login-sub/inviteCode' })
              } else if (scene.value !== '') {
                uni.navigateTo({ url: `/pages/index/index?scene=${scene.value}` })
              } else {
                uni.switchTab({
                  url: '/pages/home/index/index',
                })
              }
            })
        }
      })
    }
  } else {
    uni.showToast({
      title: '您需先授权',
      icon: 'none',
    })
  }
}

onLoad((options) => {
  // 如果是授权登录页面回来，则要回去授权页面
  scene.value = options.scene || ''
})
</script>

<style lang="scss" scoped>
:deep(.custom-checkbox) {
  display: flex;
  align-items: center;
  justify-content: center;
  .checkbox__icon {
    border-radius: 50%;
    height: 32rpx;
    width: 32rpx;
    margin: 0;
  }

  .custom-box {
    width: 32rpx;
    height: 32rpx;
    border: 1px solid #ddd;
    border-radius: 50%;
  }
}

:deep(.checkbox-active) {
  border-color: #fff !important;
  background-color: #fff !important;
}
</style>
