<template>
	
	<view class="pages-user-login">
		<!-- <view class="navbarText">登录</view> -->
		<uni-nav-bar :fixed="false" :shadow="false" :statusBar="true" :onlyLeft="true" :color="`#fff`"
		></uni-nav-bar>
		 <!-- #ifndef H5 -->
		 <view style="position: absolute;z-index:99;right:50upx;top:120upx;">
		 	<u-icon name="close" size="26" @click="goHome"></u-icon>
		 </view>
		
		<!-- #endif -->
		<view class="logocontent">
			<!-- <view class="title">LOGO</view> -->
			<image src="../static/logopic.png" style="width:200rpx;margin:0 auto;height:auto" mode="widthFix"></image>
			<view class="subtitle">希希到家专业O2O服务平台</view>
		</view>
		<view class="form">
			<u--input
				placeholder="请输入手机号"
				prefixIcon="account"
				type="number"
				maxlength="11"
				border="bottom"
				v-model="phone"
				prefixIconStyle="font-size: 40upx;color: #9a9a9a"
			></u--input>
			<!-- #ifndef APP-NVUE -->
			<u-input placeholder="请输入验证码" v-model="code" prefixIcon="lock" prefixIconStyle="font-size: 40upx;color: #9a9a9a" border="bottom">
			<!-- #endif -->
			<!-- #ifdef APP-NVUE -->
			<u--input placeholder="请输入验证码" v-model="code" prefixIcon="lock" prefixIconStyle="font-size: 40upx;color: #9a9a9a"  border="bottom">
				<!-- #endif -->
				<template slot="suffix">
					<u-code
						ref="uCode"
						@change="codeChange"
						seconds="60"
						changeText="X秒重新获取"
					></u-code>
					<text class="getcodebtn" @tap="getCode">{{tips}}</text>
					<!-- <u-button
						:text="tips"
						class="getcodebtn"
						size="mini"
					></u-button> -->
				</template>
			<!-- #ifndef APP-NVUE -->
			</u-input>
			<!-- #endif -->
			<!-- #ifdef APP-NVUE -->
			</u--input>
			<!-- #endif -->
		</view>
		<view style="margin:20rpx 50rpx;display:flex;align-items: flex-start;">
			<u-checkbox-group v-model="checked" >
				<u-checkbox activeColor="#08BF77" name="1" shape="circle"></u-checkbox>
			</u-checkbox-group>
			<view class="">
				请您详细阅读并同意<text @tap.stop="goDetail(1)" :style="{color:primaryColor}">
					《隐私政策》
				</text>与<text @tap.stop="goDetail(2)" :style="{color:primaryColor}">
					《用户协议》
				</text>
			</view>
		</view>
		<button :disabled="!phone||!code" @click="smsLogin()" class="loginBtn">登录</button>
		<!-- <view >登录</view> -->
		 <!-- #ifdef APP-PLUS -->
		<view class="otherLogin">
			<view class="line"></view>
			<view class="otext">其他登录</view>
			<view class="line"></view>
		</view>
		
		<image src="@/static/wlogin.png" class="wlogin" @tap="$refs.show_rule_item.open()" mode="widthFix"></image>
		
		<view class="page-height flex-center flex-column">
			<image mode="aspectFill" lazy-load class="logo-img mb-md" :src="base_info.app_logo"></image>
			<view class="f-caption c-caption">{{base_info.app_text}}</view>
			<view @tap="$refs.show_rule_item.open()" class="wechat-login flex-center f-title c-base" :style="{
			background: `linear-gradient(90deg, ${primaryColor} 0%, ${subColor} 99%)`}"><i
					class="iconfont iconweixin mr-sm"></i>微信登录
			</view>
		</view>

		<uni-popup ref="show_rule_item" type="center" :maskClick="false">
			<view class="common-popup-content fill-base pd-lg radius-34">
				<view class="title">温馨提示</view>
				<view class="f-desc c-title mt-lg">
					登录即表示您已详细阅读并同意<span @tap.stop="goDetail(1)" :style="{color:primaryColor}">
						《隐私政策》
					</span>与<span @tap.stop="goDetail(2)" :style="{color:primaryColor}">
						《用户协议》
					</span>
				</view>
				<view class="button">
					<view @tap.stop="$refs.show_rule_item.close()" class="item-child">取消</view>
					<view @tap.stop="wxLogin" class="item-child c-base"
						:style="{background: primaryColor,color:'#fff'}">确定</view>
				</view>
			</view>
		</uni-popup>
		<!-- #endif -->
		
		<!-- #ifdef MP-WEIXIN -->
		<view class="otherLogin">
			<view class="line"></view>
			<view class="otext">其他登录</view>
			<view class="line"></view>
		</view>
		
		<!-- <image src="@/static/wlogin.png" class="wlogin" @tap="miniLoginHandle" mode="widthFix"></image> -->
		<button  @click="miniLoginHandle" class="loginBtn">微信登录</button>
		
		<!-- #endif -->

	</view>
