<template>
	<mobile-frame>
		<view class="main">
			<view class="one" v-if="platform.uniPlatform=='app'">
				<view class="one_2">
					<uni-data-checkbox mode="tag" v-model="loginType" :localdata="loginTypeList" @change="logintypeChange"></uni-data-checkbox>
				</view>
				<view class="one_3" v-if="loginType==0">
					<uni-forms ref="codeForm" :rules="codeRules" :model="codeForm" label-width="auto">
						<uni-forms-item label="手机号" name="phone">
							<uni-easyinput type="number" v-model="codeForm.phone" placeholder="请输入手机号" />
						</uni-forms-item>
						<uni-forms-item label="验证码" name="code">
							<view class="yzm">
								<view class="l">
									<uni-easyinput type="text" v-model="codeForm.code" placeholder="请输入手机验证码" />
								</view>
								<view class="r">
									<button type="default" size="mini" @tap.stop="appsendCount">{{time_count==0?'验证码':time_count}}</button>
								</view>
							</view>
						</uni-forms-item>
						<view class="btn">
							<button type="default" size="mini" @click="codeSubmit('codeForm')">提交登录</button>
						</view>
					</uni-forms>
				</view>
				<view class="one_4" v-else-if="loginType==1">
					<uni-forms ref="accountForm" :rules="accountRules" :model="accountForm" label-width="auto">
						<uni-forms-item label="手机号" name="phone">
							<uni-easyinput type="number" v-model="accountForm.phone" placeholder="请输入手机号" />
						</uni-forms-item>
						<uni-forms-item label="登录密码" name="password">
							<uni-easyinput type="number" v-model="accountForm.password" placeholder="请输入登录密码" />
						</uni-forms-item>
						<view class="btn">
							<button type="default" size="mini" @click="accountSubmit('accountForm')">提交登录</button>
						</view>
					</uni-forms>
				</view>
			</view>
			<view class="two" v-else-if="platform.uniPlatform=='mp-weixin'">
				<view class="icon">
					<text class="iconfont icon-weixin"></text>
				</view>
				<view class="btn">
					<button type="default" size="mini" @tap="wxLogin()">微信信任登录</button>
				</view>
			</view>
			<view class="thr">
				<view class="thr_1">
					<checkbox-group @change="changeAgree">
						<label>
							<checkbox :checked="agree" />
							<text @tap="toAgree()">我已阅读并同意“用户协议”和“隐私政策”</text>
						</label>
					</checkbox-group>
				</view>
			</view>
		</view>
		<uni-popup ref="dialogShow" type="dialog">
			<uni-popup-dialog :title="dialog.title" mode="base" :before-close="true" @confirm="diaSubmit(dialog)" @close="diaReset(dialog)">
				<view class="dialog dialog_1" v-if="dialog.type=='1'">
					<uni-forms ref="phoneForm" :model="phoneForm" label-width="auto">
						<uni-forms-item label="方式">
							<uni-data-checkbox v-model="phoneForm.type" :localdata="typeList" />
						</uni-forms-item>
						<uni-forms-item label="微信" v-if="phoneForm.type==0">
							<button type="default" size="mini" open-type="getPhoneNumber" @getphonenumber="getUserPhone">获取微信绑定手机</button>
						</uni-forms-item>
						<uni-forms-item label="手机号" v-if="phoneForm.type==0">
							<uni-easyinput type="number" v-model="phoneForm.phone" disabled />
						</uni-forms-item>
						<uni-forms-item label="手机号" v-if="phoneForm.type==1">
							<view class="yzm">
								<view class="l">
									<uni-easyinput type="number" v-model="phoneForm.phone" placeholder="请输入手机号" />
								</view>
								<view class="r">
									<button type="default" size="mini" @tap="sendCount">{{time_count==0?'验证码':time_count}}</button>
								</view>
							</view>
						</uni-forms-item>
						<uni-forms-item label="验证码" v-if="phoneForm.type==1">
							<uni-easyinput type="number" v-model="phoneForm.code" placeholder="请输入验证码" />
						</uni-forms-item>
					</uni-forms>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</mobile-frame>
</template>

