<template>
	<view class="normal-login-container"
		style="background-image: url('https://jianyaoji.oss-cn-hangzhou.aliyuncs.com/jianyaoji/images/login/bg.png');background-size: 100% 100%;">
		<view class="logo-content align-center justify-center flex">
			<!--      <image style="width: 100rpx;height: 100rpx;" :src="globalConfig.appInfo.logo" mode="widthFix">-->
			<!--      </image>-->
			<text class="title">老药师云平台移动端登录</text>
		</view>
		<view style="position: fixed;top:1vw;left:1vh;font-size: 12px;color: white;">
			版本号:{{version}}
		</view>
		<view class="login-form-content">
			<view class="input-item flex align-center">
				<view class="iconfont icon-user icon"></view>
				<input v-model="loginForm.username" class="input" type="text" placeholder="请输入账号" maxlength="30" />
			</view>
			<view class="input-item flex align-center">
				<view class="iconfont icon-password icon"></view>
				<input v-model="loginForm.password" type="password" class="input" placeholder="请输入密码" maxlength="20" />
			</view>
			<view class="input-item flex align-center" style="width: 60%;margin: 0px;" v-if="captchaEnabled">
				<view class="iconfont icon-code icon"></view>
				<input v-model="loginForm.code" type="number" class="input" placeholder="请输入验证码" maxlength="4" />
				<view class="login-code">
					<image :src="codeUrl" @click="getCode" class="login-code-img"></image>
				</view>
			</view>
			<view class="action-btn">
				<button @click="handleLogin" class="login-btn cu-btn block bg-blue lg round">登 录</button>
			</view>
			<view class="action-btn">
				<button class="login-btn cu-btn block bg-blue lg round" open-type="getPhoneNumber"
					@getphonenumber="getPhoneNumber">注 册</button>
			</view>
		</view>

		<view class="xieyi text-center">
			<!--      <text class="text-grey1">登录即代表同意</text>-->
			<!--      <text @click="handleUserAgrement" class="text-blue">《用户协议》</text>-->
			<!--      <text @click="handlePrivacy" class="text-blue">《隐私协议》</text>-->
		</view>
		<u-modal title="客户注册信息" @cancel="closeDlg" confirmText="提交审核" :showCancelButton="true" @confirm="submitReg"
			:show="show">
			<view class="slot-content">
				<u--form labelPosition="left" :model="model1" ref="s">
					<u-form-item label="*客户名称：" prop="chooseUser.deptName" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="chooseUser.deptName" border="none"></u--input>
					</u-form-item>
					<u-form-item label="*联系人：" prop="chooseUser.leader" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="chooseUser.leader" border="none"></u--input>
					</u-form-item>

					<u-form-item label="手机号：" prop="chooseUser.phone" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="chooseUser.phone" border="none"></u--input>
					</u-form-item>

					<u-form-item label="*密码：" prop="chooseUser.password" borderBottom ref="item1" labelWidth="auto">
						<u--input v-if="show" v-model="chooseUser.password" border="none"></u--input>
					</u-form-item>
					<u-form-item label="登录账号：" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="chooseUser.phone" border="none" disabled></u--input>
					</u-form-item>
					<u-form-item label="*订单图片：" borderBottom ref="item1" labelWidth="auto">
						<u-upload :fileList="fileList" name="1" multiple :maxCount="1" :previewFullImage="true"
							:width="auto" :height="auto" @delete="deletePic" @afterRead="afterRead"></u-upload>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
		<u-modal title="注册记录" @cancel="closereg" confirmText="重新注册" :showCancelButton="true" @confirm="submitRegTo"
			:show="registersshow">
			<view class="slot-content">
				<u--form labelPosition="left" :model="model1" ref="s">
					<u-form-item label="客户名称：" prop="registers.deptName" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="registers.deptName" border="none" :disabled="true"></u--input>
					</u-form-item>
					<u-form-item label="联系人：" prop="registers.leader" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="registers.leader" border="none" :disabled="true"></u--input>
					</u-form-item>

					<u-form-item label="手机号：" prop="registers.phone" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="registers.phone" border="none" :disabled="true"></u--input>
					</u-form-item>

					<u-form-item label="密码：" prop="registers.password" borderBottom ref="item1" labelWidth="auto">
						<u--input v-if="registersshow" v-model="registers.password" border="none"
							:disabled="true"></u--input>
					</u-form-item>
					<u-form-item label="登录账号：" borderBottom ref="item1" labelWidth="auto">
						<u--input v-model="registers.phone" border="none" disabled :disabled="true"></u--input>
					</u-form-item>
					<u-form-item label="注册状态：" borderBottom ref="item1" labelWidth="auto">
						<!-- this.registers.status==1&&this.registers.delFlag==0 -->
						<view v-if="registers.status==0" style="color:#1a62ff;">审核中</view>
						<view v-if="registers.status==1&&registers.delFlag==0">审核完成,<text
								style="color: crimson;">未通过原因:</text><text>{{registers.remark}}</text></view>
					</u-form-item>
				</u--form>
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		getCodeImg,
		uploadRegister,
		getPhone,
		checkReg
	} from '@/api/login'
	import {
		getToken
	} from "@/utils/auth";
	import {
		checkStr
	} from "@/utils/validate";
	export default {
		data() {
			return {
				version: "",
				codeUrl: "",
				captchaEnabled: true,
				globalConfig: getApp().globalData.config,
				loginForm: {
					username: "",
					password: "",
					code: "",
					uuid: '',
				},
				show: false,
				chooseUser: {},
				fileList: [],
				registers: {},
				registersshow: false
			}
		},
		created() {
			this.show = false,
				this.getVersion();
			this.checkLogin();
		},
		methods: {
			getPhoneNumber(e) {
				console.log(e.detail.code) // 动态令牌
				// console.log(e.detail.code)  // 动态令牌
				//     console.log(e.detail.errMsg) // 回调信息（成功失败都会返回）
				//     console.log(e.detail.errno)  // 错误码（失败时返回）
				this.newUser(e.detail.code);
			},
			toRegister() {

			},
			submitReg() {
				//注册数据提交
				if (this.chooseUser.deptName === ""||this.chooseUser.deptName ==null) {
					this.$modal.msgError("请输入客户名")
				} else if (this.chooseUser.phone === ""||this.chooseUser.phone ==null) {
					this.$modal.msgError("请输入手机号")
				} else if (this.chooseUser.leader === ""||this.chooseUser.leader ==null) {
					this.$modal.msgError("请输入负责人")
				} else if(this.chooseUser.password === ""||this.chooseUser.password ==null) {
					this.$modal.msgError("请输入登录密码")
				}else if(this.fileList[0]===''||this.fileList[0]==null){
					this.$modal.msgError("请输上传订单图片")
				}else{
				uploadRegister({
					formdata: this.chooseUser,
					name: 'register',
					file: this.fileList[0].url
				}).then(res => {
					uni.showToast({
						title: '注册信息已提交',
						duration: 2000
					});
					this.show = false
				})
				}
			},
			deletePic(event) {
				this.fileList = []
			},
			async afterRead(file, lists, name) {
				//{"file":[{"size":542091,"type":"image","url":"http://tmp/MPgJgECRVMUFe49f23795545b0cd35400a9b70a9f918.jpg",
				//"thumb":"http://tmp/MPgJgECRVMUFe49f23795545b0cd35400a9b70a9f918.jpg"}],"name":"1","index":0}
				if (file.file[0].size > 2048 * 1000) {
					this.$modal.errMsg("图片大于2M")
				} else {
					this.fileList = file.file
				}
			},
			newUser(code) {
				let self = this
				uni.showLoading({
					title: '获取手机号...'
				});
				wx.login({
					success(res) {
						if (res.code) {
							let data = {
								loginCode: res.code,
								phoneCode: code
							}
							//获取到手机号
							getPhone(data).then(res => {
								//console.log("获取到手机号信息结果<>>" + JSON.stringify(res))
								if (checkStr(res.data.phone, 'mobile')) {
									//console.log("................" + res.data.phone)
									self.chooseUser.phone = res.data.phone
									self.chooseUser.openId = res.data.openId
									//通过手机号校验注册信息
									checkReg(res.data.phone).then(res => {
										//console.log("校验注册信息结果<>>" + JSON.stringify(res))
										if (res.data.code == 0) {
											//已注册待审核
											self.registers = res.data.res
											self.registersshow = true
										} else if (res.data.code == 1) {
											//已注册且通过审核,但是用户可能已被删除
											self.show = true;
										} else if (res.data.code == 2) {
											//未注册,进入注册页
											self.show = true;
										} else if(res.data.code==3){
											uni.showToast({
												title: '已存在客户信息',
												duration: 2000,
												icon:'none'
											});
										}else{
											//已注册未通过审核
											self.registers = res.data.res
											self.registersshow = true
										}
										uni.hideLoading();
									}).catch(res => {
										uni.showToast({
											title: '校验信息失败',
											duration: 2000,
											icon:'none'
										});
									})
								} else {
									uni.showToast({
										title: '手机号获取异常',
										duration: 2000,
										icon:'none'
									});
								}
								//self.show = true;
							}).catch(res => {
								uni.showToast({
									title: '获取手机号异常',
									duration: 2000,
									icon:'none'
								});
							})
						} else {
							console.log('获取code失败！' + res.errMsg)
						}
					}
				})
			},
			closereg() {
				this.registersshow = false
				this.registers = {}
			},
			submitRegTo() {
				//审核中
				if (this.registers.status == 0) {
					uni.showToast({
						title: '已在审核中...',
						duration: 1500,
						icon: 'loading'
					});
					this.registersshow = false
					this.show = false
					this.registers = {}
				} else if (this.registers.status == 1 && this.registers.delFlag == 0) {
					//审核完成且失败允许重新注册
					this.registersshow = false
					this.show = true
				}
			},
			closeDlg() {
				this.show = false;
				this.chooseUser = {};
			},
			checkLogin() {
				let token = getToken()
				if (token) {
					this.loginSuccess()
				} else {
					this.getCode()
				}
			},
			// 隐私协议
			handlePrivacy() {
				let site = this.globalConfig.appInfo.agreements[0]
				this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 用户协议
			handleUserAgrement() {
				let site = this.globalConfig.appInfo.agreements[1]
				this.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
			},
			// 获取图形验证码
			getCode() {
				getCodeImg().then(res => {
					this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled
					if (this.captchaEnabled) {
						this.codeUrl = 'data:image/gif;base64,' + res.img
						this.loginForm.uuid = res.uuid
					}
				})
			},
			getVersion() {
				let appBaseInfo = uni.getAppBaseInfo();
				let appVersionCode = appBaseInfo.appVersionCode;
				this.version = appVersionCode;
			},
			// 登录方法
			async handleLogin() {
				if (this.loginForm.username === "") {
					this.$modal.msgError("请输入您的账号")
				} else if (this.loginForm.password === "") {
					this.$modal.msgError("请输入您的密码")
				} else if (this.loginForm.code === "" && this.captchaEnabled) {
					this.$modal.msgError("请输入验证码")
				} else {
					this.$modal.loading("登录中，请耐心等待...")
					this.pwdLogin()
				}
			},
			// 密码登录
			async pwdLogin() {
				this.$store.dispatch('Login', this.loginForm).then(() => {
					this.$modal.closeLoading()
					this.loginSuccess()
				}).catch(() => {
					if (this.captchaEnabled) {
						this.getCode()
					}
				})
			},
			// 登录成功后，处理函数
			loginSuccess(result) {
				// 设置用户信息
				this.$store.dispatch('GetInfo').then(res => {
					this.$tab.reLaunch('/pages/work/index')
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #ffffff;
	}

	.normal-login-container {
		width: 100%;
		position: absolute;
		top: 0px;
		bottom: 0;
		left: 0;
		right: 0;

		.logo-content {
			width: 100%;
			font-size: 21px;
			text-align: center;
			padding-top: 15%;

			image {
				border-radius: 4px;
			}

			.title {
				margin-left: 10px;
				color: #FFFFFF;
				font-size: 56rpx;
			}
		}

		.login-form-content {
			text-align: center;
			margin: 20px auto;
			margin-top: 15%;
			width: 90%;
			background: white;
			border-radius: 30rpx;
			box-shadow: 0rpx 5rpx 27rpx 0rpx rgba(195, 195, 195, 2.4);
			padding: 10%;

			.input-item {
				margin: 20px auto;
				background-color: #f5f6f7;
				height: 45px;
				border-radius: 20px;

				.icon {
					font-size: 38rpx;
					margin-left: 10px;
					color: #999;
				}

				.input {
					width: 100%;
					font-size: 14px;
					line-height: 20px;
					text-align: left;
					padding-left: 15px;
					//background: rgb(224,236,255);
				}

			}

			.login-btn {
				margin-top: 40px;
				height: 45px;
			}

			.xieyi {
				color: #333;
				margin-top: 20px;
			}

			.login-code {
				height: 38px;
				float: right;

				.login-code-img {
					height: 38px;
					position: absolute;
					margin-left: 10px;
					width: 200rpx;
				}
			}
		}
	}
</style>