<template>
	<view>
		<!-- 状态栏 -->
		<uni-status-bar></uni-status-bar>
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<!-- 欢迎语 -->
		<view class="w-100 flex-column box-sizing font-weight" style="height: 450rpx;padding:135rpx 60rpx;">
			<view class="font-lgr">您好，</view>
			<view class="font-lgr">欢迎来到掌柜科技</view>
		</view>
		<!-- 登录区域Start -->
		<view class="mx-3">
			<!-- 账号密码登录 false代表账号密码登录 -->
			<template v-if="!status">
				<view class="mt-1 border-bottom">
					<input type="text" v-model="username" class="uni-input common-input" maxlength="17"
						placeholder="请输入会员号" />
				</view>
				<view class="mt-2 position-relative border-bottom">
					<input type="text" :password="isHidePassword" v-model="password" class="uni-input common-input"
						placeholder="请输入密码" style="padding-right: 200rpx;" maxlength="15" />
					<view class=" position-absolute top-0 right-0 d-flex a-center j-center"
						style="width: 200rpx;height: 100%;">
						<view style="font-size: 40rpx;" class="icon iconfont"
							:class="isHidePassword?'icon-buxianshimima':'icon-xianshimima'"
							@tap="isHidePassword = !isHidePassword"></view>
					</view>
				</view>
				<view class="mt-2 position-relative border-bottom">
					<input type="text" v-model="imgcode" class="uni-input common-input" maxlength="5"
						placeholder="请输入验证码" style="padding-right: 200rpx;" />
					<image style="height: 80%;padding-top: 4rpx;width: 200rpx;" mode="aspectFill"
						class="position-absolute top-0 right-0 d-flex a-center j-center text-light-muted"
						:src="imgcodesrc" @tap="refreshCaptcha"></image>
				</view>
			</template>
			<!-- 手机验证码登录 true代表手机验证码登录 -->
			<template v-else>
				<view class="mt-1 position-relative border-bottom">
					<view class="position-absolute d-flex a-center j-center left-0 top-0 font-weight"
						style="width: 100rpx;height: 100%;">+86</view>
					<input type="text" v-model="phone" class="uni-input common-input" style="padding-left: 100rpx;"
						placeholder="手机号" />
				</view>
				<view class="mt-2 position-relative border-bottom">
					<input type="text" v-model="checknum" class="uni-input common-input" maxlength="4"
						style="padding-right: 240rpx;" placeholder="请输入验证码" />
					<view class="position-absolute top-0 right-0 d-flex a-center j-center text-light-muted"
						style="width: 240rpx;height: 100%;" @tap="getCheckNum">
						<view class="d-flex a-center j-center "
							:class="!codetime?'yanzhengmaView1 main-text-color':'yanzhengmaView2'">
							{{!codetime?'获取验证码':codetime+' S'+'后重新获取'}}
						</view>
					</view>
				</view>
			</template>
			<button class="my-3 mt-4 d-flex a-center j-center font-weight main-bg-color" :loading="loading"
				:class="{'main-bf-hover-color':disabled}" type="primary" @tap="submit" :disabled="disabled"
				style="letter-spacing: 20rpx;">登录</button>
			<!-- 登录状态切换 -->
			<view class="pt-1 px-3 pb-0 text-light-muted d-flex j-sb">
				<view @tap="changeStatus">
					{{status?'密码登录':'验证码登录'}}
				</view>
				<!-- <view>
					<view @tap="navigate({url:'/pages/register/register'})">用户注册</view>
				</view> -->
			</view>
			<view class="third_party_login_box">
				<view class="third_party_title"><text>第三方登录</text></view>
				<view class="third_party_content flex-wrap">
					<image src="/static/icon/weixin.png" @click=" onWxAppLogin" mode="aspectFit"></image>
					<!-- <image src="/static/icon/zhifubao.png" mode="aspectFit"></image> -->
				</view>
			</view>
			<view class="position-fixed left-0 right-0 d-flex a-center j-center pt-2 text-light-muted"
				style="bottom:30rpx">
				登录/<span>注册</span>表示您已同意<view> <text @tap="nav('/pages/login/xieyi')"
						class="main-text-color">平台协议</text>及<text class="main-text-color"
						@tap="nav('/pages/login/mimi')">隐私协议</text>政策</view>
			</view>
		</view>
		<u-popup v-model="show" border-radius="14" mode="center" width="70%">
			<view class="shu1 shili">
				<text>温馨提示</text>
				<text>是否更新账号密码？</text>
			</view>
			<view class="heng shili_btn">
				<view class="heng1" @click="fanhui">取消</view>
				<view class="heng1" @click="zhifu" style="background-color: orangered;">确认</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import md5 from '@/plugins/md5';
	let clear;
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import socket from '@/config/socket';
	import DB from "@/common/sqlite";
	export default {
		data() {
			return {
				show: false,
				contentSlot: true,
				defaultid: '', //登录默认会员号
				status: false, //false代表账号密码登录，true代表手机验证码登录
				disabled: true, //登录按钮是否可用
				loading: false, //是否显示按钮加载状态
				username: "", //登录用户名
				password: "", //登录密码
				imgcode: "", //图片验证码0
				imgcodesrc: "", //验证码图片
				isHidePassword: true, //是否隐藏密码
				phone: "", //登录手机号
				checknum: "", //登录验证码
				codetime: 0, //验证码获取倒计时
				code: "", //用户code
				listData: [],
			};
		},
		//第一次加载
		onLoad(e) {
			 // #ifdef APP-PLUS
			this.openSQL();
			this.selectTableData();
			// #endif
			this.username = this.defaultid;
		},
		//页面显示   

		onShow() {
			uni.getClipboardData({
				success: (res) => {
					let id = (res.data.replace(/(^\s*)|(\s*$)/g, "")).toUpperCase();
					if ((id.length == 17) && (id.indexOf('99') == 0) && (id.indexOf('D') > 0) && (id.indexOf(
							'M') > 0) && (id !== this.username)) {
						uni.showModal({
							content: '是否自动填充会员号',
							cancelText: '否',
							confirmText: '是',
							success: (res1) => {
								if (res1.confirm) {
									this.username = id;
								}
							}
						});
					}
				}
			})
		},
		watch: {
			username(val) {
				this.username = this.username.toUpperCase();
				this.OnBtnChange();
			},
			password(val) {
				this.OnBtnChange();
			},
			imgcode(val) {
				this.OnBtnChange();
			},
			phone(val) {
				this.OnBtnChange();
			},
			checknum(val) {
				this.OnBtnChange();
			}
		},
		onShow() {
			this.refreshCaptcha();
			uni.getClipboardData({
				success: (res) => {
					let id = (res.data.replace(/(^\s*)|(\s*$)/g, "")).toUpperCase();
					if ((id.length == 17) && (id.indexOf('99') == 0) && (id.indexOf('D') > 0) && (id.indexOf(
							'M') > 0) && (id !== this.username)) {
						uni.showModal({
							content: '是否自动填充会员号',
							cancelText: '否',
							confirmText: '是',
							success: (res1) => {
								if (res1.confirm) {
									this.username = id;
								}
							}
						});
					}

				}
			})
		},
		onUnload() {
			this.closeSQL();
		},
		computed: {
			...mapState(["userLoginId"])

		},
		//方法
		methods: {
			...mapMutations(['setUserInfo']),
			// 跳转页面
			nav(url) {
				uni.navigateTo({
					url: url
				});
			},

			// 图片验证码
			refreshCaptcha() {
				this.imgcodesrc = this.$base.baseUrl + '/captcha.jpg?t=' + new Date().getTime();
			},
			// 切换登录状态
			changeStatus() {
				uni.hideKeyboard();
				this.initInput();
				this.username = this.defaultid;
				this.status = !this.status;
				this.refreshCaptcha();
			},
			// 初始化表单
			initInput() {
				this.username = '';
				this.password = '';
				this.phone = '';
				this.checknum = '';
				this.imgcode = "";
			},
			// 改变按钮状态
			OnBtnChange() {
				if ((this.username && this.password && this.imgcode) || (this.phone && this.checknum)) {
					this.disabled = false;
					return;
				}
				this.disabled = true;
			},
			// 获取验证码
			async getCheckNum() {
				uni.hideKeyboard();
				if (this.codetime > 0) return;
				// 验证手机号合法性
				if (!this.phone) {
					return uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
				}
				if (!this.$base.phoneRegular.test(this.phone)) {
					return uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					});
				}
				// 请求服务器，发送验证码
				let res = await this.$http.get('/sendMsg', {
					phone: this.phone,
					type: "0"
				});
				// 请求失败处理
				if (res.code != 200) {
					return uni.showToast({
						title: res.data.msg,
						icon: "none"
					});
				} else {
					uni.showToast({
						title: "发送成功",
						icon: "none"
					});
				}
				// 发送成功，开启倒计时
				this.codetime = 60;
				let timer = setInterval(() => {
					this.codetime--;
					if (this.codetime < 1) {
						clearInterval(timer);
						this.codetime = 0;
					}
				}, 1000);
			},
			async getCheckNum1() {
				uni.hideKeyboard();
				if (this.codetime > 0) return;
				// 验证手机号合法性
				if (!this.phone) {
					return uni.showToast({
						title: '请输入手机号',
						icon: 'none'
					});
				}
				if (!this.$base.phoneRegular.test(this.phone)) {
					return uni.showToast({
						title: '请输入正确的手机号码',
						icon: 'none'
					});
				}
				// 请求服务器，发送验证码
				let res = await this.$http.get('/sendMsg', {
					phone: this.phone,
					type: "0"
				});
				// 请求失败处理
				if (res.code != 200) {
					return uni.showToast({
						title: res.data.msg,
						icon: "none"
					});
				} else {
					uni.showToast({
						title: "发送成功",
						icon: "none"
					});
				}
				// 发送成功，开启倒计时
				this.codetime = 60;
				let timer = setInterval(() => {
					this.codetime--;
					if (this.codetime < 1) {
						clearInterval(timer);
						this.codetime = 0;
					}
				}, 1000);
			},
			//#ifdef APP-PLUS
			//确认离开
			fanhui() {
				this.show = false;
				this.$login({
					url: "/login",
					data: {
						account: this.username,
						password: this.password,
						captcha: this.imgcode.toLowerCase()
					}
				}).then(res => {
					socket.init();
					return;
				})
			},
			//立即支付
			zhifu() {
				this.show = false;
				this.updateTableData();
				this.$login({
					url: "/login",
					data: {
						account: this.username,
						password: this.password,
						captcha: this.imgcode.toLowerCase()
					}
				}).then(res => {
					socket.init();
					return;
				})
			},
			//#endif
			// 提交登录
			submit() {
				// // 账号密码登录
				uni.hideKeyboard();
				if (!this.status) {
					//#ifdef H5
					if (this.username == 'ADMIN') {
						return uni.showToast({
							title: '无效账号',
							icon: "none"
						});
					} else {
						this.$login({
							url: "/login",
							data: {
								account: this.username,
								password: this.password,
								captcha: this.imgcode.toLowerCase()
							}
						}).then(res => {
							socket.init();
							return;
						})
					}
					//#endif
					//#ifdef APP-PLUS
					if (this.listData.length > 0) {
						console.log(this.status)
						this.listData.map(ele => {
							if (this.username != ele.username || this.password != ele.password) {
								this.show = true;
							} else {
								this.$login({
									url: "/login",
									data: {
										account: this.username,
										password: this.password,
										captcha: this.imgcode.toLowerCase()
									}
								}).then(res => {
									socket.init();
									return;
								})
							}
						})
					} else {
						this.$login({
							url: "/login",
							data: {
								account: this.username,
								password: this.password,
								captcha: this.imgcode.toLowerCase()
							}
						}).then(res => {
							this.openSQL(); //打开数据库
							this.createTable(); //创建表
							this.insertTableData(this.username, this.password); //新增表数据
							socket.init();
							return;
						})
					}
					//#endif
				} else {
					// 验证码登录
					// 验证手机号合法性
					if (!this.$base.phoneRegular.test(this.phone)) {
						return uni.showToast({
							title: '请输入正确的手机号码',
							icon: 'none'
						});
					}
					this.$login({
						url: "/loginByPhone?phone=" + this.phone + "&phoneMsg=" + this.checknum,
					}).then(res => {

						// socket.init();
						return;
					})
				}
			},
			// 微信APP登录
			onWxAppLogin() {
				var that = this;
				uni.login({
					provider: 'weixin',
					scopes: "auth_user",
					onlyAuthorize: true,
					success: function(loginRes) {
						that.codeRes(loginRes);
					}
				});
			},
			async codeRes(data) {
				this.$login({
					url: "/wechat/login",
					data: {
						code: data.code,
					}
				}).then(res => {
					socket.init();
					return;
				})

			},

			// 打开数据库
			openSQL() {
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				console.log("数据库状态", open ? "开启" : "关闭");
				// if (!open) {
				DB.openSqlite()
					.then(res => {})
					.catch(error => {
						console.log(error)
					});
				// }
			},
			// 关闭数据库
			closeSQL() {
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				if (open) {
					DB.closeSqlite()
						.then(res => {
							// this.showToast("数据库已关闭");
						})
						.catch(error => {
							// this.showToast("数据库关闭失败");
						});
				}
			},
			// 创建表
			createTable() {
				let open = DB.isOpen();
				if (open) {
					this.openSQL();
					let sql =
						'"id" INTEGER PRIMARY KEY AUTOINCREMENT,"username" text,"password" text,"defaultid" text,"time" text';
					// 创建表 DB.createTable(表名, 表的列)
					DB.createTable("chat", sql)
						.then(res => {
							// this.showToast("创建chat表成功");
						})
						.catch(error => {});
				} else {}
			},

			// 新增表数据
			insertTableData(user, word) {
				let open = DB.isOpen();
				if (open) {
					let arr = [{
						username: user,
						password: word,
						defaultid: user,
					}]
					arr.map(item => {
						let time = this.formatDate(new Date().getTime());
						let sql = `'${item.username}','${item.password}','${item.defaultid}','${time}'`;
						let condition = "'username','password','defaultid','time'";
						// 新增 DB.insertTableData(表名, 对应表头列的数据)
						DB.insertTableData("chat", sql, condition)
							.then(res => {
								this.selectTableData();
							})
							.catch(error => {});
					})
				} else {}
			},

			// 查询表数据
			selectTableData() {
				let open = DB.isOpen();
				console.log(open)
				if (open) {
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					DB.selectTableData("chat")
						.then(res => {
							console.log("contact表数据", res);
							this.listData = res;
							this.username = res[0].username;
							this.defaultid = res[0].defaultid;
							this.password = res[0].password;
						})
						.catch(error => {});
				} else {}
			},

			// 修改表数据
			updateTableData() {
				let open = DB.isOpen();
				if (open) {
					let time = this.formatDate(new Date().getTime());
					let data = `username ='${this.username}',password ='${this.password}',defaultid='${this.username}'`;
					// 修改表数据 DB.updateTableData(表名, 要修改的列名=修改后列值, 修改条件的列名, 修改条件的列值)
					DB.updateTableData("chat", data)
						.then(res => {
							console.log(res)
							this.showToast("保存成功");
							this.selectTableData();
						})
						.catch(error => {
							console.log(error)
						});
				} else {}
			},

			// 删除表数据
			deleteTableData() {
				let open = DB.isOpen();
				if (open) {
					// 删除表 DB.deleteTableData(表名,查询条件列名,查询条件列值)
					DB.deleteTableData("chat")
						.then(res => {
							this.selectTableData();
						})
						.catch(error => {});
				} else {}
			},
			// 提示框
			showToast: function(str) {
				uni.showToast({
					icon: "none",
					title: str,
					mask: true
				});
			},

			// 时间戳转年月日
			formatDate(data) {
				let now = new Date(data);
				var year = now.getFullYear(); //取得4位数的年份
				var month =
					now.getMonth() + 1 < 10 ?
					"0" + (now.getMonth() + 1) :
					now.getMonth() + 1;
				var date = now.getDate() < 10 ? "0" + now.getDate() : now.getDate();
				var hour = now.getHours() < 10 ? "0" + now.getHours() : now.getHours();
				var minute =
					now.getMinutes() < 10 ? "0" + now.getMinutes() : now.getMinutes();
				var second =
					now.getSeconds() < 10 ? "0" + now.getSeconds() : now.getSeconds();
				return (
					year +
					"-" +
					month +
					"-" +
					date +
					" " +
					hour +
					":" +
					minute +
					":" +
					second
				);
			}
		},
		//页面隐藏
		onHide() {},
		//页面卸载
		onUnload() {},
		//页面下来刷新
		onPullDownRefresh() {},
		//页面上拉触底
		onReachBottom() {},
	};
