// pages/setting/pages/changePhone/changePhone.js
import { editUserPhone, sendPhoneCode } from '../../../../services/index'
import { testPhone } from '../../../../utils/util'
import {
	captcha
} from '../../../../config/config'
let time = 60
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		phoneNow: '',
		yanzheng: '获取验证码',
		time: 60,
		phone: '',
		format_phone: '',
		code: '',
    cansubmit: false,
    captcha
	},
	show() {
		// const captchaResult = getApp().captchaResult;
		// getApp().captchaResult = null; // 验证码的票据为一次性票据，取完需要置空
		// if (captchaResult && captchaResult.ret === 0) {
		// 	// 将验证码的结果返回至服务端校验
		// 	const ticket = captchaResult.ticket;
		// 	const randstr = captchaResult.randstr;
		// 	this.send({ randstr, ticket })
		// }
	},
	submit() {
		if (this.data.cansubmit) {
			editUserPhone({
				new_phone: this.data.phone,
				code: this.data.code,
			}).then(data => {
				wx.showToast({
					icon: 'none',
					mask: true,
					title: '手机号修改已完成',
					success: res => {
						setTimeout(() => {
							wx.navigateBack({
								delta: 1,
							})
						}, 1200)
					}
				})
				wx.setStorageSync('phone', this.data.phone)
			})
		} else {
			wx.showToast({
				icon: 'none',
				title: '请填写完整信息',
			})
		}
	},
	saveCode(e) {
		const code = e.detail.value
		this.setData({
			code
		})
		this.check()
	},
	savePhone(e) {
		if (e.detail.keyCode !== 8) {
			const format_phone = e.detail.value.split('').filter(value => value.trim())
			if (testPhone(format_phone.join(''))) {
				this.setData({
					phone: format_phone.join('')
				}, () => {
					this.check()
				})
			}
			if (format_phone.length >= 3) {
				format_phone.splice(3, 0, ' ')
			}
			if (format_phone.length >= 8) {
				format_phone.splice(8, 0, ' ')
			}
			this.setData({
				format_phone: format_phone.join('')
			})
		} else {
			const format_phone = e.detail.value.trim()
			this.setData({
				format_phone,
				phone: '',
				cansubmit: false
			})
		}
	},
	toTCaptcha() {
		if (testPhone(this.data.phone)) {
			if (time === 60) {
				editUserPhone({
					new_phone: this.data.phone,
					type: 'check_phone',
				}).then(data => {
					// wx.navigateToMiniProgram({
					// 	appId: 'wx5a3a7366fd07e119',
					// 	path: '/pages/captcha/index',
					// 	extraData: {
					// 		appId: captcha//您申请的验证码的 appId
					// 	}
          // })
          this.selectComponent('#captcha').show()
				})
			} else {
				wx.showToast({
					mask: true,
					icon: 'none',
					title: '请勿重复点击',
				})
			}
		} else {
			wx.showToast({
				icon: 'none',
				title: '请填写正确手机号',
			})
		}
	},
	send({ randstr, ticket }) {
		sendPhoneCode({
      phone: this.data.phone,
      ticket,
      randstr
    }).then(data => {
      wx.showToast({
        icon: 'none',
        title: '验证码发送成功',
      })
    })
    this.countdown()
	},
	countdown() {
		time--;
		this.setData({
			time,
			yanzheng: time + 's后重试'
		})
		let inter = setInterval(() => {
			if (time > 1) {
				time--;
				this.setData({
					time,
					yanzheng: time + 's后重试'
				})
			} else {
				clearInterval(inter)
				time = 60
				this.setData({
					time: 60,
					yanzheng: '获取验证码'
				}, _ => {
					inter = null;
				})
			}
		}, 1000)
	},
	check() {
		if (testPhone(this.data.phone) && this.data.code) {
			this.setData({
				cansubmit: true
			})
			return true
		} else {
			this.setData({
				cansubmit: false
			})
			return false
		}
  },
    // 验证码验证结果回调
    handlerVerify: function (ev) {
      // 如果使用了 mpvue，ev.detail 需要换成 ev.mp.detail
      if (ev.detail.ret === 0) {
        // 验证成功
        console.log('randstr:', ev.detail.ticket)
        console.log('ticket:', ev.detail.ticket)
        this.send({
          ticket: ev.detail.ticket,
          randstr: ev.detail.randstr
        })
      } else {
        // 验证失败
        // 请不要在验证失败中调用refresh，验证码内部会进行相应处理
      }
    },
    // 验证码准备就绪
    handlerReady: function () {
      console.log('验证码准备就绪')
    },
    // 验证码弹框准备关闭
    handlerClose: function (ev) {
      // 如果使用了 mpvue，ev.detail 需要换成 ev.mp.detail,ret为0是验证完成后自动关闭验证码弹窗，ret为2是用户主动点击了关闭按钮关闭验证码弹窗
      if (ev && ev.detail.ret && ev.detail.ret === 2) {
        console.log('点击了关闭按钮，验证码弹框准备关闭');
      } else {
        console.log('验证完成，验证码弹框准备关闭');
      }
    },
    // 验证码出错
    handlerError: function (ev) {
      console.log(ev.detail.errMsg)
      wx.showModal({
        title: '提示',
        content: ev.detail.errMsg,
        showCancel: false
      })
    },
	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {

	},

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

	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {
		wx.getStorage({
			key: 'phone',
			success: res => {
				const _data = res.data
				this.setData({
					phoneNow: _data.substring(0, 3) + ' **** ' + _data.substring(7, 11)
				})
			}
		})
	},

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

	},

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

	},

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

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	}
})