<template>
	<view>
		<!-- 状态栏 -->
		<!-- 公共组件-每个页面必须引入 -->
		<public-module></public-module>
		<app-update ref="app_update"></app-update>
		<!-- 欢迎语 -->
		<view class="dis j-end a-c">
			<image src="../../static/image/login/2.png" mode=""
				style="height: 280px;width: calc(100% - 16px);margin-top: 25%;">
			</image>
		</view>
		<view class="" style="margin-top: -120px;">
			<u-tabs :list="list" :is-scroll="true" :current="current" @change="change"
				style="background: transparent;margin-bottom: 30px;"></u-tabs>
			<!-- 登录区域Start -->
			<view class="mx-3">
				<!-- 账号密码登录 false代表账号密码登录 -->
				<template v-if="current==0">
					<view class="mt-2 position-relative border-bottom">
						<view class="position-absolute d-flex a-center j-center left-0 top-0 font-weight"
							style="height: 100%;">
							<image src="../../static/image/login/zhanghao.png" mode=""
								style="width: 18px;height: 18px;">
							</image>
						</view>
						<input type="text" v-model="username" class="uni-input common-input" maxlength="17"
							placeholder="请输入会员号" style="padding-left: 56rpx;background: transparent;" />
					</view>
					<view class="mt-2 position-relative border-bottom">
						<view class="position-absolute d-flex a-center j-center left-0 top-0 font-weight"
							style="height: 100%;">
							<image src="../../static/image/login/mima.png" mode="" style="width: 18px;height: 18px;">
							</image>
						</view>
						<input type="text" :password="isHidePassword" v-model="password" class="uni-input common-input"
							placeholder="请输入密码" style="padding-right: 200rpx;padding-left: 56rpx;" maxlength="15" />
						<view class=" position-absolute top-0 right-0 d-flex a-center j-center"
							style="width: 200rpx;height: 100%;">
							<image
								:src="isHidePassword?'../../static/image/login/biyan.png':'../../static/image/login/zhengyan.png'"
								@tap="isHidePassword = !isHidePassword" mode="" style="width: 18px;height: 18px;">
						</view>
					</view>
					<view class="mt-2 position-relative border-bottom">
						<view class="position-absolute d-flex a-center j-center left-0 top-0 font-weight"
							style="height: 100%;">
							<image src="../../static/image/login/yanzhengma.png" mode=""
								style="width: 18px;height: 18px;">
							</image>
						</view>
						<input type="text" v-model="imgcode" class="uni-input common-input" maxlength="5"
							placeholder="请输入验证码" style="padding-right: 200rpx;padding-left: 56rpx;" />
						<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-2 position-relative border-bottom">
						<view class="position-absolute d-flex a-center j-center left-0 top-0 font-weight"
							style="height: 100%;">
							<image src="../../static/image/login/shoujihao.png" mode=""
								style="width: 18px;height: 18px;">
							</image>
						</view>
						<input type="text" v-model="phone" class="uni-input common-input" style="padding-left: 56rpx;"
							placeholder="手机号" />
					</view>
					<view class="mt-2 position-relative border-bottom">
						<view class="position-absolute d-flex a-center j-center left-0 top-0 font-weight"
							style="height: 100%;">
							<image src="../../static/image/login/yanzhengma.png" mode=""
								style="width: 18px;height: 18px;">
							</image>
						</view>
						<input type="text" v-model="checknum" class="uni-input common-input" maxlength="4"
							style="padding-right:120px;padding-left: 56rpx;" 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 text-color':'yanzhengmaView2'">
								{{!codetime?'获取验证码':codetime+' S'+'后重新获取'}}
							</view>
						</view>
					</view>
				</template>
				<button class="my-3 mt-4 d-flex a-center j-center font-weight bg-color" :loading="loading"
					:class="{'bg-hover-color':disabled}" type="primary" @tap="submit" :disabled="disabled"
					style="letter-spacing: 20rpx;">登录</button>
				<view class=" left-0 right-0 dis a-c j-start  text-light-muted" style="bottom:30rpx">
					<u-checkbox v-model="checked"></u-checkbox>
					我已确认并同意<view> <text @tap="nav('/pages/login/xieyi')" class="text-color">平台协议</text>及<text
							class="text-color" @tap="nav('/pages/login/mimi')">隐私协议</text>政策</view>
				</view>
				<!-- #ifdef APP -->
				<view class="third_party_login_box">
					<view class="third_party_title"><text>第三方登录</text></view>
					<view class="third_party_content flex-wrap">
						<image src="../../static/image/login/wx.png" @click="onWxAppLogin" mode="aspectFit"></image>
						<image src="../../static/image/login/zf.png" @click="onzfbAppLogin" mode="aspectFit"></image>
					</view>
				</view>
				<!-- #endif -->
			</view>
		</view>

		<u-toast ref="uToast" />
		<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="quxiao">取消</view>
				<view class="heng1" @click="queren" style="background-color: orangered;">确认</view>
			</view>
		</u-popup>
	</view>
