<template>
	<view class="page">
		<cu-custom :isBack="false" :isHome="true">
		</cu-custom>
		<view class="main">
			<image src="/static/imgs/login.png" class="logo"></image>
			<view class="title">课后百科</view>
			<view class="action margin-top-xl">
						<view class="des margin-top">您尚未登录需要获取您的授权后进入</view>
			      <button class="cu-btn block round bg-grey lg margin-top" @tap="back">暂不登录</button>
			      <button class="cu-btn block round bg-cyan lg margin-top" @tap="login">立即登录</button>
			</view>
			<view class="agreement margin-top-lg">
				<checkbox-group @change="agreement=!agreement" style="display:inline-block;">
					<label>
							<checkbox class="cyan check-agreement"></checkbox>
							<text class="text">阅读并同意以下条款</text>
					</label>
        </checkbox-group>
				<text class="text-cyan"  @tap="goto('user')">《用户协议》</text>
				<text class="text-cyan" @tap="goto('privacy')">《隐私政策》</text>
			</view>
		</view>
	</view>
</template>

<script>
import { _login, _auth, _getBindPhone } from '@/api/auth'
import socket from '@/common/webSocket'
export default {
  data() {
    return {
      agreement: false,
      wxCode: ''
    }
  },
  onLoad(options) {
    uni.login({
      success: wxres => {
        this.wxCode = wxres.code
      }
    })
  },
  methods: {
    back() {
      uni.navigateBack({
        delta: 0
      })
    },
    goto(type) {
      this.globalNavigateTo('agreement', { type })
    },
    login() {
      if (!this.agreement) {
        uni.showToast({ title: '请先阅读并勾选协议', icon: 'none' })
        return
      }
      uni.getUserProfile({
        desc: '用于完善会员资料',
        success: res => {
          this.$store.dispatch('setUser', res.userInfo)
          this.flashToken(res)
        }
      })
    },
    flashToken(wxConfig) {
      _login({ code: this.wxCode }).then(res => {
        const { openid, session_key: session } = res.data
        this.$store.dispatch('setSession', session)
        const params = {
          session: session,
          iv: wxConfig.iv,
          encryptedData: wxConfig.encryptedData,
          openid: openid,
          code: this.globalApp.code
        }
        _auth(params).then(rs => {
          this.$store.dispatch('setToken', rs.data.token).then(res => {
            socket.initSocket()
            this.getBindPhone()
            this.globalReLaunch('index')
          })
        })
      })
    },
    getBindPhone() {
      _getBindPhone().then(res => {
        this.$store.dispatch('setPhone', res.data.mobile)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '~@/common/css/mixin.scss';
.page{
	background-color:#fff;
}
.main{
	padding-top:50px;
	text-align:center;
}
.title {
	margin:12px auto;
  @include title(32px, 20px);
	width:80px;
	border-bottom:4px solid #00d2e330;
}
.logo{
	width:100px;
	height:100px;
}
.action{
	margin:0 auto;
	width:80%;
}
.check-agreement{
	transform: scale(0.7);
}
</style>
