<template>
  <view class="container">
    <view class="store-info">
      <view class="header">
        <!-- <open-data class="avatar" type="userAvatarUrl"></open-data> -->
        <image class="image" :src="storeInfo && storeInfo.image_url ? storeInfo.image_url : '/static/default-avatar.png'"></image>
      </view>
    </view>
    <view class="auth-title">申请获取以下权限</view>
    <view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
    <view class="login-btn">
      <!-- 获取支付宝用户信息 -->
      <button class="button btn-normal" :style="{ background: '#1776FE' }" open-type="getAuthorize" scope="userInfo"
        @getAuthorize="getUserProfile" @error="handleAuthError">授权登录</button>
    </view>
    <view class="no-login-btn">
      <button class="button btn-normal" @click="handleCancel()">暂不登录</button>
    </view>

  </view>
</template>

<script>
  import store from '@/store'
  import { isEmpty } from '@/utils/util'
  import SettingModel from '@/common/model/Setting'

  export default {

    data() {
      return {
        // 商城基本信息
        storeInfo: undefined,
        // 支付宝小程序登录凭证 (code)
        // 提交到后端，用于换取openid
        code: ''
      }
    },

    created() {
      // 获取商城基本信息
      this.getStoreInfo()
    },

    methods: {

      // 获取商城基本信息
      getStoreInfo() {
        SettingModel.item('store').then(store => this.storeInfo = store)
      },

      // 获取authCode
      // https://opendocs.alipay.com/mini/api/openapi-authorize
      getCode() {
        return new Promise((resolve, reject) => {
          my.canIUse('getAuthCode') && my.getAuthCode({
            scopes: 'auth_base', // auth_base auth_user
            success({ authCode }) {
              console.log('getAuthCode success', authCode)
              resolve(authCode)
            },
            fail: reject
          })
        })
      },

      // 获取支付宝用户信息
      getUserProfile() {
        const app = this
        my.canIUse('getOpenUserInfo') && my.getOpenUserInfo({
          success(res) {
            const response = JSON.parse(res.response).response
            console.log('用户同意了授权', response)
            // 授权成功事件
            if (response.code == 10000) {
              app.onAuthSuccess({ nickName: response.nickName, avatarUrl: response.avatar })
              return
            }
            // 授权失败
            const errorMsg = response.code == 40006 ? 'my.getOpenUserInfo接口权限不足，请在支付宝小程序控制台绑定产品 “获取会员基础信息”' : response.subMsg
            app.$error(response.code + ' ' + errorMsg)
          },
          fail(err) {
            console.error('getOpenUserInfo fail', err)
          }
        })
      },

      // 用户取消授权
      handleAuthError({ detail }) {
        console.log('handleAuthError', detail)
      },

      // 授权成功事件
      // 这里分为两个逻辑:
      // 1.将authCode和userInfo提交到后端，如果存在该用户 则实现自动登录，无需再填写手机号
      // 2.如果不存在该用户, 则显示注册页面, 需填写手机号
      // 3.如果后端报错了, 则显示错误信息
      async onAuthSuccess(userInfo) {
        const app = this
        // 提交到后端
        store.dispatch('LoginMpAlipay', {
            partyData: {
              code: await app.getCode(),
              oauth: 'MP-ALIPAY',
              userInfo
            },
            refereeId: store.getters.refereeId
          })
          .then(result => {
            // 一键登录成功
            app.$toast(result.message)
            // 相应全局事件订阅: 刷新上级页面数据
            uni.$emit('syncRefresh', true)
            // 跳转回原页面
            setTimeout(() => app.onNavigateBack(), 2000)
          })
          .catch(err => {
            const resultData = err.result.data
            // 显示错误信息
            if (isEmpty(resultData)) {
              app.$toast(err.result.message)
            }
            // 跳转回原页面
            if (resultData.isBack) {
              setTimeout(() => app.onNavigateBack(1), 2000)
            }
            // 判断还需绑定手机号
            if (resultData.isBindMobile) {
              app.onEmitSuccess(userInfo)
            }
          })
      },

      // 将oauth提交给父级
      // 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
      async onEmitSuccess(userInfo) {
        const app = this
        app.$emit('success', {
          oauth: 'MP-ALIPAY', // 第三方登录类型: MP-ALIPAY
          code: await app.getCode(), // 支付宝登录的authCode, 用于换取openid
          userInfo // 支付宝用户信息
        })
      },

      /**
       * 暂不登录
       */
      handleCancel() {
        // 跳转回原页面
        this.onNavigateBack()
      },

      /**
       * 登录成功-跳转回原页面
       */
      onNavigateBack(delta = 1) {
        const pages = getCurrentPages()
        if (pages.length > 1) {
          uni.navigateBack({
            delta: Number(delta || 1)
          })
        } else {
          this.$navTo('pages/index/index')
        }
      }

    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 0 60rpx;
    font-size: 32rpx;
    background: #fff;
    min-height: 100vh;
  }

  .store-info {
    padding: 80rpx 0 48rpx;
    border-bottom: 1rpx solid #e3e3e3;
    margin-bottom: 72rpx;
    text-align: center;

    .header {
      width: 190rpx;
      height: 190rpx;
      border: 4rpx solid #fff;
      margin: 0 auto 0;
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 2rpx 0 10rpx rgba(50, 50, 50, 0.3);

      .image {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
  }

  .auth-title {
    color: #585858;
    font-size: 34rpx;
    margin-bottom: 40rpx;
  }

  .auth-subtitle {
    color: #888;
    margin-bottom: 88rpx;
    font-size: 28rpx;
  }

  .login-btn {
    padding: 0 20rpx;

    .button {
      height: 88rpx;
      background: #04be01;
      color: #fff;
      font-size: 30rpx;
      border-radius: 999rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }


  .no-login-btn {
    margin-top: 20rpx;
    padding: 0 20rpx;

    .button {
      height: 88rpx;
      background: #dfdfdf;
      color: #fff;
      font-size: 30rpx;
      border-radius: 999rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
</style>