<template>
	<view class="content">
		<view class="lang-change" @click="changeLanguage">
			<span :class="currentLanguage == 'English' ? 'current' : ''">En</span>
			<span class="current">/</span>
			<span :class="currentLanguage == '简体中文' ? 'current' : ''">中</span>
			<span class="current">/</span>
			<span :class="currentLanguage == 'Português' ? 'current' : ''">Pt</span>
			<span class="current">/</span>
			<span :class="currentLanguage == 'Russian' ? 'current' : ''">RU</span>
			<span class="current">/</span>
			<span :class="currentLanguage == uzbk ? 'current' : ''">Uz</span>
		</view>
		<view class="logo">
			<image style="height:104rpx;width:104rpx" src="/static/czzn-img/login/logo.png" mode="aspectFit" />
			<view class="app-name">{{$t('login.e')}}</view>
		</view>
		<!-- 账号密码登录 -->
		<template v-if="loginType == 1">
			<view class="inp_box">
				<input type="text" v-model="loginForm.username" @blur="getNameUrl"
					:placeholder="this.$t('login.placeholder')" />
			</view>
			<view class="inp_box" v-if="needCode">
				<input type="text" v-model="loginForm.code" @blur="getUrl"
					:placeholder="this.$t('login.codePlaceholder')" />
			</view>
			<view class="inp_box">
				<input type="password" v-model="loginForm.password"
					:placeholder="this.$t('login.passwordPlaceholder')" />
			</view>

		</template>


		<!-- 手机号登录 -->
		<!-- #ifdef MP-WEIXIN-->
		<template v-else>
			<view class="inp_box">
				<input type="text" v-model="phoneLoginForm.mobile" :placeholder="this.$t('login.phonePlaceholder')" />
			</view>
			<view class="inp_box">
				<input v-model="phoneLoginForm.code" :placeholder="this.$t('login.verifyCodePlaceholder')" />
				<button :class="time != 0 ? 'load-reget' : ''" @click="getCode" :disabled='time != 0'
					class="get-code-btn">{{
					isGetCode ? '' : $t("login.getCode") }}{{ time ? `${time}s` : '' }}</button>
			</view>
		</template>
		<!-- #endif -->
		<!-- 阅读同意/忘记密码 -->
		<view class="agree-forget">
			<view class="agree">
				<uni-data-checkbox selectedColor="#3275F5" multiple v-model="agree" checked=true :localdata="option">
				</uni-data-checkbox>
				<span>{{ $t("login.agree") }}</span>
			</view>
			<span class="forget" @click="toReset" v-if="loginType == 1">{{ $t('login.forgetPassword') }}</span>
		</view>

		<!-- 登录按钮 -->
		<view class="btn-wrap">
			<button :class="agree[0] && canLogin ? 'bind-btn' : 'btn-disabled'" :disabled="!(agree[0] && canLogin)"
				@click="loginType == 1 ? onAccountLogin() : onPhoneLogin()">{{ $t('login.login') }}</button>
		</view>
		<!-- 切换登陆方式/注册 -->
		<view class="login-opertion">
			<!-- <span class="flex" @click="changeLoginType">{{ loginType == 1 ? $t('login.phoneLogin') : $t('login.pwdLogin')
			}}</span>
			<span class="line"></span> -->
			<span class="flex" @click="toRegister">{{ $t('login.register') }}</span>
		</view>
		<!-- 微信登陆 -->
		<!-- #ifdef MP-WEIXIN-->
		<view class="divider">
			<u-divider text="快捷登陆" textSize="12"></u-divider>
		</view>
		<view class="wechat-login">
			<image src="../../static/czzn-img/login/wechat.png" class="wechat-logo" @click="wechatLogin" />
		</view>
		<!-- #endif -->

		<!-- #ifdef APP-PLUS||H5-->
		<!-- <view class="divider">
			<u-divider text="服务" textSize="12"></u-divider>
		</view>
		<view class="app-login">
			<image src="/subpages/static/czzn-img/state/server.png" class="app-logo" @click="server" />
			<text @click="server">{{ $t('login.server') }}</text>
		</view> -->
		<!-- #endif -->

	</view>
</template>