<script>
	export default {
		data() {
			return {
				point_title: this.$config.point_title,
				// 平台信息
				platform: {},
				//openid
				openid: '',
				// 隐私协议
				agree: false,
				// app-start
				loginType: 0,
				// 短信登录
				loginTypeList: [ //
					{
						"value": 0,
						"text": "短信登录"
					}, {
						"value": 1,
						"text": "密码登录"
					},
				],
				// 验证码登录
				codeForm: {},
				codeRules: {
					phone: {
						rules: [ //
							{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '账号长度在{maxLength}个字符',
							}
						]
					},
					code: {
						rules: [ //
							{
								required: true,
								errorMessage: '请输入短信验证码',
							}
						]
					}
				},
				// 密码登录
				accountForm: {},
				accountRules: {
					phone: {
						rules: [ //
							{
								required: true,
								errorMessage: '请输入手机号',
							},
							{
								minLength: 11,
								maxLength: 11,
								errorMessage: '账号长度在{maxLength}个字符',
							}
						]
					},
					password: {
						rules: [ //
							{
								required: true,
								errorMessage: '请输入登录密码',
							}
						]
					}
				},
				// app-end
				// 微信登陆
				// 无账号
				is_user: false,
				user: {},
				// 弹框
				dialog: {
					title: '绑定手机号',
					type: '1'
				},
				// 绑定手机号
				phoneForm: {
					type: 0,
				},
				typeList: [ //
					{
						text: '微信',
						value: 0
					},
					{
						text: '短信验证',
						value: 1
					}
				],
				// 倒计时
				time_count: 0
			};
		},
		onShow: function() {
			const that = this;
			that.search();
		},
		methods: {
			search() {
				const that = this;
				uni.getStorage({
					key: 'system',
					success: function(res) {
						if (res.data) that.$set(that, `platform`, res.data);
						// 获取openid
						that.searchOpenid()
					}
				})
			},
			// 查询openid
			searchOpenid() {
				const that = this;
				if (that.platform.uniPlatform == 'mp-weixin') {
					uni.login({
						provider: 'weixin',
						success: async function(res) {
							const aee = await that.$api(`/wechat/api/login/app`, 'GET', {
								config: that.$config.wx_projectkey,
								js_code: res.code
							})
							if (aee.errcode == '0') {
								that.$set(that, `openid`, aee.data.openid);
								// 微信登录
								that.openidLogin(aee.data.openid);
							}
						},
						fail: function(err) {
							console.log(err);
						}
					})
				} else if (that.platform.uniPlatform == 'app') {
					console.log('to do');
				}
			},
			// 有账号，微信登录，直接返回上一页
			async openidLogin(e) {
				const that = this;
				let res = await that.$api(`/user/wxLogin`, 'POST', {
					openid: e
				})
				if (res.errcode == '0') {
					uni.setStorage({
						data: res.data,
						key: 'token',
						success: function() {
							uni.navigateBack({
								delta: 1
							})
						}
					})
				} else {
					if (res.errcode == '-5') {
						console.log('无账号');
						that.$set(that, `is_user`, false)
					}
				}
			},
			// 微信信任登录
			async wxLogin() {
				const that = this;
				if (that.agree) {
					uni.getUserProfile({
						desc: '用于展示',
						success: async function(res) {
							let parmas = {
								openid: that.openid,
								icon: [{
									url: res.userInfo.avatarUrl
								}],
								name: res.userInfo.nickName,
							}
							const arr = await that.$api(`/user`, 'POST', parmas);
							if (arr.errcode == '0') {
								that.$set(that, `user`, arr.data);
								// 打开弹框
								that.diaShow();
							} else {
								uni.showToast({
									title: arr.errmsg,
									icon: 'none'
								});
							}
						},
						fail: function(err) {
							console.log(err);
						}
					})

				} else {
					uni.showToast({
						title: '请阅读并同意用户协议和隐私政策',
						icon: 'none'
					})
				}
			},
			// 微信信任登录-1
			async wxLogins() {
				const that = this;
				const agg = await that.$api(`/user/wxLogin`, 'POST', {
					openid: that.openid
				})
				if (agg.errcode == '0') {
					uni.setStorage({
						data: agg.data,
						key: 'token',
						success: function() {
							uni.navigateBack({
								delta: 1
							})
						}
					})
				} else {
					uni.showToast({
						title: agg.errmsg,
						icon: 'none'
					});
				}
			},
			// 打开弹框,绑定手机号
			diaShow() {
				const that = this;
				that.$refs.dialogShow.open();
			},
			// 获取手机号
			async getUserPhone(e) {
				const that = this;
				let user = that.user;
				let detail = e.detail;
				let res = await that.$api(`/wechat/api/login/getPhone`, 'GET', {
					config: that.$config.wx_projectkey,
					code: detail.code
				})
				if (res.errcode == '0') {
					let phone = res.data && res.data.phone_info && res.data.phone_info.purePhoneNumber || '';
					that.$set(that.phoneForm, `phone`, phone);
				} else {
					uni.showToast({
						title: res.errmsg,
						icon: 'none'
					})
				}

			},
			// 短信验证
			// 获取验证码
			async sendCount() {
				const that = this;
				let user = this.user;
				let form = that.form && that.form.phone ? that.form : that.phoneForm;
				if (form && form.phone) {
					let res = await that.$api(`/user/toBindPhone`, 'POST', {
						id: user._id,
						phone: form.phone
					})
					if (res.errcode == '0') {
						uni.showToast({
							title: '发送成功'
						})
						that.$set(that, `time_count`, 60);
						that.timeDown();
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						})
					}
				} else {
					uni.showToast({
						title: '输入错误，请重新输入!',
						icon: 'none'
					})
				}
			},
			// 倒计时
			timeDown() {
				const that = this;
				var times = setInterval(() => {
					that.time_count--;
					if (that.time_count <= 0) {
						clearInterval(times);
					}
				}, 1000);
			},
			// 弹框确认(关闭)
			async diaSubmit(e) {
				const that = this;
				let user = this.user;
				if (e.type == '1') {
					const that = this;
					let form = that.phoneForm;
					if (form.type == '0') {
						if (form && form.phone) that.updatePhone(form.phone);
					} else if (form.type == '1') {
						const res = await that.$api(`/user/checkBindPhone`, 'POST', {
							id: user._id,
							code: form.code,
							phone: form.phone
						});
						if (res.errcode == '0') {
							const arr = await that.$api(`/user/${user._id}`, 'POST', {
								phone: form.phone
							});
							if (arr.errcode == '0') {
								uni.showToast({
									title: '绑定手机号成功',
									icon: 'none'
								})
								that.wxLogins();
							} else {
								uni.showToast({
									title: arr.errmsg,
									icon: 'none'
								})
							}
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
					}
				}
			},
			async updatePhone(e) {
				const that = this;
				let user = that.user;
				let arr = await that.$api(`/user/${user._id}`, 'POST', {
					phone: e
				})
				if (arr.errcode == '0') {
					that.wxLogins();
				} else {
					uni.showToast({
						title: res.errmsg,
						icon: 'none'
					})
				}
			},
			// 弹框取消(关闭)
			diaReset(e) {
				const that = this;
				if (e.type == '1') {
					that.wxLogins();
				}
			},
			// 账号登录-start
			// 选择登录类型
			logintypeChange(e) {
				const that = this;
				that.$set(that, `loginType`, e.detail.value)
			},
			// 验证码登录
			async appsendCount() {
				const that = this;
				let form = that.codeForm;
				if (form && form.phone) {
					let res = await that.$api(`/user/toLoginByCode`, 'POST', {
						phone: form.phone
					})
					console.log(res);
					if (res.errcode == '0') {
						uni.showToast({
							title: '发送成功'
						})
						that.$set(that, `time_count`, 60);
						that.timeDown();
					} else {
						uni.showToast({
							title: res.errmsg,
							icon: 'none'
						})
					}
				} else {
					uni.showToast({
						title: '输入错误，请重新输入!',
						icon: 'none'
					})
				}
			},
			codeSubmit(ref) {
				const that = this;
				let agree = that.agree;
				that.$refs[ref].validate().then(async params => {
					if (agree) {
						const res = await that.$api(`/user/checkLoginCode`, 'POST', params);
						if (res.errcode == '0') {
							uni.setStorage({
								key: 'token',
								data: res.data,
								success: function() {
									uni.navigateBack({
										delta: 1
									})
								}
							});
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: '请阅读并同意用户协议和隐私政策',
							icon: 'none'
						})
					}

				}).catch(err => {
					console.log(err);
				})
			},
			// 账号登录
			accountSubmit(ref) {
				const that = this;
				let agree = that.agree;
				that.$refs[ref].validate().then(async params => {
					if (agree) {
						const res = await that.$api(`/user/login`, 'POST', {
							...params
						})
						if (res.errcode == '0') {
							uni.setStorage({
								key: 'token',
								data: res.data,
								success: function() {
									uni.navigateBack({
										delta: 1
									})
								}
							});
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
					} else {
						uni.showToast({
							title: '请阅读并同意用户协议和隐私政策',
							icon: 'none'
						})
					}
				}).catch(err => {
					console.log(err);
				})
			},
			// 账号登录-end
			// 同意隐私协议
			changeAgree() {
				const that = this;
				if (that.agree) that.$set(that, `agree`, false)
				else that.$set(that, `agree`, true);
			},
			// 查看隐私协议
			toAgree() {
				uni.navigateTo({
					url: `/pages/other/agree`
				})
			},
		}
	}