</template>

<script>
	import {
		mapState,
		mapActions,
		mapMutations
	} from 'vuex';
	import siteInfo from '@/siteinfo.js';
	import $store from "@/store/index.js"
	export default {
		components: {},
		data() {
			return {
				isLoad: false,
				base_info: {},
				tips: '',
				code:'',
				phone:'',
				checked:[],
				pid:null
				
			}
		},
		async onLoad(option) {
			// console.log('pages/login',"888")
			// #ifdef H5
			var searchURL = window.location.search;
			searchURL = searchURL.substring(1, searchURL.length);
			var targetPageId = searchURL.split("&")[0].split("=")[1].split("?")[0];
			console.log(option,targetPageId.substring(-1,1))
			this.pid=targetPageId?targetPageId.substring(-1,1):''
			this.pid = targetPageId
			// #endif
			let {
				autograph = '',
				appLogin = ''
			} = this
			console.log('autograph,appLogin', autograph, appLogin)
			if (autograph && appLogin) {
				if(appLogin.unionId){
					this.toLogin(appLogin)
					return
				}else{
					console.log("777")
					this.checked=[]
					this.checked.push('1')
					this.smsLogin(appLogin)
					return
				}
				
			}
			let data = await this.$api.base.getConfig()
			console.log(data,"fff")
			this.base_info = data
			if (!data.primaryColor) {
				data.primaryColor = '#A40035'
			}
			if (!data.subColor) {
				data.subColor = '#F1C06B'
			}
			let configInfo = Object.assign(this.$util.deepCopy(this.configInfo), data)
			this.updateConfigItem({
				key: 'configInfo',
				val: configInfo
			})
			this.isLoad = true
		},
		computed: mapState({
			primaryColor: state => state.config.configInfo.primaryColor,
			subColor: state => state.config.configInfo.subColor,
			configInfo: state => state.config.configInfo,
			autograph: state => state.user.autograph,
			appLogin: state => state.user.appLogin,
			userInfo: state => state.user.userInfo,
		}),
		methods: {
			...mapActions(['getConfigInfo', 'getUserInfo','getMineInfo']),
			...mapMutations(['updateConfigItem', 'updateUserItem']),
			//微信登录
			async wxLogin() {
				this.$refs.show_rule_item.close()
				try {
					let [providerErr, providerData] = await uni.getProvider({
						service: 'oauth',
					});
					// let [loginErr, loginData] =await uni.getUserProfile({
					// 	desc: '用于您的页面展示用户头像与昵称',
					// 	lang: 'zh_CN',
					// 	success: res => {
					// 	    console.log(res,"jjj");
					// 		// this.isShowLogin = false;
					// 		// this.userInfo = res.userInfo;
					// 	},
					// 	fail: err => {
					// 		console.log(err.errMsg);
					// 	}
					// });
					
					let [loginErr, loginData] = await uni.login({
						provider: 'weixin'
					});
					let [infoErr, infoData] = await uni.getUserInfo({
						provider: 'weixin'
					})
					console.log("333",infoData)
					let {
						userInfo = {}
					} = infoData
					let {
						openId = ''
					} = userInfo;
					// #ifdef APP-PLUS
					if (!openId) return
					// #endif
					this.$util.showLoading({
						title: "登录中..."
					})
					try {
						this.toLogin(userInfo)
					} catch (e) {
						this.$util.hideAll()
					}
				} catch (e) {
					console.log(e)
					this.$util.showToast({
						title: '请先安装微信或升级版本'
						
					});
				}

			},
			//小程序微信登陆
			async miniLoginHandle(){
				if(this.checked.length==0){
					uni.$u.toast('请阅读并同意《隐私政策》和用户协议');
					 return false;
				}
				let res = await this.miniproLogin();
				console.log(res,"=======")
				uni.navigateBack({
					delta:1
				})
				// uni.getUserProfile({
				// 	desc: '用于您的页面展示用户头像与昵称',
				// 	lang: 'zh_CN',
				// 	success: (res) => {
				// 	    console.log(res,"jjj");
				// 		uni.login({
				// 			provider: 'weixin',
				// 			success:async(res) => {
				// 				console.log(res,"====");
				// 				let userLoginInfo = await this.$api.base.mpproLogin({
				// 					code: res.code
				// 				})
				// 				console.log(userLoginInfo)
				// 				this.$util.goUrl({
				// 					url: `/pages/service`,
				// 					openType: `reLaunch`
				// 				})
				// 			}
				// 		});
						
				// 	},
				// 	fail: err => {
				// 		console.log(err.errMsg);
				// 	}
				// });
				
			},
			async smsLogin(item){
				console.log("短信登陆",item)
				if(this.checked.length==0){
					uni.$u.toast('请阅读并同意《隐私政策》');
					 return false;
				}
				let userInfo;
				if(!item){
					let params={
						phone:this.phone,
						code:this.code,
						pid:this.pid
					}
					// #ifdef MP-WEIXIN
					let [providerErr, providerData] = await uni.getProvider({
						service: 'oauth',
					});
					let [loginErr, loginData] = await uni.login({
						provider: providerData.provider[0]
					});
					params.wx_code =loginData.code
					// #endif
					userInfo = await this.$api.base.smsLogin(params)
					
					
				}else{
					userInfo = item;
				}
				console.log(userInfo,"---")
				this.$util.showLoading({
					title: "登录中..."
				})
				try {
					console.log("111")
					
					// let user_info = await this.$api.base.appLogin({
					// 	data: userInfo
					// })
					this.updateUserItem({
						key: 'appLogin',
						val: userInfo
					})
					let {
						autograph,
						data
					} = userInfo
					this.$util.hideAll()
					this.updateUserItem({
						key: 'userInfo',
						val: data
					})
					this.updateUserItem({
						key: 'autograph',
						val: autograph
					})
					if (!this.configInfo.id) {
						await this.getConfigInfo()
					}
					this.getMineInfo(1)
					let {
						phone = ''
					} = data
					phone = 1
					// #ifdef H5
					this.$util.goUrl({
						url: '/user/pages/download',
						openType: `reLaunch`
					})
					// #endif
					// #ifdef APP-PLUS
					this.$util.goUrl({
						url: phone ? `/pages/service` : `/user/pages/phone`,
						openType: `reLaunch`
					})
					// #endif
					this.$util.goUrl({
						url: phone ? `/pages/service` : `/user/pages/phone`,
						openType: `reLaunch`
					})
					
				} catch (e) {
					console.log(e)
					this.$util.hideAll()
				}
			},
			goHome(){
				this.$util.goUrl({
					url :`/pages/service`,
					openType: `reLaunch`
				})
			},
			async toLogin(userInfo) {
				console.log(userInfo,"mmnn")
				let user_info = await this.$api.base.appLogin({
					data: userInfo
				})
				this.updateUserItem({
					key: 'appLogin',
					val: userInfo
				})
				let {
					autograph,
					data
				} = user_info
				this.$util.hideAll()
				this.updateUserItem({
					key: 'userInfo',
					val: data
				})
				this.updateUserItem({
					key: 'autograph',
					val: autograph
				})
				if (!this.configInfo.id) {
					await this.getConfigInfo()
				}
				let {
					phone = ''
				} = data
				phone = 1
				// this.$util.goUrl({
				// 	url: phone ? `/pages/service` : `/user/pages/phone`,
				// 	openType: `reLaunch`
				// })
				// #ifdef H5
				this.$util.goUrl({
					url: '/user/pages/download',
					openType: `reLaunch`
				})
				// #endif
				 // #ifdef APP-PLUS
				this.$util.goUrl({
					url: phone ? `/pages/service` : `/user/pages/phone`,
					openType: `reLaunch`
				})
				// #endif
			},
			goDetail(type) {
				let {
					siteroot
				} = siteInfo
				let href = siteroot.split('index.php')[0]
				let page = type == 1 ? 'protocol' : 'information'
				let url = `${href}${page}.html`
				console.log(url,"iiuu")
				this.$util.goUrl({
					url,
					openType: 'web'
				})
			},
			codeChange(text) {
				this.tips = text;
			},
			async  getCode() {
				var phoneReg = /(^1\d{10}$)|(^[0-9]\d{7}$)/;
				if(!phoneReg.test(this.phone)) {
				   uni.$u.toast('请输入正确的手机号码');
				    return false;
				}
				if (this.$refs.uCode.canGetCode) {
				  // 模拟向后端请求验证码
				  uni.showLoading({
					title: '正在获取验证码'
				  })
				  let res = await this.$api.base.setCode({
				  	phone:this.phone
				  })
				  console.log(res,"999")
				  if(res){
					  uni.hideLoading();
					  // 这里此提示会被this.start()方法中的提示覆盖
					  uni.$u.toast('验证码已发送');
					  // 通知验证码组件内部开始倒计时
					  this.$refs.uCode.start();
				  }
				 
				} else {
				  uni.$u.toast('倒计时结束后再发送');
				}
			},
			//小程序登录
			async miniproLogin() {
				const isW7 = true
				const isH5 = false
				const formatUrl = function(url) {
					let model_name = "longbing_massages_city";
					let baseUrl = isW7 ?
						`${siteInfo.siteroot}?i=${siteInfo.uniacid}&t=${siteInfo.multiid}&v=${siteInfo.version}&from=wxapp&c=entry&a=wxapp&do=api&core=core2&m=${model_name}&s=${url}` :
						`${siteInfo.siteroot}?i=${siteInfo.uniacid}&m=${model_name}&s=${url}`
				
					if (isH5) {
						baseUrl = `/api?i=${siteInfo.uniacid}&m=${model_name}&s=${url}`
					}
					return baseUrl;
				}
				let {
					query
				} = await uni.getLaunchOptionsSync();
				console.log('query', query)
				let url = formatUrl("index/login")
				try {
					uni.showLoading({
						title: "登录中..."
					})
					let [providerErr, providerData] = await uni.getProvider({
						service: 'oauth',
					});
					let [loginErr, loginData] = await uni.login({
						provider: providerData.provider[0]
					});
			
					let login_param = {
						code: loginData.code,
						pid: query.pid
					}
			
					console.log("login_param=1111=>", login_param);
					var Fly = require("../utils/wx.js") //wx.js为您下载的源码文件
					var fly = new Fly; //创建fly实例
					var tokenFly = new Fly();
					let d = await tokenFly.post(url, login_param);
					console.log(d,"0001111111")
					let {
						code,
						data,
						error
					} = d.data
			
					
					if (code !== 200) {
						uni.hideLoading()
						serverError({
							code,
							msg: error
						});
						throw d;
					}
					//登录成功
					uni.hideLoading()
					console.log(data.data,"0003333333")
					$store.commit('updateUserItem', {
						key: 'userInfo',
						val: data.data
					})
					$store.commit('updateUserItem', {
						key: 'autograph',
						val: data.autograph
					})
					return data;
				} catch (e) {
					console.log(e,"0000")
					uni.hideLoading()
					let {
						code,
						error
					} = e.response.data
					if (code !== 200) {
						serverError({
							code,
							msg: error
						});
					}
					return await Promise.reject(e);
				}
			}
		},
		beforeDestroy() {
			
			this.$util.goUrl({
				url :`/pages/service`,
				openType: `reLaunch`
			})
		}
	}
