<template>
	<view class="login-all-wrap">
		<image class="bgimage" src="./image/bj_denglu.png"></image>
		<view class="leftbtn" :style="'top:' + top + 'px;'">
			<view @click="changelogintype" v-if="false">{{i18n.login.passLogin}}</view>
			<view @click="changelogintype" v-if="false">{{i18n.login.kuaijieLogin}}</view>
		</view>
		<view v-if="loginType == true" class="logintitle">{{i18n.login.shoujikuaijieLogin}}</view>
		<view v-if="loginType == false" class="logintitle">{{i18n.login.zhpassLogin}}</view>
		<view class="vview"></view>
		<view class="codephoneinput row">
			<input :placeholder="i18n.login.placePhone" v-model="mobile" @input="mobileinpit" :maxlength="11"
				type="number" placeholder-style="color:rgba(201,201,201,1);" />
		</view>
		<block v-if="loginType == true">
			<view class="codephoneinput row" style="margin-top: 20px;">

				<input :focus="codeFocus" :placeholder="i18n.login.placeCode" v-model="codes" :maxlength="6"
					style="flex: 1;" type="number" placeholder-style="color:rgba(201,201,201,1);" />
				<view @click="getSmsCode" class="codetext"
					:style="canshowcode == true?  'color: #FF5725;': 'color: rgba(201,201,201,1);'">
					{{codetimes}}
				</view>
			</view>
		</block>
		<block v-else>
			<view class="codephoneinput row" style="margin-top: 20px;">
				<input :placeholder="i18n.login.pleasePass" :focus="passwordFocus" style="width: 100%;"
					v-model="password" :password="true" type="text" placeholder-style="color:rgba(201,201,201,1);" />
			</view>
			<view class="codephoneinput row" style="margin-top: 20px;display: flex;">
				<input placeholder="请输入验证码" style="width: 100%;"
					v-model="code" type="text" placeholder-style="color:rgba(201,201,201,1);" />
				<img :src="captchaImg" alt="加载验证码失败"
					style="width: 180rpx; height: 74rpx; cursor: pointer; display: block" @click="getCaptchaImg" />
			</view>
		</block>
		<view class="small-btn">
			<view  class="reg-btn" @click="loginType = !loginType">
				切换登录方式
			</view>
			<!-- <navigator v-if="loginType == false" class="forget-pass" url="/pages/login/regist?type=3">
				{{i18n.login.forgetPass}}
			</navigator> -->
		</view>
		<button enabled="enabled" class="login-btn" style="border-radius: 50rpx; border: 0;" type="primary"
			:class="{ opatity: enabled}" @click="submit">
			{{i18n.login.login}}
		</button>
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<view class="popup-title">
					<text>选择登录店铺</text>
				</view>
				<view class="popup-container" v-for="item in shopList" :key="item" @tap="checkShop(item)">
					<text style="display: inline-block">{{item.shopName}}</text>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	
	const app = getApp();
	// import {
	// 	genTestUserSig
	// } from '@/debug/GenerateTestUserSig.js';
	export default {
		components: {},
		data() {
			return {
				captchaId:'',
				wayValue:0,
				captchaImg:'',
				top: 0,
				loginType: false,
				codetimes: '获取验证码',
				timer: null,
				canshowcode: false,
				passwordFocus: false,
				codeFocus: false,
				agree: true,
				mobile: "",
				password: "",
				captchaId: '',
				phone: "",
				code: "",
				codes:'',
				smsType: 0, //获取验证码类型 0 登录 1 注册 2忘记密码
				unionid: '',
				nickName: '',
				avatar: '',
				countryCode: '+86',
				captcha: ''
			}
		},
		onShow() {
			var that = this
			uni.getStorage({
				key: 'countryCode',
				success: res => {
					that.countryCode = res.data
					console.log(res)
				}
			})
			// this.captchaInit()
		},
		onReady() {
			this.codetimes = this.i18n.login.getcode
		},
		onUnload() {
			clearInterval(this.timer)
			this.timer = null
		},
		onLoad(option) {
			this.top = getApp().globalData.top + 20
			// this.setregisterID()
			this.getCaptchaImg();
		},
		computed: {
			enabled: function() {
				if (this.loginType == true) {
					if (this.mobile.length == 11 && this.codes.length == 6) {
						return false;
					}
				} else {
					if (this.mobile.length == 11 && this.password.length > 5) {
						return false;
					}
				}
				return true;
			},
			i18n() {
				return this.$t('index')
			},
			captchaUrl() {
				return `https://storage.xenjoyou.com/hiver/common/captcha/draw/${this.captcha}`
			}
		},
		methods: {
			
			captchaInit() {
				const that = this
				this.NB.sendRequest('/common/captcha/init', {}, false).then(data => {
					that.captcha = data.result
					console.log('data.data.result',data.result)
					  this.NB.sendRequest('https://storage.xenjoyou.com/hiver/common/captcha/draw/'+ data.result, {}, false).then(data => {
					    console.log('data',data)
					    that.captcha = data
					  })
				}).catch(data => {})
			},
			setregisterID(info) {
				const clientId = getApp().globalData.registrationID
				this.NB.sendRequest('/worker/admin/editApp', {
					workerId: info.workerId,
					clientId:clientId
				}, false, 'POST')
			},
			chooseCountry() {
				uni.navigateTo({
					url: 'country'
				})
			},
			NotAgree() {
				if (this.agree == false) {
					uni.showToast({
						title: this.i18n.login.yuedubngtongyixieyi,
						icon: 'none'
					})
					return
				}
			},
			saveLocal(info) {
				this.setregisterID(info)
				getApp().globalData.userinfo = info
				uni.setStorageSync(
					'userinfo',
					info,
				);
				


				// getApp().globalData.userinfo = info
				// console.log(info)
				// uni.setStorage({
				// 	key: 'userinfo',
				// 	data: info,
				// 	success: function() {}
				// });

				// setTimeout(function() {
				// 		uni.reLaunch({
				// 			url: '../index/index'
				// 		})
				// 	}, 1000);
			},
			changelogintype() {
				this.passwordFocus = false
				this.codeFocus = false
				this.loginType = !this.loginType
			},
			mobileinpit(event) {
				if (this.loginType == true) {
					if (event.detail.value.length == 11) {
						this.canshowcode = true
					} else {
						this.canshowcode = false
					}
				} else {
					if (event.detail.value.length == 11) {
						this.passwordFocus = true
					} else {
						this.passwordFocus = false
					}
				}
			},
			password_input(event) {},
			agreeme() {
				if (this.agree == true) {
					this.agree = false;
				} else {
					this.agree = true;
				}
			},
			gotoxieyi(ID) {
				var url = getApp().globalData.weburl + 'appapi/page/detail?id=' + ID
				uni.setStorage({
					key: 'weburl',
					data: url,
					success() {
						uni.navigateTo({
							url: '../webview/index',
						});
					}
				})
			},
			register() {
				uni.navigateTo({
					url: "../reg/reg"
				})
			},
			getSmsCode() {
				var that = this
				if (this.canshowcode == false) {
					return
				}
				let sign = this.NB.sort2url({
					'account': this.mobile,
					'type': 1
				});
				var dic = {}
				dic.account = this.mobile
				dic.code = this.countryCode
				dic.type = 1
				dic.sign = sign
				console.log(dic)
				this.NB.sendRequest(`/common/captcha/sendLoginSms/${this.mobile}`, {
					type: this.wayValue
				}, true).then(data => {
					if (data.code == 200) {
						that.codeFocus = true
						var time = 60
						that.canshowcode = false
						clearInterval(that.timer)
						that.timer = null
						that.codetimes = '(' + '60s)'
						that.timer = setInterval(function() {
							time = time - 1
							that.codetimes = '(' + time + 's)'
							if (time <= 0) {
								clearInterval(that.timer)
								that.timer = null
								that.canshowcode = true
								that.codetimes = "获取验证码"
							}
						}, 1000);
					}
				}).catch(data => {
					console.log(data)
					if (data.code == 200) {
						that.codeFocus = true
						var time = 60
						that.canshowcode = false
						clearInterval(that.timer)
						that.timer = null
						that.codetimes = '(' + '60s)'
						that.timer = setInterval(function() {
							time = time - 1
							that.codetimes = '(' + time + 's)'
							if (time == 0) {
								clearInterval(that.timer)
								that.timer = null
								that.canshowcode = true
								that.codetimes = this.i18n.login.getcode
							}
						}, 1000);
					}
				})
			},
			getCaptchaImg() {
				this.NB.sendRequest('/common/captcha/init', {}, false, 'GET', 'application/json').then(res => {
					
					if (res.code == 200) {
						this.captchaId = res.result
						this.captchaImg = getApp().globalData.mainurl + '/common/captcha/draw/' + this
							.captchaId
						
					} else {
						this.tui.toast(res.message)
					}
				})
			},
			//多店铺的时候点击选择需要登录的店铺
			checkShop(item) {
				let that = this;
				uni.getSystemInfo({
					success: function (res1) {
						that.NB.sendRequest('/auth/chooseShop', {
							shopId: item.shop.id,
							deviceId:res1.deviceId
						}, true, 'POST', 'application/x-www-form-urlencoded').then(res => {
							if (res.code == 200) {
								uni.setStorageSync('type',item.type)
								uni.setStorageSync('warehouseKeeperFlag',item.warehouseKeeperFlag)
								uni.setStorageSync('shopId',item.shop.id)
								uni.setStorageSync('shopName',item.shopName)
								uni.setStorageSync('storeFlag',item.storeFlag)
								uni.setStorageSync('shopIcon',res.result.shopIcon)
								uni.setStorageSync('shopAddress',res.result.shopAddress)
								uni.setStorageSync('shopRemark',res.result.remark)
								uni.setStorageSync("shopOwnerPhone", item.shopOwnerPhone)
								uni.setStorageSync('schoolShop',res.result.shop)
								uni.setStorageSync('schoolShop',res.result.shop)
								uni.setStorageSync('shopTakeaway',item.shopTakeaway)
								uni.setStorageSync('area',JSON.stringify(item))
								uni.setStorageSync("isShop",true)
								setTimeout(() => {
									uni.reLaunch({
										url: '../index/index'
									})
								}, 200)
								uni.showToast('登录成功', 2000, true)
							} else {
								that.tui.toast(res.message)
								return
							}
						}).catch((res) => {})
						
					}
				});
			},
			//打开弹出层
			toggle(type) {
				this.type = type
				this.$refs.popup.open(type)
			},
			submit() {
				if (this.enabled) {
					uni.showToast({
						title: '请输入手机号和验证码后登录',
						icon: 'none'
					});
					return;
				}
				let url;
				let data;
				if (this.loginType == true) {
					url = "/auth/smsLogin";
					data = {
						mobile: this.mobile,
						code: this.codes,
						saveLogin: true,
						type: this.wayValue,
						clientId: uni.getStorageSync('registerID')
					};
				} else {
					url = `/auth/login`;
					data = {
						username: this.mobile,
						password: this.password,
						captchaId: this.captchaId,
						code: this.code,
						saveLogin: true,
						type: 0,
						clientId: uni.getStorageSync('registerID')
					};
				}
				let that = this;
				uni.showLoading({
					title: '',
					mask: true
				});
				
				that.NB.sendRequest(url, data, true, 'POST', 'application/x-www-form-urlencoded').then(res => {
					if (res.code !== 200) return
					console.log('shopList',res.result.shopList)
					console.log('shopList.shop',res.result.shopList[0].shop)
					uni.setStorageSync("hiver_token", res.result.accessToken)
					uni.setStorageSync("wayValue", this.wayValue)
					uni.setStorageSync("nickname", res.result.user.nickname)
					uni.setStorageSync('username',this.mobile)
					
					if (res.result.shopList.length > 1) {
						this.shopList = res.result.shopList;
						
						this.toggle("center");
					}else{
						this.checkShop(res.result.shopList[0])
					}
				})

			}
		}
	}
</script>

<style>
	@import url("./login.css");
</style>