<template>
	<view class="page-content my-bg">
		<cu-custom class="main-topbar bg-main-oil" bgColor="bg-main-oil">
			<block slot="content">星油云站</block>
		</cu-custom>
		<view class="bg-img margin flex padding-lg radius align-center text-center"
			:style="'background-image: url('+mainURL+'login-bg.png)'">
			<view class="padding-lg margin text-center text-lg text-white w100">
				<text class="">
					油站工作人员绑定油站
				</text>
			</view>

		</view>
		<view class="pannel">
			<view class="bg-white margin padding radius  ">
				<view class="cu-form-group radius " @tap="routerTo('/pages/login/posLogin/posLogin')">
					<view class="title mini-label text-black">已有账号登录</view>
					<view class="cuIcon-right">

					</view>
				</view>
				<!-- <view class="cu-form-group  padding-top" @tap="routerTo('/pages/login/login')">
					<view class="title mini-label text-black">首次认证登录</view>
					<view class="cuIcon-right">
					</view>
				</view> -->
			</view>

		</view>
		<view class="margin text-center">
			<button v-if="checked" class="cu-btn round  bg-main-oil  lg text-lg" open-type="getPhoneNumber"
				@getphonenumber="decryptPhoneNumber">
				<!-- <text class="cuIcon-weixin padding-right-xs"> </text> -->
				<text>
					手机号快捷登录
				</text>
			</button>
			<button v-else class="cu-btn round  bg-main-oil  lg text-lg" @click="$refs.popup.open('center')">
				<text>
					手机号快捷登录
				</text>
			</button>
			<!-- <button class="cu-btn round  btnSize" open-type="getPhoneNumber"
				@getphonenumber="decryptPhoneNumber">
				<text class="cuIcon-weixin  text-green lg"></text>
			</button> -->
		</view>

		<view class="bottom-part">
			<service-hotline ref="serviceHotline" :checked='checked' @onCheck="checkAgree" />
		</view>

		<uni-popup ref='popup'>
			<view class="protocol_body">
				<view class="protocol_header">
					使用协议及隐私保护
				</view>
				<view class="protocol_content">
					为了更好地保障您的合法权益，请您阅读并同意 <text style="  color: black; font-weight: 600;"
						@click="$refs.serviceHotline.toAgree('xoilCloudUserAgree')">《用户协议》</text> 与 <text
						style=" color: black; font-weight: 600;"
						@click="$refs.serviceHotline.toAgree('xoilCloudPrivacyAgreement')">《隐私政策》</text>。
				</view>
				<view class="protocol_footer">
					<button @click="$refs.popup.close()" class="protocol_footer_close">取消</button>
					<button @click="checked=true;$refs.popup.close();" class="protocol_footer_confirm">确定</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import cloudSiteApi from '@/api/cloud-site.js'
	import loginApi from '@/api/login.js'
	import oilIdentityApi from '@/api/oil-identity.js'
	import oliUserApi from '@/api/oli-user.js'
	// import loginBottom from './components/loginBottom.vue'
	export default {
		// components:{
		// 	loginBottom
		// },
		data() {
			return {
				count: 0,
				baseURL: this.global.baseURL,
				mainURL: this.global.mainURL,
				forcedLogin: true,
				oilSiteNo: '',
				sessionKey: '',
				outType: '0',
				checked: false
			};
		},
		created() {
			uni.showShareMenu()
			// this.loginWeixin()
		},
		onLoad(option) {
			if (option.type == '1') {
				this.outType = option.type
				uni.clearStorageSync() //清除缓存
			}
			// this.refreshLocation()
			uni.login({ //微信登陆
				provider: 'weixin',
				success: (loginRes) => {
					const code = loginRes.code
					let _that = this
					this.onceCode = code
					oilIdentityApi.sendCode(this.onceCode).then(res => { //根据微信登陆返回的code获取unionid openid
						if (res.code === 20000) {
							this.sessionKey = res.data.sessionKey
							uni.setStorageSync('openid', res.data.openId)
							uni.setStorageSync('unionid', res.data.unionId)
							if (_that.outType !== '1') {
								this.autoLogin()
								return
							}
						} else if (res.code == 1002) {
							uni.showModal({
								title: '微信登录失败提醒',
								content: `${res.msg}如有疑问，请联系客服处理`
							})
						} else {
							// console.log('res', res.code)
						}
					}).catch(err => {
						uni.reLaunch({
							url: '/BagAuth/pages/login/boforeLogin/boforeLogin',
							fail: (err) => {
								// console.log(err)
							}
						})
					})
				},
				fail: err => {},
			})
		},
		methods: {
			checkAgree(val) {
				this.checked = val
			},
			decryptPhoneNumber(e) {
				if (!this.checked) {
					uni.showToast({
						title: '请您阅读并同意协议',
						icon: 'none'
					})
					return
				}
				// 通过用户授权获取到用户的手机号信息
				if (e.detail.errMsg === 'getPhoneNumber:ok') {
					const data1 = {
						...e.detail,
						sessionKey: this.sessionKey,
						unionId: uni.getStorageSync('unionid'),
						openId: uni.getStorageSync('openid'),
						appId: 'wxaf56b8bae925ba19'
					}
					let url1 = 0 == this.TabCur ? 'bindLoginByPhonePersonal' : 'bindLoginByPhoneCompany'
					this.bindLoginByPhone(data1, url1)
				} else {
					uni.showModal({
						title: '您已拒绝授权手机号'
					})
				}
			},
			bindLoginByPhone(data, url) { //绑定用户手机号
				if (this.count < 1) {
					oilIdentityApi.bindLoginByPhonePersonal(data, url).then(res => {
						if (res.code == 20000) {
							this.loginSuccess(res)
						}
					})
				}
			},
			loginSuccess(res) { //这里是绑定登录 
				if (res.data.authTokenDTO.loginFlag) {
					this.setStored(res)
				}
			},
			refreshLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: function(res) {
						uni.setStorageSync('location', res)
					}
				});
			},
			routerTo(url) {
				uni.navigateTo({
					url: url
				})
			},
			autoLogin() { //根据登录时获取到的 unionid openid 自动登录
				let data = {
					unionId: uni.getStorageSync('unionid'),
					openId: uni.getStorageSync('openid')
				}
				console.log(data, '这里是自动登录data')
				oilIdentityApi.loginPersonal(data).then(res => { //微信自动登录
					console.log(res, '这里是自动登录res')
					if (res.data.authTokenDTO.loginFlag == true) {
						this.setStored(res)
					}
				})
			},
			// 存值本地 根据手机号获取其下的油站并且存储本地
			setStored(res) {
				let user = res.data.authTokenDTO.loginUser,
					unionId = uni.getStorageSync('unionid'),
					openId = uni.getStorageSync('openid'),
					phone = res.data.sysCustomerInfo.phone //获取该用户手机号
				setTimeout(() => {
					uni.showToast({
						title: res.msg,
						icon: 'none',
						complete: (err) => {
							// console.log(err)
						}
					})
				}, 1000);
				uni.setStorageSync('user', user)
				uni.setStorage({
					key: 'Authorization',
					data: res.data.authTokenDTO.accessToken,
					success: () => {
						console.log('Authorization成功', res.data.authTokenDTO.accessToken)
					}
				})
				uni.setStorage({
					key: 'device',
					data: openId,
					success: () => {
						console.log('deviceopenid', openId)
					}
				})
				uni.setStorage({
					key: 'unionId',
					data: unionId,
					success: () => {
						console.log('deviceunionId', unionId)
					}
				})
				uni.setStorageSync('userMenu', res.data.authTokenDTO.loginUser.roleMenus) //获取权限菜单列表
				uni.setStorageSync('loginUser', { //存储用户基本信息 id,name,userphone
					id: res.data.authTokenDTO.loginUser.id,
					name: res.data.authTokenDTO.loginUser.name,
					userPhone: res.data.authTokenDTO.loginUser.userPhone
				})
				//根据获取手机号 获取其号下的油站信息
				console.log('这里是获取手机号登录')
				oliUserApi.getByPhone(phone).then((res) => {
					console.log('这里是获取手机号登录', res)
					if (res.code == 20000) {
						uni.setStorageSync('oliList', res.data) //本地存储当前用户其下有多少油站，用于用户登录进入时选择进入油站
						// 获取信息存储本地
						uni.setStorageSync('checkFirst', true) //进入前重置进入状态，判断用户是否是登录进入，用来做区分
						uni.showToast({
							title: res.msg,
							icon: 'success',
							duration: 3000
						})
						uni.reLaunch({
							url: '/pages/index/index',
							fail: (err) => {
								console.log(err)
							}
						})
					} else {
						uni.showToast({
							title: '未绑定油站请联系客服',
							icon: 'none',
							duration: 1500
						})
					}
				})
			},
			nextStep() {
				if (this.oilSiteNo) {
					cloudSiteApi.verifyOilSite({
						oilSiteCode: this.oilSiteNo
					}).then(res => {
						if (res.code === 20000) {
							//历史遗留代码---------------------------------
							// address: "安徽省合肥市庐阳区大杨镇"
							// fuelLogo: null
							// linkMan: "符红敏"
							// oilSiteCode: "1591260293"
							// oilSiteName: "杭州首鸿金融信息服务有限公司"
							// phone: "15617055136"
							//--------------------------------------------
							uni.setStorage({
								key: 'oilSiteCode',
								data: this.oilSiteNo,
								success: () => {
									console.log('缓存成功')
								}
							})
							uni.setStorage({
								key: 'oilSite',
								data: res.data,
								success: () => {
									console.log('缓存成功')
								}
							})
							uni.navigateTo({
								url: '/pages/Auth/Auth'
							})
						}
					})
					//历史遗留代码 不知道干嘛的 保不齐之后要用--------------
					// uni.setStorage({
					// 	key: 'oilSiteCode',
					// 	data: this.oilSiteNo,
					// 	success: () => {
					// 		console.log('缓存成功')
					// 	}
					// })
					// uni.navigateTo({
					// 	url: '/pages/Auth/Auth'
					// })
					//--------------------------------------------------
				} else {
					uni.showToast({
						title: '请输入云站号',
						duration: 3000,
						icon: 'none'
					})
				}
			},
			getMsg() {
				uni.requestSubscribeMessage({
					tmplIds: ['W5XD3NQVa6knC5jXHeWT8GS7q5CHrDUMY_sF79kLkKk'],
					success: (res) => {
						console.log(res)
					}
				})
			},
			getUserInfo({
				detail
			}) {
				console.log('三方登录只演示登录api能力，暂未关联云端数据');
				console.log('detail', detail)
				if (detail.userInfo) {
					this.loginLocal(detail.userInfo.nickName);
				} else {
					uni.showToast({
						icon: 'none',
						title: '登陆失败'
					});
				}

			},
			loginLocal(nickName) {
				uni.setStorageSync('login_type', 'local')
				uni.setStorageSync('username', nickName)
				this.toMain(nickName);
			},
			toMain(userName) {
				// this.login(userName) 
				/**
				 * 强制登录时使用reLaunch方式跳转过来
				 * 返回首页也使用reLaunch方式
				 */
				if (this.forcedLogin) {
					uni.reLaunch({
						url: '/pages/index/index',
						success: () => {
							console.log('success')
						},
						fail: err => {
							console.log(err)
						}
					});
				} else {
					uni.navigateBack();
				}

			}
		}
	};
