<template>
	<view class="">
		<!-- <w-navbar></w-navbar> -->
		<view class="backView">
			<view class="login-block" v-if="needAuth">
				<u-image :fade="false" class="u-flex u-row-center logo" :src="logo" width="200" height="200">
					<u-loading slot="loading"></u-loading>
					<view slot="error" style="font-size: 24rpx;">加载失败</view>
				</u-image>
				<u-image :fade="false" class="u-flex u-row-center logo2" :src="logo2" width="214" height="60">
					<u-loading slot="loading"></u-loading>
					<view slot="error" style="font-size: 24rpx;">加载失败</view>
				</u-image>
			</view>
			<view class="bind-block" v-else>
				<u-image :fade="false" class="u-flex u-row-between logo" :src="logo" width="148" height="148">
					<u-loading slot="loading"></u-loading>
					<view slot="error" style="font-size: 24rpx;">加载失败</view>
				</u-image>
				<view class="bind-phone">{{ bindPhone }}</view>
				<view class="bind-tips">{{ bindTips }}</view>
			</view>
			<u-gap height="480"></u-gap>
            <view v-if="needAuth" @click.capture="loadLogin">
                <button class="loginBtn" lang="zh_CN"
                 @tap="getUserProfile">
                	<text class="u-font-32 white">{{ loginTitle }}</text>
                </button>
            </view>
            <view @click.capture="getCode" v-else>
                <button class="loginBtn" open-type="getPhoneNumber"
                 throttle-time="1000" @getphonenumber="signupLogin">
                    <text class="u-font-32 white">{{ bindTitle }}</text>
                </button>
            </view>
		</view>
	</view>
</template>

<script>
import util from '@/utils/util.js'
import login from '@/utils/login.js'
const app = getApp()
export default {
	data() {
		return {
			needAuth: true,
			TimeID: -1,
			loginTitle: '用户登录',
			bindTitle: '立即绑定',
			bindPhone: '绑定手机',
			bindTips: '首次登录的用户需绑定手机才可接单',
			code: '',
		}
	},
	computed: {
		logo() {
			return this.qnFile('logo.png')
		},
		logo2() {
			return this.qnFile('logo-2.png')
		},
	},
	onLoad(e) {
		app.trackPage('授权登录页')
	},
	onShow() {
		// 微信授权过用户信息，则无需重复授权
		if (this.vuex_auth_user && Object.keys(this.vuex_auth_user).length) {
			this.needAuth = false
		}
	},
	methods: {
        loadLogin() {
            uni.showLoading({
            	title: '加载中..',
            	mask: true
            });
        },
		qnFile(src) {
			return process.uniEnv.qn_base_url + src
		},
		async getCode() {
			login.appLogin().then(res => {
				this.code = res.code
			})
		},
		// 微信授权用户信息
		getUserProfile() {
			var that = this
			if(uni.getUserProfile) {
				// 每次触发 uni.getUserProfile 均会弹出授权窗口，用户授权后可成功获取用户信息
				uni.getUserProfile({
					desc: '用于授权登录',
					success: function (res) {
						const userInfo = res.userInfo;
						that.$u.vuex('vuex_auth_user', userInfo)
						uni.showLoading({
							title: '授权中..',
							mask: true
						});
						if (getApp().globalData.logout) {
							uni.hideLoading()
							that.setLoginStatus()
						} else {
							that.authLogin()
						}
					},
					fail: function (res) {
                        uni.hideLoading()
						uni.showModal({
							title: '授权失败',
							content: '请允许获取用户信息的授权',
							showCancel: false
						});
					}
				})
			} else {
                uni.hideLoading()
				// 可能由于账号配置，或者其他原因导致无法调起微信用户授权
				uni.showModal({
					title: '授权失败',
					content: '请确认你的用户授权是否可用',
					showCancel: false
				});
			}
		},
		authLogin() {
			var that = this
			let params = {
				nickname: this.vuex_auth_user.nickName || '',
				avatar: this.vuex_auth_user.avatarUrl || '',
			}
			login.appLogin().then(res => {
				params.code = res.code
				return login.authorization(params);
			}).then(res => {
				uni.hideLoading();
				if (res && res.code == 200 && res.data && res.data.token) {
					login.setUserData(res.data, that)
					app.track('auth_login', {mobile: res.data.mobile});
					app.profileSet(that)
					app.profileAppend(that)
					that.goBackPage()
				} else {
					that.setLoginStatus()
				}
			}).catch(res => {
				uni.hideLoading()
				that.setLoginStatus()
			})
		},
        inGetAuth() {
          uni.showLoading({
          	title: '授权中..',
          	mask: true
          });  
        },
		signupLogin(e) {
			var that = this
			if(e && e.detail) {
				if(e.detail.errMsg.indexOf('user deny') > -1) {
					uni.showModal({
						title: '提示',
						showCancel: false,
						content: '用户未授权不能完成注册'
					});
				} else if(e.detail.encryptedData && e.detail.iv) {
					let params = {
						nickname: this.vuex_auth_user.nickName || '',
						avatar: this.vuex_auth_user.avatarUrl || '',
						encryptedData: e.detail.encryptedData,
						iv: e.detail.iv,
					}
					if (that.code) {
                        that.inGetAuth()
						uni.checkSession({
							success () {
								//session_key 未过期，并且在本生命周期一直有效
								params.code = that.code
                                that.inGetAuth()
								login.signup(params).then(res => {
                                    that.inGetAuth()
									if (res) {
										login.setUserData(res.data, that)
										app.track('signup_login', {mobile: res.data.mobile});
										app.profileSet(that)
										app.profileAppend(that)
										app.getBaseInfo(that)
                                        uni.hideLoading()
										that.goBackPage()
									} else {
                                        uni.hideLoading()
										uni.showToast({
											title: '授权失败，请重新授权',
											icon: 'none'
										});
										that.setLoginStatus(false)
									}
								}).catch(res => {
									uni.hideLoading()
									that.setLoginStatus(false)
								})
							},
							fail () {
								// session_key 已经失效，需要重新执行登录流程
								that.toLogin(params)
							}
						})
					} else {
						that.toLogin(params)
					}
				} else {
                    uni.hideLoading()
					uni.showModal({
						title: '提示',
						showCancel: false,
						content: '用户取消授权'
					});
				}
			} else {
                uni.hideLoading()
				uni.showModal({
					title: '提示',
					showCancel: false,
					content: '授权失败，请重新授权'
				});
			}
		},
		toLogin(params) {
			login.appLogin().then(res => {
				params.code = res.code
				return login.signup(params);
			}).then(res => {
				if (res) {
					login.setUserData(res.data, this)
					app.track('signup_login', {mobile: res.data.mobile});
					app.profileSet(this)
					app.profileAppend(this)
					app.getBaseInfo(this)
					this.goBackPage()
				} else {
                    uni.hideLoading()
					uni.showToast({
						title: '授权失败，请重新授权',
						icon: 'none'
					});
					this.setLoginStatus(false)
				}
			}).catch(res => {
				uni.hideLoading()
				this.setLoginStatus(false)
			})
		},
		goBackPage() {
			let pages = getCurrentPages();
			if(pages.length) {
				let index = pages.length - 1;
				if(index) {
					let prevPage = pages[index]; //上一个页面
					if (prevPage && prevPage.$vm) {
						prevPage.$vm.isRefresh = true;
					}
					uni.navigateBack({
						delta: 1
					})
				} else {
					uni.redirectTo({
						url:'pages/index/index'
					})
				}
			} else {
				uni.reLaunch({
					url: "pages/index/mine"
				})
			}
			
		},
		setLoginStatus(authed = true) {
			getApp().globalData.logout = false
			this.code = ''
			if (authed) {
				this.needAuth = false
				uni.setNavigationBarTitle({
					title: '登录页'
				});
			} else {
				if(!this.vuex_auth_user || !Object.keys(this.vuex_auth_user).length) {
					this.needAuth = true
					uni.setNavigationBarTitle({
						title: '授权页'
					});
				}
			}
		},

		//取消点击
		cancelClick: function () {
			uni.navigateBack({})
		},
	}
}
</script>

