<template>
  <view class="GetUserIcon" v-show="Show">
    <view class="centerLabel">
      <image mode="widthFix" src="https://cjgw.oss-cn-hangzhou.aliyuncs.com/ygcxxfb/image/morentouxiang.png"></image>
      <text>授权头像</text>
      <button open-type="getUserInfo" @tap="ToGetUserIcon">授权头像</button>
    </view>
  </view>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const { mapState: mapUserState, mapMutations: mapUserMutations } = createNamespacedHelpers('user')
export default {
  name: 'GetUserIcon',
  data () {
    return {
      Show: false
    }
  },
  computed: {
    ...mapUserState({
      UserInfo: x => x.UserInfo // 用户信息
    })
  },
  created () {
    this.Init() // 初始化
  },
  methods: {
    ...mapUserMutations([
      'EditUserInfo'
    ]),
    Init () { // 初始化
      let _that = this
      wx.getSetting({ // 校验用户是否已授权
        success (res) {
          if (res.authSetting['scope.userInfo']) { // 已授权时，获取用户信息
            wx.authorize({
              scope: 'scope.userInfo',
              success () {
                wx.getUserInfo({ // 授权成功时，获取用户信息
                  success (subRes) {
                    _that.EditUserInfo({ name: 'Icon', value: subRes.userInfo.avatarUrl })
                    _that.EditUserInfo({ name: 'Name', value: subRes.userInfo.nickName })
                  }
                })
              }
            })
          } else { // 未授权时，显示弹窗
            _that.Show = true
          }
        }
      })
    },
    ToGetUserIcon () { // 获取用户头像
      let _that = this
      wx.authorize({
        scope: 'scope.userInfo',
        success () {
          wx.getUserInfo({ // 授权成功时，获取用户信息
            success (res) {
              _that.EditUserInfo({ name: 'Icon', value: res.userInfo.avatarUrl })
              _that.EditUserInfo({ name: 'Name', value: res.userInfo.nickName })
              _that.Show = false
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss">
.GetUserIcon {
  width: 100%;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  z-index: 100;
  background: rgba(0, 0, 0, 0.6);
  > view {
    width: 60%;
    padding: 20px 0 0;
    background: #fff;
    border-radius: 10px;
    overflow: hidden;
    > image {
      width: 120px;
      margin: 0 auto;
      display: block;
    }
    > text {
      font-size: 32px;
      color: #07c160;
      line-height: 80px;
      display: block;
      text-align: center;
      border-top: 2px solid #f5f5f5;
      margin-top: 40px;
      &:active {
        background: #f5f5f5;
      }
    }
    > button {
      width: 100%;
      height: 80px;
      opacity: 0;
      display: block;
      position: absolute;
      left: 0;
      bottom: 0;
    }
  }
}
</style>
