<template>
  <view class="ss-p-30 head-box">
    <template v-if="changeType === 'login'">
      <view class="head-title ss-m-b-30 MiSans-Semibold">欢迎来到辞图科技，请先登录</view>

      <view class="ss-m-t-100">
        <view>
          <button
            v-if="!protocol"
            class="send-button MiSans-Medium"
            @click="showProtocolToast"
            >
            微信授权注册/登录
          </button>
          <button 
          v-else
            class="send-button MiSans-Medium"
            :loading="phoneNumberLoading"
            :disabled="phoneNumberLoading"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
            >
            微信授权注册/登录
          </button>
        </view>

        <view class="ss-flex ss-row-center ss-m-y-50">
          <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>
    </template>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { weChatRegister } from '@/api/common'
import { closeAuthModal } from '@/hooks/useModal'

const phoneNumberLoading = ref(false)
const protocol = ref(true)

const changeType = ref('login')

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

const showProtocolToast = () => {
  uni.showToast({ title: '请先阅读并同意用户协议和隐私政策', icon: 'none' })
}

// 微信登录/注册
const getPhoneNumber = async (e) => {
  if (e?.detail?.errMsg !== 'getPhoneNumber:ok') {
    uni.showToast({ title: '微信登录失败', icon: 'none' })
    return
  }
  changeType.value = 'login'
  phoneNumberLoading.value = true

  wx.login({
    success: async (res) => {
      try {
        const { result } = await weChatRegister({ wechat_code: res?.code })
        console.log(result, '用户注册返回结果')
        uni.setStorageSync('wechat_user', result)
        uni.$emit && uni.$emit('auth:login', result)
        closeAuthModal()
      } finally {
        phoneNumberLoading.value = false
      }
    },
    fail:(res)=> { 
      phoneNumberLoading.value = false
      console.log("获取登录凭证code失败！", res)
    }
  })
}
</script>

<style scoped lang="scss">
.head-title {
  font-size: 40rpx;
  text-align: center;
  color: #00B760;
  margin-top: 30rpx;
}
</style>