</script>

<style lang="scss">
	.main {
		.one {
			padding: 2vw;

			.one_2 {
				margin: 4vw 22vw;
				text-align: center;
			}

			.btn {
				text-align: center;
				margin: 0 0 2vw 0;
				width: 96vw;

				button {
					width: 40%;
					padding: 1vw 2vw;
					background-color: var(--f35BColor);
					color: var(--fffColor);
					font-size: var(--font20Size);
				}
			}
		}

		.two {
			text-align: center;
			margin: 20vw 0;

			.icon {
				margin: 0 0 5vw 0;

				text {
					font-size: 60px;
				}
			}

			.btn {
				button {
					background-color: var(--f35BColor);
					color: var(--fffColor);
				}
			}
		}

		.thr {
			.thr_1 {
				padding: 0 2vw;
				font-size: 14px;
				text-align: center;
				position: absolute;
				width: 96vw;
				bottom: 25vw;
			}
		}
	}

	.dialog {
		width: 100vw;
	}

	.dialog_1 {
		.uni-forms {
			display: flex;

			form {
				width: 100%;
			}
		}

		.uni-data-checklist {
			border: 1px solid #E5E5E5;
			padding: 1vw;
			border-radius: 5px;
		}

		.uni-forms-item {
			margin-bottom: 2vw !important;
		}


	}

	.yzm {
		display: flex;
		flex-direction: row;
		justify-content: space-between;

		.l {
			flex-grow: 1;
		}

		.r {
			width: 18vw;

			button {
				width: 100%;
				line-height: 2.8;
				padding: 0 1vw;
			}
		}
	}
</style>
