<template>
  <view class="container">
    <image src="../../static/icon/login.png" mode="scaleToFill" class="icon"></image>
    <view class="content">
      <button 
        open-type='getPhoneNumber' 
        @getphonenumber="getPhoneNumber"
        :loading="getPhoneNumberLoading"
        :disabled="getPhoneNumberLoading"
      >
        授权登录
      </button>
      <button type="default">手机登录</button>
      <text>登录即代表同意《隐私政策》和《用户服务协议》</text>
    </view>
  </view>
</template>
<script>
  import {
    mapState,
    mapMutations
  } from "vuex";

  export default {
    data() {
      return {
        code: '',
        getPhoneNumberLoading:false
      }
    },
    computed: {
      ...mapState(["appId", "stationId", "phoneNumber", "countryCode", "purePhoneNumber", "openId", "unionId",
        "userInfo"
      ])
    },
    async created() {
      if(this.phoneNumber !== '' && this.openId !== '' && this.unionId !== '' ){
          uni.redirectTo({
            url:"/pages/index/index"
          })
          return 
      }
      
      let [err, loginData] = await uni.login();
      this.code = loginData.code
 
    },
    methods: {
      ...mapMutations({
        updateOpenId: "updateOpenId",
        updateUnionId: "updateUnionId",
        updateUserInfo: "updateUserInfo",
        updatePhoneNumber: "updatePhoneNumber",
        updateCountryCode: "updateCountryCode",
        updatePurePhoneNumber: "updatePurePhoneNumber"
      }),
      //#ifdef MP-WEIXIN
      async getPhoneNumber(info) {
        this.getPhoneNumberLoading  = true;
        uni.showLoading({
          title: '获取中...',
          mask: true
        });
        
        if (info.detail.errMsg === "getPhoneNumber:ok") {
          try {
            console.log(this.code)
            let loginDataArr = await uni.login();
            this.code = loginDataArr[1].code
            const iv = info.detail.iv
            const encryptedData = info.detail.encryptedData
            const keyData = await this.$Request({
              url: "/getSessionKeyAndOpenID",
              method: "GET",
              data: {
                code: this.code,
                stationId: this.stationId
              }
            })
            console.log("keyData", keyData)
            const openId = keyData.openId
            this.updateOpenId(openId)
            const unionId = keyData.unionId
            this.updateUnionId(unionId)
            const sessionKey = keyData.sessionKey
            const decryptData = await this.$Request({
              url: "/decryptEncryptedData",
              method: "POST",
              data: {
                sessionKey,
                encryptedData,
                iv
              }
            })
            console.log("decryptData", decryptData)
            const phoneNumber = decryptData.phoneNumber // 全手机号
            const countryCode = decryptData.countryCode // 区号
            const purePhoneNumber = decryptData.purePhoneNumber // 不带区号的手机号
            this.updatePhoneNumber(phoneNumber)
            this.updateCountryCode(countryCode)
            this.updatePhoneNumber(purePhoneNumber)
            const AppUserInfoData = await this.$Request({
              url: "/addAppUserInfo",
              method: "POST",
              data: {
                "userType": "2",
                "openId": this.openId,
                "blogNickName": this.userInfo.nickName,
                "sexFlag": this.userInfo.gender === 1 ? 'M' : 'F',
                "blogProfilePhoto": this.userInfo.avatarUrl,
                "mobilePhone": this.phoneNumber,
                "stationId": this.stationId, //油站Id
                "stationName": this.stationName, //油站名称
                "unionId": this.unionId
              }
            })
            if (AppUserInfoData.retCode !== 0) {
              throw new Error("存入用户失败")
            }
            this.getPhoneNumberLoading = false
            uni.hideLoading();
            uni.navigateBack({
              delta:1
            })
            // console.log(redirectData)
          } catch (e) {
            this.getPhoneNumberLoading = false
            uni.hideLoading();
            uni.showToast({
              title: '授权失败，请再次尝试一下'
            })
          }
        } else {
          this.getPhoneNumberLoading = false
          uni.hideLoading();
          uni.showToast({
            title: '授权拒绝，请登录后操作'
          })
        }
      },
      //#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;
      }

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

        button:nth-child(1) {
          width: 616rpx;
          height: 76rpx;
          background: linear-gradient(123deg, #12A273 0%, #12A273 100%);
          border-radius: 38rpx;
          font-size: 32rpx;
          color: #FFFFFF;
          line-height: 76rpx;
        }

        button:nth-child(2) {
          width: 616rpx;
          height: 76rpx;
          background-color: #f0f2f5;
          border-radius: 38rpx;
          font-size: 32rpx;
          font-weight: 400;
          color: rgba(0, 0, 0, 0.25);
          line-height: 76rpx;
        }

        text {
          margin-top: 42rpx;
          height: 36rpx;
          font-size: 26rpx;
          color: rgba(0, 0, 0, 0.5);
          line-height: 36rpx;
        }
      }
    }
  }
</style>
