<template>
  <Overlay :show="show" @update:show="handleClose">
    <view
      class="fixed top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 flex flex-col items-center bg-white p-[40rpx] rounded-[32rpx]"
      @click.stop
    >
      <image
        class="w-[200rpx] h-[200rpx]"
        src="https://api.static.ycymedu.com/images/logo.png"
        mode="aspectFit"
      ></image>
      <view class="flex flex-col items-center">
        <text class="text-[26rpx] mt-[20rpx] mb-[40rpx]" :selectable="false">
          {{ phone ? '申请使用您的手机号' : '申请获取您的个人信息' }}
        </text>
        <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>
    </view>
  </Overlay>
</template>

<script lang="ts" setup>
import { useLogin } from '@/login-sub/hooks/useUserInfo'
import Overlay from './Overlay.vue'
import RadioGroup from './radio-group/RadioGroup.vue'
import Radio from './radio-group/Radio.vue'
import Checkbox from './check-group/Checkbox.vue'
import CheckboxGroup from './check-group/CheckboxGroup.vue'

import {
  getSessionKey,
  getVolunteerInitialization,
  getWxUserInfo,
  setWxInfo,
} from '@/service/index/api'
import { useUserStore } from '@/store/user'
import { City } from '@/types/app-type'

defineProps({
  show: {
    type: Boolean,
    default: false,
  },
})
defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})

const emits = defineEmits(['update:show', 'authReady'])

const userStore = useUserStore()

const handleClose = () => {
  emits('update:show', false)
}

const phone = ref(true) // 手机号登陆
const checked = ref([]) // 是否同意条款
const getPhoneInfo = ref(null)

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

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

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 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: userInfo.code, openId: result.openId })

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

        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)
            handleClose()
            emits('authReady')
          })
        }
      })
    }
  } else {
    uni.showToast({
      title: '您需先授权',
      icon: 'none',
    })
  }
}
</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>