</script>

<style lang="scss">
	page {
		background: #fff;
	}
	.loginBtn{
		// padding:30upx 0;
		text-align: center;
		background: #08BF77 !important;
		border-radius: 10upx;
		margin:50upx 54upx;
		font-size: 34upx;
		font-family: PingFang SC;
		font-weight: 400;
		color: #FFFFFF;
		height: auto;
		width: auto;
	}
	.pages-user-login {
		height: calc(100vh);
		position: relative;
		.navbarText{
			height: 88upx;
			text-align: center;
			border-bottom: 1px solid #EAEAEA;
			line-height: 88upx;
			font-size: 36upx;
			font-family: Alibaba PuHuiTi;
			font-weight: 400;
			color: #333333;
			background: #FFFFFF;
		}
		.logocontent{
			text-align: center;
			.title{
				margin-top: 108upx;
				font-size: 72upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #333333;
			}
			.subtitle{
				font-size: 30upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
				margin-top:59upx;
			}
		}
		.form{
			margin:0  54upx;
			margin-top:calc(5vh);
			/deep/.u-border-bottom {
			    border-color: #eaeaea !important;
				padding:37upx 0 !important;
			}
			.getcodebtn{
				font-size: 30upx;
				font-family: PingFang SC;
				font-weight: 400;
				color: #08BF77;
			}
		}
		
		.otherLogin{
			display: flex;
			align-items: center;
			margin:0 54upx;
			.line{
				height: 1px;
				border: 1px solid #EAEAEA;
				flex:1
			}
			.otext{
				font-size: 28upx;
				font-family: PingFang SC;
				font-weight: 500;
				color: #999999;
				margin:0 47upx;
			}
		}
		.wlogin{
			width:80upx;
			height:80upx;
			margin:50upx auto;
		}
		
		// .logo-img {
		// 	width: 160rpx;
		// 	height: 160rpx;
		// }

		// .wechat-login {
		// 	width: 522rpx;
		// 	height: 98rpx;
		// 	box-shadow: 0 18rpx 9rpx 0 rgba(0, 188, 82, 0.07);
		// 	border-radius: 49rpx;
		// 	margin: 200rpx 0;
		// }

	}
</style>