<style lang="scss" scoped>
.backView {
	background-color: #FFFFFF;
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;

	.login-block {
		margin-top: 240rpx;
	}
	.bind-block {
		margin-top: 202rpx;
		margin-left: 50rpx;
		.bind-phone {
			font-size: 52rpx;
			margin-top: 48rpx;
			font-weight: bold;
			color: #333333;
			line-height: 52rpx;
			margin-left: 10rpx;
		}
		.bind-tips {
			margin: 24rpx 60rpx 14rpx 10rpx;
			font-size: 28rpx;
			font-weight: 400;
			color: #999999;
			line-height: 40rpx;
		}
	}
}
.logo2 {
	margin-top: 28rpx;
}

.noticeView {
	background-color: #FFFFFF;
	width: 100%;
	height: 470rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.noticeImage {
	background-color: #FFFFFF;
	width: 386rpx;
	height: 270rpx;
	margin-top: 180rpx;
}

.noticeTitleView {
	margin-top: 80rpx;
	width: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
}

.noticeTitle {
	width: 60%;
	font-size: 24rpx;
	color: #999999;
	text-align: center;
	line-height: 40rpx;
}

.loginBtn {
	background-color: #2272FF;
	font-size: 32rpx;
	font-weight: 600;
	color: #FFFFFF;
	line-height: 104px;
	width: 600rpx;
	height: 104rpx;
	border-radius: 52rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.disable {
    background-color: #2272FF !important;
    font-size: 32rpx;
    font-weight: 600;
    color: #FFFFFF !important;
    line-height: 104px;
    width: 600rpx;
    height: 104rpx;
    border-radius: 52rpx;
    display: flex;
    align-items: center;
    justify-content: center;
}

.cancelView {
	width: 100%;
	margin-top: 30rpx;
	display: flex;
	align-items: center;
	justify-content: center;
}

.cancelText {
	color: #666666;
	font-size: 32rpx;
}

.white {
	color: #FFFFFF;
}

</style>