</script>
<style scoped>
	.shu1 {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		align-items: center;

	}

	.shili_btn {
		width: 100%;
		height: 90rpx;
		border-top: 2rpx solid #F2F2F2;
	}

	.shili_btn>view {
		width: 50%;
		height: 100%;
		background-color: #ffffff;
		cursor: pointer;
	}

	.shili_btn>view:nth-child(2) {
		color: #FFFFFF;
		background-color: #007BFF;
	}

	.shili>text:nth-child(1) {
		font-weight: bold;
	}

	.shili {
		padding: 40rpx;
		box-sizing: border-box;
	}

	.heng {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.heng1 {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	/* 第三方登录Start */
	.third_party_login_box {
		position: fixed;
		bottom: 100rpx;
		left: 0;
		right: 0;
		height: 170rpx;
		padding: 0 30rpx;
	}

	.third_party_login_box .third_party_title {
		display: flex;
		align-items: center;
	}

	.third_party_login_box .third_party_title:before,
	.third_party_login_box .third_party_title:after {
		content: "";
		flex: 1;
		height: 2rpx;
		background-color: #f5f5f5;
	}

	.third_party_login_box .third_party_title text {
		font-size: 24rpx;
		color: #999999;
		flex-shrink: 0;
		padding: 0 20rpx;
	}

	.third_party_login_box .third_party_content {
		height: 140rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.third_party_login_box .third_party_content image {
		margin: 0rpx 20rpx;
		width: 80rpx;
		height: 80rpx;
	}

	/* 第三方登录End */
	.yanzhengmaView1 {
		background: #FFFFFF;
		border-radius: 10rpx;
		width: 150rpx;
		padding: 5rpx 0;
	}

	.yanzhengmaView2 {
		background: #FFFFFF;
		border-radius: 10rpx;
		width: 220rpx;
		padding: 5rpx 0;
	}
</style>