// pages/login/login.js
const app = getApp();
const speed = 1000;
const time = 60;
const interval = 50;
let phoneInter: number = 0;
let codeInter: number = 0;
let setInter: number = 0
import { baseurl, captcha } from '../../config'
import { getAuthCodeImpl, phoneLoginImpl } from "../../service/impl/hwUser.impl";
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		color: false, // 验证码字体颜色
		code_message: '获取验证码', // 验证码文字
		time, // 时间
		canLogin: false, //是否可以登陆
		phone: '', // 手机
		formatPhone: '',
		code: '', // 验证码
		userAgreement: encodeURIComponent(baseurl + '/uploadfile/userAgreement.html'),
		privacyPolicy: encodeURIComponent(baseurl + '/uploadfile/privacyPolicy.html'),
		isCheck: false, // 是否勾选用户协议
	},
	/**
	 * 勾选用户协议
	 */
	checked() {
		this.setData({
			isCheck: !this.data.isCheck,
			canLogin: Boolean(app.globalData.phone_zz.test(this.data.phone) && this.data.code && !this.data.isCheck),
		})
	},
	// 打开用户协议 和 隐私政策
	openWebView(e: any) {
		wx.navigateTo({
			url: '/pages/web-view/web-view?url=' + e.currentTarget.dataset.url,
		})
	},
	/**
	 * 
	 * 时间倒计时
	 */
	countDown(options: any) {
		const _time = --this.data.time;
		this.setData({
			code_message: `已发送(${_time}s)`,
			color: true,
			time: _time
		})
		setInter = setInterval(_ => {
			let _time = this.data.time;
			_time--;
			if (_time > 0) {
				this.setData({
					code_message: `已发送(${_time}s)`,
					color: true,
					time: _time
				})
			} else {
				clearInterval(setInter);
				this.setData({
					code_message: `重新发送`,
					color: false,
					time
				});
			}
		}, speed)
		getAuthCodeImpl({ phone: this.data.phone, ...options }).then(res => {
			if (res.errCode === 0) {
				wx.showToast({
					icon: 'none',
					title: '发送成功',
				})
			}
		}).catch(() => {
			clearInterval(setInter);
			wx.showModal({
				title: '提示',
				content: '发送失败，请稍后重试',
				showCancel: false,
				success: () => {
					this.setData({
						code_message: `重新发送`,
						color: false,
						time
					})
				}
			})
		})
	},
	/**
	 * 获取验证码
	 * @phone 电话号码
	 */
	getCode() {
		if (this.data.time === time) {
			if (app.globalData.phone_zz.test(this.data.phone)) {
				wx.navigateToMiniProgram({
					appId: 'wx5a3a7366fd07e119',
					path: '/pages/captcha/index',
					extraData: {
						appId: captcha//您申请的验证码的 appId
					}
				})
			} else {
				wx.showToast({
					icon: 'none',
					title: this.data.phone ? '手机号码格式错误！' : '请填写手机号码！',
				})
			}
		}
	},
	/**
	 * 检查是否可以登陆
	 * @canLogin 是否可以登陆
	 * @phone  电话号码
	 */
	checkPhone(e: any) {
		const value: string = e.detail.value;
		const phone = value.replace(/\s/g, '');
		clearTimeout(phoneInter);
		phoneInter = setTimeout(_ => {
			let formatPhone: string
			if (phone.length === 11) {
				formatPhone = phone.replace(/^(.{3})(.*)(.{4})/, '$1 $2 $3');
				this.setData({
					formatPhone
				})
			}
			this.setData({
				canLogin: Boolean(app.globalData.phone_zz.test(value) && this.data.code && this.data.isCheck),
				phone: phone,
			})
		}, interval)
	},
	/**
	 * 检查验证码是否可以登陆
	 * @canLogin 是否可以登陆
	 * @code  验证码
	 */
	checkCode(e: any) {
		const value = e.detail.value;
		clearTimeout(codeInter);
		codeInter = setTimeout(_ => {
			this.setData({
				canLogin: Boolean(app.globalData.phone_zz.test(this.data.phone) && value && this.data.isCheck),
				code: value
			})
		}, interval)
	},
	/**
	 * 点击登录
	 * @phone {number} 电话号码
	 * @code {string} 验证码
	 * @register_from {注册来源} 0 小程序 1 APP 2 后台
	 */
	submit() {
		// 首先判断是否可以登陆
		const status = this.data.canLogin;
		if (status) {
			phoneLoginImpl({
				phone: this.data.phone,
				code: this.data.code,
				register_from: 0
			}).then(res => {
				if (res.errCode === 0) {
					// 请求成功 存入userID和userToken 并根据来源跳转不同的页面  后台账号跳转首页
					wx.setStorage({
						key: 'userId',
						data: res.data.userInfo.id,
						success: () => {
							wx.setStorage({
								key: 'userToken',
								data: res.data.userInfo.userToken,
								success: () => {
									wx.setStorageSync('userInfo', res.data.userInfo)
									wx.setStorageSync('firstLogin', true)
									if (!wx.getStorageInfoSync().keys.length) {
										wx.setStorageSync('hasClear', true)
									}
									// 提交是否登录信息
									if (res.data.userInfo.isDemonstrate) {
										wx.reLaunch({
											url: '/pages/index/index'
										})
									} else {
										wx.reLaunch({
											url: '/pages/my-order/my-order'
										})
									}
								}
							})
						}
					})
				}
			})
		} else {
			let content = ''
			if (!this.data.isCheck) {
				content = '请勾选用用户协议与隐私政策'
			}
			if (!this.data.code) {
				content = '请填写验证码'
			}
			if (!this.data.phone || !app.globalData.phone_zz.test(this.data.phone)) {
				content = '电话号码格式错误'
			}
			wx.showModal({
				title: '登录失败',
				content,
				showCancel: false,
				confirmColor: '#31364C',
			})
		}
	},
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.options = options;
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		wx.hideHomeButton();
		const captchaResult = app.globalData.captchaResult;
		console.log(captchaResult);
		if (captchaResult && captchaResult.ret === 0) {
			// 将验证码的结果返回至服务端校验
			const ticket = captchaResult.ticket;
			const randstr = captchaResult.randstr;
			this.countDown({ ticket, randstr })
			app.globalData.captchaResult = null; // 验证码的票据为一次性票据，取完需要置空
		}
	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	}
})