</script>

<style scoped>
	.protocol_footer_close {
		width: 185rpx; 
		border-radius: 94rpx 94rpx 94rpx 94rpx;
		opacity: 1;
		border: 1px solid #000000;
		font-size: 26rpx;
	}
	
	.protocol_footer_confirm {
		width: 185rpx; 
		background: #FD0505;
		border-radius: 56rpx 56rpx 56rpx 56rpx;
		opacity: 1;
		font-size: 26rpx;
		color: #FFFFFF;
	}
	
	.protocol_footer {
		display: flex;
		justify-content: space-between; 
		color: #FFFFFF;
	}
	
	.protocol_content {
		font-size: 32rpx;
		font-family: PingFang SC-Medium, PingFang SC;
		font-weight: 400;
		color: #666666;
		line-height: 46rpx;
		margin: 60rpx 0;
	}
	
	.protocol_header {
		width: 330rpx;
		height: 32rpx;
		font-size: 36rpx;
		color: #000000;
		width: 100%;
		text-align: center;
	}
	.protocol_body {
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 20rpx 20rpx;
		opacity: 1;
		padding: 70rpx 50rpx;
		max-width: 634rpx;
		box-sizing: border-box;
	}
	.btnSize {
		font-size: 60rpx;
	}

	.page-content {
		position: relative;
	}

	.logo {
		min-width: 100%;
		text-align: center;
	}

	.logo img {
		width: 200upx;
		height: 200rpx;
		background-size: contain;
		margin: auto;
	}

	.bottom-bg {
		position: sticky;

		bottom: 50upx;
	}
</style>
