<template>
  <view class="container">
    <image src="../../static/icon/login.png" mode="scaleToFill" class="icon"></image>
    <view class="hr"></view>
    <view class="content">
      <text>申请获取以下权限</text>
      <!--  #ifdef  MP-WEIXIN -->
      <text>获得你的公开信息（昵称、头像、地区等）</text>
      <!--  #endif -->
      <!--  #ifdef  MP-ALIPAY -->
      <text>获得你的公开信息（昵称、头像、地区等）</text>
      <!--  #endif -->
    </view>
    <!--  #ifdef  MP-WEIXIN -->
    <button :loading="getUserInfoLoading" :disabled="getUserInfoLoading" @click="getUserInfo">
      授权获取
    </button>
    <!--  #endif -->

    <!--  #ifdef  MP-ALIPAY -->
    <!--
    <button :loading="getUserInfoLoading"  open-type="getAuthorize" scope="userInfo"
      @getAuthorize="getUserInfo" @onError="onAuthError">
      本地授权获取
    </button>
    -->
    <button  @click="getAliInfo" :loading="getUserInfoLoading" :disabled="getUserInfoLoading">
      授权获取
    </button>    
    <!--  #endif -->
    

  </view>
</template>
<script>
  import {
    mapState,
    mapMutations
  } from "vuex";

  export default {
    data() {
      return {
        code: '',
        getUserInfoLoading: false
      }
    },
    created() {
      if (store.state.userInfo.nickName !== undefined) {
        uni.redirectTo({
          url: "/pages/authen/login"
        })
        return
      }
    },
    computed: {
      // ...mapState(["appId", "stationId", "phoneNumber", "countryCode", "purePhoneNumber", "openId", "unionId",
      //   "userInfo"
      // ]),
      // ...mapState({
      //   appId: state => state.appId,
      //   phoneNumber: state => state.user.phoneNumber,
      //   // countryCode: state => state.user.countryCode,
      //   // purePhoneNumber: state => state.user.purePhoneNumber,
      //   openId: state => state.user.openId,
      //   unionId: state => state.user.unionId,
      //   userInfo: state => state.user.userInfo,
      //   stationId: state => state.station.stationId,
      // }),
    },
    async created() {
      let [err, loginData] = await uni.login();
      this.code = loginData.code
    },
    methods: {
      ...mapMutations({
        updateUserInfo: "updateUserInfo",
        clearUserInfo: "clearUserInfo"
      }),
      ...mapMutations({
        updateOpenId: "updateOpenId",
        updateUnionId: "updateUnionId",
        updateUserInfo: "updateUserInfo",
        updatePhoneNumber: "updatePhoneNumber",
        updateCountryCode: "updateCountryCode",
        updatePurePhoneNumber: "updatePurePhoneNumber",
        resetApplet: "resetApplet",
        clearUserAuthen:"clearUserAuthen"
      }),
      //#ifdef MP-ALIPAY
      getAliInfo(){
        let userInfo = undefined
        my.getAuthCode({
          // scopes: ['auth_user',"auth_base","auth_zhima"],
          scopes: ['auth_user',"auth_base"],
         // 主动授权：auth_user，静默授权：auth_base。或者其它scope。如需同时获取用户多项授权，可在 scopes 中传入多个 scope 值。
          success: async (res) => {
            console.log(res)
            if (res.authCode) {
              // 认证成功
              // 调用自己的服务端接口，让服务端进行后端的授权认证
              const profileData = await this.$Request({
                url: "/getAliUserInfo",
                method: "GET",
                data:{
                  authCode:res.authCode
                }
              })
              console.log(profileData)
              userInfo = profileData.data
              userInfo = {
                nickName:userInfo.userId, // 先骗过auth认证
                avatarUrl:userInfo.avatar
                // gender:userInfo.gender
              }
              const userId = profileData.data.userId;
              
              this.updateUserInfo(userInfo)
              this.updateUnionId(userId)
              this.updateOpenId(userId)

              const [redirectErr, redirectData] = await uni.redirectTo({
                url: "/pages/authen/login"
              })
            }
          },
          fail:(err)=>{
            this.clearUserAuthen();
            uni.showToast({
              title: e.message,
              icon:"error"
            })
          }
        });
      },
      //#endif
      //#ifdef MP-WEIXIN
      async getUserInfo(res) {
        let userInfo = undefined
        try {
          this.getUserInfoLoading = true;
          uni.showLoading({
            title: '获取中...',
            mask: true
          });
          const profileData = await wx.getUserProfile({
            lang: "zh_CN",
            desc: "更好的消费推送体验"
          })
          userInfo = profileData.userInfo
  
          userInfo = {
            nickName:userInfo.nickName,
            avatarUrl:userInfo.avatarUrl,
            gender:userInfo.gender
          }
          this.updateUserInfo(userInfo)
          this.getUserInfoLoading = false
          uni.hideLoading();
          const [redirectErr, redirectData] = await uni.redirectTo({
            url: "/pages/authen/login"
          })
        } catch (e) {
          this.getUserInfoLoading = false
          uni.hideLoading();
          uni.showToast({
            title: '请重新授权~',
            icon:"error"
          })
          this.clearUserInfo()
        }
      },
      //#endif
    },
    onLoad() { //默认加载
    }
  }
</script>
<style lang="scss">
  page {
    width: 750rpx;
    background-color: #f0f2f5;
    min-height: 100vh;

    .container {
      text-align: center;

      .icon {
        margin-top: 414rpx;
        width: 508rpx;
        height: 388rpx;
        margin-top: 180rpx;
        display: inline-block;
      }

      .hr {
        margin-top: 120rpx;
        display: inline-block;
        width: 618rpx;
        height: 2rpx;
        box-sizing: border-box;
        border: 1rpx solid rgba(0, 0, 0, 0.1);
      }

      .content {
        margin-top: 90rpx;
        display: inline-flex;
        flex-direction: column;
        justify-content: center;

        width: 616rpx;

        text:nth-child(1) {
          height: 44rpx;
          font-size: 32rpx;
          color: #000000;
          line-height: 44rpx;
          text-align: left;
        }

        text:nth-child(2) {
          height: 44rpx;
          font-size: 28rpx;
          text-align: left;
          color: rgba(0, 0, 0, 0.25);
          line-height: 44rpx;
        }
      }

      button {
        margin-top: 90rpx;
        display: inline-block;
        width: 616rpx;
        height: 76rpx;
        background: linear-gradient(123deg, #12A273 0%, #12A273 100%);
        border-radius: 38rpx;
        font-size: 32rpx;
        color: #FFFFFF;
        line-height: 76rpx;
      }
    }
  }
</style>
