<template>
  <view class="content">
    <view>
      <image src="https://eshangtech.com/ShopICO/yxcl-register-pht.png" mode="aspectFit"></image>
      <view v-if="!store.$state.WeChat_UserId" class="desc">
        <button type="primary" class="btn" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">微信授权</button>
      </view>
      <view v-else class="desc">
        <button type="primary" class="btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          快速登录账号
        </button>
      </view>
    </view>
    <view class="login-tip-text"> 该小程序仅供企业内部人员登录使用，<br />您的手机号是核实身份的唯一凭证。 </view>
  </view>
</template>

<script lang="ts" setup>
import { useUserInfo } from '@/stores/userInfo'
import { getEmpower, getPhoneEmpower } from '@/api/login/login'

const store = useUserInfo()

function bindGetUserInfo(e) {
  console.log(e)
  uni.getUserInfo({
    provider: 'weixin',
    success: function (res) {
      console.log('res', res)
      let data = {
        WeChat_AppId: store.weChatMessage.WeChat_AppId as string,
        WeChat_MiniProToken: store.token,
        encryptedData: encodeURIComponent(res.encryptedData),
        iv: encodeURIComponent(res.iv),
      }
      console.log('data', data)
      getEmpower(data).then((res) => {
        console.log('res', res)
        if (res.Result_Code === 101) {
          uni.showToast({
            title: res.Result_Desc,
            icon: 'none',
          })
        } else if (res.Result_Code === 100) {
          uni.setStorageSync('user', res.Result_Data)
          store.$state.WeChat_UserId = res.Result_Data.WeChat_UserId
        }
      })
    },
  })
}

function getPhoneNumber(e) {
  console.log(e)
  console.log(uni.getStorageSync('token'))
  let data = {
    WeChat_AppId: store.weChatMessage.WeChat_AppId as string,
    WeChat_MiniProToken: store.token,
    encryptedData: encodeURIComponent(e.detail.encryptedData),
    iv: encodeURIComponent(e.detail.iv),
  }
  console.log('data', data)
  getPhoneEmpower(data).then((res) => {
    console.log('res', res)
    if (res.Result_Code === 100) {
      uni.setStorageSync('userPhone', res.Result_Data)
      uni.redirectTo({ url: '/pages/index/index' })
    } else {
      uni.showToast({
        title: res.Result_Desc,
        icon: 'none',
      })
    }
  })
}
</script>

<style scoped lang="scss">
.content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 100vh;
  box-sizing: border-box;
  background-color: #fff;
  padding-top: 60rpx;
  image {
    width: 624rpx;
    height: 579rpx;
  }
  .desc {
    margin: 0 auto;
    .btn {
      width: 100%;
      margin-top: 84rpx;
      font-size: 28rpx;
      padding: 10px 0px;
    }
  }
  .login-tip-text {
    position: sticky;
    bottom: 120rpx;
    left: 0;
    width: 580rpx;
    z-index: 99;
    text-align: center;
    font-size: 26rpx;
    color: #888;
  }
}
</style>