</template>
<script>
	import appUpdate from "@/components/yzhua006-update/app-update.vue"; //app更新组件
	import md5 from '@/plugins/md5';
	let clear;
	import {
		mapState,
		mapMutations
	} from 'vuex';
	import socket from '@/config/socket';
	import DB from "@/common/sqlite";
	export default {
		components: {
			appUpdate
		},
		data() {
			return {
				checked: false,
				list: [{
					name: '账号登录'
				}, {
					name: '短信登录'
				}],
				current: 0,
				isLoading: false,
				show: false,
				contentSlot: true,
				status: false, //false代表账号密码登录，true代表手机验证码登录
				disabled: true, //登录按钮是否可用
				loading: false, //是否显示按钮加载状态
				username: "", //登录用户名
				password: "", //登录密码
				imgcode: "", //图片验证码0
				imgcodesrc: "", //验证码图片
				isHidePassword: true, //是否隐藏密码
				phone: "", //登录手机号
				checknum: "", //登录验证码
				captchaId: "",
				codetime: 0, //验证码获取倒计时
				code: "", //用户code
				listData: [],
			};
		},
		onReady() {
			this.isLoading = true;
		},
		beforeCreate() {
			setTimeout(() => {
				this.$refs.app_update.update(); //调用子组件检查更新方法
				setTimeout(() => {
					if (this.$refs.app_update.popup_show == true && this.$refs.app_update.force == true) {}
				}, 100)
			}, 500)
		},
		//第一次加载
		async onLoad(e) {
			let pageRequest = {
				pageNum: 1,
				pageSize: 20,
				columnFilters: {
					apptype: {
						name: "apptype",
						value: "apk",
					}
				}
			};
			let getquote = await this.$http.post('/sysVersion/findPage', pageRequest);
			// #ifdef APP-PLUS
			this.openSQL();
			this.selectTableData();
			// this.deleteTableData();
			// #endif
		},

		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();
			}
		},
		mounted() {
			// //取出缓存中的账号、密码
			const HBusername = uni.getStorageSync('username');
			const HBpassword = uni.getStorageSync('password');
			// //有账号、密码就赋值给文本，没有就清空
			this.username = HBusername;
			this.password = HBpassword;
		},
		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;
								}
							}
						});
					}

				}
			})
			let args = plus.runtime.arguments;
			if (args) {

				plus.runtime.arguments = null; //进入之后就把urlscheme清空要不然下一次oushow时还会执行
				// 处理args参数，如直达到某新页面等
				//通过code请求获取user_id
				var authCode = args.split("=")[1];
				if (authCode != undefined && authCode != "" && authCode != null) {
					this.$login({
						url: "/alipay/login",
						data: {
							code: authCode,
						}
					}).then(res => {
						return uni.showToast({
							title: res.msg,
							icon: 'none'
						});
						socket.init();
						return;
					})
				}
			}

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

		},
		//方法
		methods: {
			...mapMutations(['setUserInfo']),

			// 跳转页面
			change(index) {
				this.current = index;
			},
			nav(url) {
				uni.navigateTo({
					url: url
				});
			},

			// 图片验证码
			refreshCaptcha() {
				let randnum = Math.floor(Math.random() * (1000000 - 1 + 1)) + 1
				this.imgcodesrc = this.$base.baseUrl + "/captchaById?t=" + new Date().getTime() +
					'&captchaId=' + randnum;
				this.captchaId = randnum;
			},
			// 切换登录状态
			changeStatus() {
				uni.hideKeyboard();
				this.initInput();
				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);
			},
			//#ifdef APP-PLUS
			quxiao() {
				this.show = false;
				this.$login({
					url: "/login2",
					data: {
						account: this.username,
						password: this.password,
						captcha: this.imgcode.toLowerCase(),
						captchaId: this.captchaId,
					}
				}).then(res => {
					if (res) {
						return uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					} else {
						socket.init();
					}

				})
			},
			queren() {
				this.show = false;
				this.$login({
					url: "/login2",
					data: {
						account: this.username,
						password: this.password,
						captcha: this.imgcode.toLowerCase(),
						captchaId: this.captchaId,
					}
				}).then(async res => {
					if (res) {
						return uni.showToast({
							title: res.msg,
							icon: 'none'
						});
					} else {
						this.deleteTableData();
						this.openSQL();
						this.createTable(); //创建表
						this.insertTableData(this.username, this.password); //新增表数据
						socket.init();
					}

				})
			},
			//#endif
			// 提交登录
			submit() {
				if (!this.checked) {
					return this.$refs.uToast.show({
						title: '请阅读后勾选并同意《平台协议》及《隐私协议》政策',
						type: 'default',
					})
				}
				// // 账号密码登录
				uni.hideKeyboard();
				if (this.current == 0) {
					//#ifdef H5
					this.$login({
						url: "/login2",
						data: {
							account: this.username,
							password: this.password,
							captcha: this.imgcode.toLowerCase(),
							captchaId: this.captchaId,
						}
					}).then(res => {
						if (res) {
							return uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						} else {
							socket.init();
						}
					})
					// }
					//#endif
					//#ifdef APP-PLUS
					if (this.listData.length > 0) {
						this.listData.map(ele => {
							if (this.username == ele.username && this.password == ele.password) {
								this.$login({
									url: "/login2",
									data: {
										account: this.username,
										password: this.password,
										captcha: this.imgcode.toLowerCase(),
										captchaId: this.captchaId,
									}
								}).then(res => {
									if (res) {
										return uni.showToast({
											title: res.msg,
											icon: 'none'
										});
									} else {
										socket.init();
									}
								})

							} else {
								this.show = true;
							}
						})
					} else {
						this.$login({
							url: "/login2",
							data: {
								account: this.username,
								password: this.password,
								captcha: this.imgcode.toLowerCase(),
								captchaId: this.captchaId,
							}
						}).then(res => {
							if (res) {
								return uni.showToast({
									title: res.msg,
									icon: 'none'
								});
							} else {
								this.openSQL(); //打开数据库
								this.createTable(); //创建表
								this.insertTableData(this.username, this.password); //新增表数据
								socket.init();
							}
						})
					}
					//#endif
				} else {
					// 验证码登录
					// 验证手机号合法性
					if (!this.$base.phoneRegular.test(this.phone)) {
						return uni.showToast({
							title: '请输入正确的手机号码',
							icon: 'none'
						});
					}
					this.$login({
						url: "/loginByPhone",
						data: {
							phone: this.phone,
							phoneMsg: this.checknum
						}
					}).then(res => {
						if (res) {
							return uni.showToast({
								title: res.msg,
								icon: 'none'
							});
						}
						// socket.init();
						return;
					})
				}
			},
			// 微信APP登录
			onWxAppLogin() {
				var that = this;
				uni.login({
					provider: 'weixin',
					onlyAuthorize: true,
					success: function(loginRes) {
						that.codeRes(loginRes.code);

					},
					fail: (err) => {
						uni.showToast({
							title: '绑定失败',
							icon: "none"
						});
						console.log('login fail:', err);
					}
				});
			},
			onzfbAppLogin() {
				let urls =
					'https://openauth.alipay.com/oauth2/publicAppAuthorize.htm?app_id=2021004153668213&scope=auth_user&redirect_uri=https://test.baoxianzhanggui.com/pay/';
				urls = encodeURIComponent(urls); //将地址编码成浏览器访问的格式
				plus.runtime.openURL(
					'alipays://platformapi/startapp?appId=20000067&url=' + urls,
					res => {
						//这里写打开URL地址失败后的处理0
						uni.showModal({
							content: '本机未检测到对应客户端，是否打开浏览器访问页面？',
							success: function(res) {
								if (res.confirm) {
									//plus.runtime.openURL();
								}
							}
						});
					},
					'com.eg.android.AlipayGphone'
				);
			},
			codeRes(code) {
				this.$login({
					url: "/wechat/login",
					data: {
						code: code,
					}
				}).then(res => {
					return uni.showToast({
						title: res.msg,
						icon: 'none'
					});
					socket.init();
					return;
				})
			},
			// 打开数据库
			openSQL() {
				// 这个是查询有没有打开数据库
				let open = DB.isOpen();
				DB.openSqlite()
					.then(res => {})
					.catch(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,"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,
					}]
					arr.map(item => {
						let time = this.formatDate(new Date().getTime());
						let sql =
							`'${item.username}','${item.password}','${time}'`;
						let condition = "'username','password','time'";
						// 新增 DB.insertTableData(表名, 对应表头列的数据)
						DB.insertTableData("chat", sql, condition)
							.then(res => {
								this.selectTableData();
							})
							.catch(error => {});
					})
				} else {}
			},


			// 查询表数据
			selectTableData() {
				let open = DB.isOpen();
				if (open) {
					// 查询表 DB.selectTableData(表名,查询条件列名,查询条件列值)
					DB.selectTableData("chat")
						.then(res => {
							console.log("contact表数据", res);
							this.listData = res;
							this.username = res[0].username;
							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}'`;
					// 修改表数据 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.dropTable("chat")
						.then(res => {})
						.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 lang="scss" scoped>
	/deep/ {
		.u-tab-bar {
			background: linear-gradient(90deg, #0052FF 0%, rgba(0, 82, 255, 0) 100%) !important;
			border-radius: 4px 4px 4px 4px;
		}
	}

	.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: 50rpx;
		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;
	}

	.bg-color {
		background-color: #0052FF;
		border-radius: 20px;
	}

	.bg-hover-color {
		background-color: #0052FF;
		opacity: 0.65;
		border-radius: 20px;
	}

	.text-color {
		color: #0052FF;
	}
</style>