<template>
  <view class="page">
    <cu-custom :isBack="true" title="绑定手机号"></cu-custom>
    <view class="bind bg-white">
      <view class="bind-img">
        <image src="/static/imgs/phone.png" mode="widthFix" style="width:400rpx;" />
      </view>
      <view class="bind-text">请绑定手机号</view>
      <view class="bind-tip" style="margin-top:10px;"> 为向您提供更优质的交易相关基本功能，我们将会获取您的手机号。</view>
      <view class="bind-tip">
        为了更好的保障个人权益，请您仔细阅读
        <text style="color:#02a5b1" class="text" @tap="goto('user')">《用户协议》</text>和
        <text style="color:#02a5b1" class="text" @tap="goto('privacy')">《隐私政策》</text>
      </view>
      <button class="bind-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">立即绑定</button>
    </view>
  </view>
</template>

<script>
import { _bindPhone, _login, _getBindPhone } from '@/api/auth'
import { mapGetters } from 'vuex'
export default {
  data () {
    return {
      key: '绑定手机号'
    }
  },
  computed: {
    ...mapGetters([
      'token', 'session'
    ])
  },
  methods: {
    goto (type) {
      this.globalNavigateTo('agreement', { type })
    },
    getPhoneNumber (e) {
      const detail = e.detail
      if (!detail.iv) {
        return false
      }
      const _self = this
      const params = {
        iv: detail.iv,
        encryptedData: detail.encryptedData,
        token: this.token,
        code: this.globalApp.code
      }
      uni.checkSession({
        success () {
          params.session = _self.session
          _self.bindPhone(params)
        },
        fail () {
          uni.login({
            success: wxres => {
              _login({ code: wxres.code }).then(res => {
                params.session = res.data.session_key
                _self.$store.dispatch('setSession', res.data.session_key)
                _self.bindPhone(params)
              })
            }
          })
        }
      })
    },
    bindPhone (params) {
      _bindPhone(params).then(res => {
        uni.showToast({ title: res.msg, icon: 'none' })
        const token = res.data.token
        this.$store.dispatch('setToken', token).then(res => {
          this.getBindPhone()// 获取手机号
          setTimeout(() => {
            uni.navigateBack()
          }, 800)
        })
      })
    },
    getBindPhone () {
      _getBindPhone().then(res => {
        this.$store.dispatch('setPhone', res.data.mobile)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.bind {
  padding: 30px 44rpx 10px;
}
.bind-img {
  margin: 0 auto;
  text-align: center;
}
.bind-text {
  margin-top: 20px;
  color: #000;
  font-size: 18px;
  text-align: center;
}
.bind-tip {
  font-size: 14px;
}
.bind-btn {
  margin-top: 30px;
  background: #5fd0e4;
  border-radius: 4px;
  color: #fff;
  width: 100%;
  padding: 0;
  font-size: 14px;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 10vw;
}
.bind-btn:hover {
  background: #3f8b97;
}
</style>