<script>
	import {
		publicUrl
	} from '../../utils/config'
	import {
		userLogin,
		phoneLogin,
		getTelCode,
		getTenantByUsername,
		getUrlByName,
		getUrlByCode,
		bindNameCode,
	} from "../../api/login"
	import {
		getUserInfo
	} from "../../api/user"
	import {
		encryption,
		getTenantCacheList
	} from '../../utils/util'
	import {
		mapMutations
	} from 'vuex';
	import {changeUrl} from '../../utils/config'
	export default {
		data() {
			return {
				time: 0,
				timer: undefined,
				isGetCode: false,
				loginType: 1,
				agree: [1],
				option: [{
					text: '',
					value: 1,
				}],
				currentLanguage: '',
				canLogin: false,
				needCode:false,
				loginForm: {
					username: "",
					password: "",
					code: "",
					randomStr: "blockPuzzle",
				},
				noRegisterUserName: "", //未注册的
				phoneLoginForm: {
					mobile: "",
					code: "",
				},
				serverForm: {
					type: "2",
					ip: "http://5.63.101.254:3789",
					// ip:"http://localhost:9999",
				},
				uzbk:"O'zbekcha",
			}
		},
		onLoad(options) {
			if (uni.getStorageSync('CURRENT_LANG') == "en") {
				this.currentLanguage = 'English';
			} else if (uni.getStorageSync('CURRENT_LANG') == "pt") {
				this.currentLanguage = 'Português';
			} else if (uni.getStorageSync('CURRENT_LANG') == "uz") {
				this.currentLanguage = "O'zbekcha";
			} else if (uni.getStorageSync('CURRENT_LANG') == "ru") {
				this.currentLanguage = "Russian";
			}else {
				this.currentLanguage = '简体中文';
			}
			var server = uni.getStorageSync('server');
			this.defServer()
			console.log("当前服务器信息、", server);
			if (options.username) {
				this.loginForm.username = options.username
				this.phoneLoginForm.mobile = options.username
				this.getTenantUsername()
			}

		},
		methods: {
			...mapMutations({
				setUserInfo: 'user/login'
			}),
			//切换语言
			changeLanguage() {
				console.log('语言切换')
				uni.showActionSheet({
					itemList: ["English", "简体中文", "Português","O'zbekcha",'Russian'],
					success: res => {
						let language = uni.getStorageSync('CURRENT_LANG')
						console.log(res.tapIndex,language);
						if ((res.tapIndex === 0 && language != 'en') || (res.tapIndex === 1 && language !=
								'zh-Hans') || (res.tapIndex === 2 && language != 'pt') || (res.tapIndex === 3 && language != 'uz') || (res.tapIndex === 4 && language != 'ru')) {
							const globalData = getApp().globalData
							console.log(globalData, '--------------');
							console.log(language);
							if (res.tapIndex === 0) {
								language = globalData.locale = 'en'
							} else if (res.tapIndex === 1) {
								language = globalData.locale = 'zh-Hans'
							} else if (res.tapIndex === 2) {
								language = globalData.locale = 'pt'
							} else if (res.tapIndex === 3) {
								language = globalData.locale = 'uz'
							}else if (res.tapIndex === 4) {
								language = globalData.locale = 'ru'
							}
							uni.setStorageSync('CURRENT_LANG', language)
							getApp().globalData.$i18n.locale = language
							if (res.tapIndex === 0) {
								this.currentLanguage = 'English'
							} else if (res.tapIndex === 1) {
								this.currentLanguage = '简体中文'
							} else if (res.tapIndex === 2) {
								this.currentLanguage = 'Português'
							} else if (res.tapIndex === 3) {
								this.currentLanguage = "O'zbekcha"
							}else if (res.tapIndex === 4) {
								this.currentLanguage = "Russian"
							}
							if (uni.setLocale) {
								uni.setLocale(language)
							}
							uni.reLaunch({
								url: '/pages/login/login',
								complete: () => {
									uni.$emit("changeLanguage", language)
								}
							})
						}
					},
					fail: () => {},
					complete: () => {}
				});
			},

			//绑定微信
			bindWechat() {
				// #ifdef MP-WEIXIN
				console.log("当前是微信");
				wx.login({
					success(result) {
						wx.request({
							url: publicUrl + '/admin/social/bind?state=E_MINI&code=' + result.code,
							method: 'post',
							header: {
								'Authorization': 'Bearer ' + uni.getStorageSync('token')
							},
							success(r) {
								console.log(r)
								if (r.statusCode == 200) {
									wx.showToast({
										title: '绑定成功',
										icon: "none",
										duration: 1000,
									})
								} else if (r.statusCode != 200 && r.data.error) {
									uni.showToast({
										title: r.data.error,
										icon: 'none',
										duration: 2000
									})
									uni.navigateTo({
										url: '/pages/login/chooserole'
									})
								} else if (r.statusCode != 200 && r.data.msg) {
									uni.showToast({
										title: r.data.msg,
										icon: 'none',
										duration: 2000
									})
								}
							}
						})
					}
				})
				// #endif
				// #ifndef MP-WEIXIN
				console.log("当前不是微信");
				// #endif
			},

			//获取验证码
			getCode() {
				let phone = /^1[3-9]\d{9}$/
				if (this.phoneLoginForm.mobile == '') {
					uni.showToast({
						title: this.$t('login.phonePlaceholder'),
						icon: "none",
						duration: 2500,
					})
				} else{
					getTelCode(this.phoneLoginForm.mobile).then(res => {
						if (res.statusCode === 200) {
							this.isGetCode = true
							this.time = 60
							this.timer = setInterval(() => {
								this.time--
								if (this.time == 0) {
									clearInterval(this.timer)
								}
							}, 1000)
						}
					})
				}
			},
			//切换登录方式
			changeLoginType() {
				if (this.loginType == 1) {
					this.loginType = 0
				} else if (this.loginType == 0) {
					this.loginType = 1
				}
			},
			//去注册
			toRegister() {
				uni.navigateTo({
					url: '/pages/login/chooserole'
				})
			},
			//去重置密码
			toReset() {
				uni.showModal({
						content: this.$t('login.conenct'),
						showCancel: false,
					})
				// uni.navigateTo({
				// 	url: '/pages/login/forgot'
				// })
			},
			//手机验证码登录
			onPhoneLogin() {
				if (this.phoneLoginForm.mobile == '') {
					uni.showToast({
						title: this.$t('login.phonePlaceholder'),
						icon: "none",
						duration: 2500,
					})
				} else if (this.phoneLoginForm.code == '') {
					uni.showToast({
						title: this.$t('login.verifyCodePlaceholder'),
						icon: "none",
						duration: 2500,
					})
				} else {
					let param = {
						mobile: 'SMS@' + this.phoneLoginForm.mobile + '@' + this.phoneLoginForm.code,
						grant_type: 'mobile'
					};
					phoneLogin(param).then(res => {
						if (res.statusCode === 200) {
							uni.setStorageSync('userId', res.data.user_info.id)
							uni.setStorageSync('userName', this.loginForm.username)
							uni.setStorageSync('token', res.data.access_token)
							this.onGetUserInfo(true)
							uni.switchTab({
								url: "/pages/home/home"
							})
							uni.showToast({
								title: this.$t('login.success'),
								icon: "none",
								duration: 2500,
							})
						}
					})
				}
			},
			//账号登录
			onAccountLogin() {
				console.log("登录信息、", this.loginForm);
				if (this.noRegisterUserName == this.loginForm.username) {
					uni.showModal({
						content: this.$t('login.noRegister'),
						showCancel: false,
					})
					return
				}
				let serverPrefix = uni.getStorageSync("serverPrefix");
				if (serverPrefix == undefined || serverPrefix == "" || serverPrefix == null || serverPrefix == "null") {
					uni.showModal({
						content: "请选择一个服务器",
						showCancel: false,
					})
					return
				}
				if (this.loginForm.username == '') {
					uni.showToast({
						title: this.$t('login.placeholder'),
						icon: "none",
						duration: 2500,
					})
				} else if (this.loginForm.password == '') {
					uni.showToast({
						title: this.$t('login.passwordPlaceholder'),
						icon: "none",
						duration: 2500,
					})
				} else {
					const userInfo = encryption({
						data: {
							username: this.loginForm.username,
							password: this.loginForm.password,
							delFlag: '0',
							source: 'mini'
						},
						key: 'pigxpigxpigxpigx',
						param: ['password'],
						source: 'mini'
					})
					userLogin(userInfo).then(res => {
						if (res.statusCode === 200) {
							var userId = res.data.user_id
							if (!userId) {
								userId = res.data.user_info.id
							}
							uni.setStorageSync('userId', userId)
							uni.setStorageSync('userName', this.loginForm.username)
							uni.setStorageSync('token', res.data.access_token)
							this.onGetUserInfo(true)
						}
					})
				}
			},
			//获取用户详情
			onGetUserInfo(isBindWebChart) {
				getUserInfo().then(res => {
					if (res.statusCode == 200 && res.data.code == 0) {
						console.log(res);
						var userType = res.data.data.sysUser.type;
						uni.setStorageSync('userInfo', res.data.data.sysUser)
						uni.setStorageSync('tenantInfo', res.data.data.tenantList)
						uni.setStorageSync('userType', userType)
						uni.setStorageSync('isAuditUser', false)
						uni.setStorageSync('isEnterpriseUser', userType == "5" ? true : false)
						uni.setStorageSync('isDealerUser', userType == "3" ? true : false)
						uni.setStorageSync('isDriverUser', userType == "4" ? true : false)
						uni.setStorageSync('isTransUser', userType == "7" ? true : false)
						var tenantList = getTenantCacheList();
						//默认第一个租户
						uni.setStorageSync("currentTenantId", tenantList[0]);
						//AUDIT_USER 移动端审核角色
						//DEALER_USER 客商角色
						//DRIVER_USER 移动端司机
						// if (res.data.data.roleCodes) {
						// 	uni.setStorageSync('userRoleCode', res.data.data.roleCodes)
						// 	if (res.data.data.roleCodes.includes("DEALER_USER")) {
						// 		uni.setStorageSync('isDealerUser', true)
						// 		uni.setStorageSync('isAuditUser', false)
						// 		uni.setStorageSync('isDeliverUser', false)
						// 	}
						// 	if (res.data.data.roleCodes.includes("DRIVER_USER")) {
						// 		uni.setStorageSync('isDriverUser', true)
						// 		uni.setStorageSync('isAuditUser', false)
						// 		uni.setStorageSync('isDeliverUser', false)
						// 	}
						// 	if (res.data.data.roleCodes.includes("AUDIT_USER")) {
						// 		uni.setStorageSync('isAuditUser', true)
						// 		uni.setStorageSync('isDealerUser', false)
						// 		uni.setStorageSync('isDriverUser', false)
						// 	}
						// }
						this.setUserInfo(res.data.data.sysUser)
						if (isBindWebChart == true) {
							// this.bindWechat() //自动绑定微信
						}
						console.log("当前登录账户类型、", res.data.data.sysUser.type);
						if (uni.getStorageSync('isAuditUser')) {
							getApp().globalData.tabIndex = 'approval'
							if (uni.getStorageSync("serverStatus") == 1) {
								uni.switchTab({
									url: "/pages/approval/approvallist"
								})
							} else {
								uni.navigateTo({
									url: "/pages/login/chooseEnterp"
								})
							}
						} else {
							getApp().globalData.tabIndex = 'home'
							uni.switchTab({
								url: "/pages/home/home"
							})
						}
						uni.showToast({
							title: this.$t('login.success'),
							icon: "none",
							duration: 2500,
						})
					} else if (res.statusCode != 200 || res.data.code === 1) {
						uni.showToast({
							title: res.data.error || res.data.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			}, //微信登录
			wechatLogin() {
				let that = this;
				wx.login({
					success(res) {
						wx.request({
							url: publicUrl + '/auth/mobile/token/social?grant_type=mobil&mobile=E_MINI@' +
								res.code + '&code=' + res.code,
							method: 'post',
							header: {
								Authorization: 'Basic cGlnOnBpZw==',
							},
							success(res) {
								console.log(res);
								if (res.statusCode === 401) {
									wx.showModal({
										content: '用户未绑定微信,请先登录并绑定账号',
										showCancel: true,
										success: function(res) {
											if (res.confirm) {
												uni.removeStorageSync('token')
												uni.removeStorageSync('tenantId')
												uni.removeStorageSync('userId')
												uni.removeStorageSync('userName')
												uni.removeStorageSync('userInfo')
												uni.removeStorageSync('userType')
												uni.removeStorageSync('serverAddress');
												uni.removeStorageSync('serverPrefix');
												uni.removeStorageSync('tenantInfo')
												uni.reLaunch({
													url: "/pages/login/login"
												})
												console.log('用户点击确定');
											} else if (res.cancel) {
												console.log('用户点击取消');
											}
										}
									})
								} else if (res.statusCode === 200) {
									console.log("微信登录返回、", res);
									uni.setStorageSync('userId', res.data.user_info.id)
									uni.setStorageSync('userName', res.data.user_info.username)
									uni.setStorageSync('token', res.data.access_token)
									that.onGetUserInfo(false)
								} else if (res.statusCode != 200 || res.data.code === 1) {
									uni.showToast({
										title: res.data.error || res.data.msg,
										icon: 'none',
										duration: 2000
									})
								}
							},
						});
					},
				});
			},
			//选择服务器
			server() {
				uni.navigateTo({
					url: '/pages/login/server'
				})
			},
			defServer() {
				// #ifdef MP-WEIXIN
				var tenantVersion = uni.getStorageSync('tenantVersion');
				if (tenantVersion != 3) {
					uni.setStorageSync('serverStatus', 2);
					uni.setStorageSync('serverAddress', this.serverForm.ip);
					uni.setStorageSync('server', this.serverForm);
					uni.setStorageSync('serverPrefix', "/ymt");
				}
				// #endif
			},
			//获取租户
			getTenantUsername() {
				// let serverPrefix = uni.getStorageSync("serverPrefix");
				// if (serverPrefix == undefined || serverPrefix == "" || serverPrefix == null || serverPrefix == "null") {
				// 	uni.showModal({
				// 		content: "请选择一个服务器",
				// 		showCancel: false,
				// 	})
				// 	return
				// }
				if (
					!this.loginForm.username.length ||
					this.loginForm.username.length == 0
				) {
					return false;
				}
				getTenantByUsername(this.loginForm.username).then(response => {
					let tenantList = response.data.data ? response.data.data : [];
					if (tenantList.length != 0) {
						this.noRegisterUserName = ""
						uni.setStorageSync('tenantId', tenantList[0].id);
						if (tenantList[0].cloudAddress) {
							// #ifdef MP-WEIXIN
							this.serverForm.ip = tenantList[0].cloudAddress;
							uni.setStorageSync('tenantVersion', 3);
							uni.setStorageSync('serverStatus', 2);
							uni.setStorageSync('serverAddress', this.serverForm.ip);
							uni.setStorageSync('server', this.serverForm);
							uni.setStorageSync('serverPrefix', "/admin");
							// #endif
						}
							this.canLogin = true
					} else {
						this.noRegisterUserName = this.loginForm.username
						uni.showModal({
							content: this.$t('login.noRegister'), //未注册用户
							icon: 'none',
							showCancel: false,
						});
						this.canLogin = false
					}
				});
			},
			//获取Url
			getUrl(){
				let that = this
				if (this.loginForm.username == '') {
					uni.showToast({
						title: this.$t('login.placeholder'),
						icon: "none",
						duration: 2500,
					})
				} else if (this.loginForm.code == '') {
					uni.showToast({
						title: this.$t('login.codePlaceholder'),
						icon: "none",
						duration: 2500,
					})
				} else {
					let data = {
						username: this.loginForm.username,
						companyCode: this.loginForm.code
					}
					bindNameCode(data).then(res=>{
						if (res.statusCode === 200 && res.data.data.code === 0) {
							getUrlByCode(this.loginForm.code).then(r=>{
								if (res.statusCode === 200 && r.data.code === 0) {
									let data = r.data.data
									uni.setStorageSync('serverAddress', data.requestUrl);
									uni.setStorageSync('serverPrefix', data.methodPrefix);
									changeUrl()
									that.getTenantUsername()
								}else{
									uni.showToast({
										title: r.data.msg,
										icon: "none",
										duration: 2500,
									})
								}
							})
						}else{
							this.canLogin = false
							uni.showToast({
								title: res.data.data.msg,
								icon: "none",
								duration: 2500,
							})
						}
					})
				}
			},
			//用户名获取url
			getNameUrl(){
				if (this.loginForm.username == '') {
					uni.showToast({
						title: this.$t('login.placeholder'),
						icon: "none",
						duration: 2500,
					})
				}else{
					getUrlByName(this.loginForm.username).then(res=>{
						console.log('1111111111122222222222222',res);
						if (res.statusCode === 200 && res.data.code === 0) {
							let data = res.data.data
							if(data){
								uni.setStorageSync('serverAddress', data.requestUrl);
								uni.setStorageSync('serverPrefix', data.methodPrefix);
								this.needCode = false
								this.getTenantUsername()
							}else{
								uni.showToast({
									title: res.data.msg,
									icon: "none",
									duration: 2500,
								})
								this.canLogin = false
								this.needCode = true
							}
						}else{
							uni.showToast({
								title: res.data.msg,
								icon: "none",
								duration: 2500,
							})
						}
					})
				}
			}
			
		}
	}
</script>
<style>
	/* #ifndef APP-NVUE */
	view {
		display: flex;
		box-sizing: border-box;
		flex-direction: column;
	}

	page {
		box-sizing: border-box;
		padding: 0 48rpx 80rpx;
		height: 100%;
	}

	/* #endif*/
</style>
<style lang="scss" scoped>
	@import '../../common/css/login.scss';
</style>