//手机号码相关
export default {
    data() {
        return {
            phonePattern: /^[1][3,4,5,6,7,8,9][0-9]{9}$/,
            isSend: false,
            msgCode: '',
            sendNum: 60,
            timer: null,
            captchaKey: '',
            codeImg: '',
            captcha: '',
            phone: ''
        }
    },
    methods: {
        getCode() {
            return this.$http.get('/captcha/get').then(res => {
                this.captchaKey = res.key
                this.codeImg = res.image
                this.$toast.dismiss()
                this.emitter.emit('phoneShow')
            })
        },
        sendMsg(phone) {
            this.phone = phone
            this.isSend = true
            this.setTime(60)
            return this.$http
                .get('/sms/sendVerify', {
                    phone: phone
                })
                .then(res => {
                    this.msgCode = res
                    this.$toast.success('发送成功')
                    return Promise.resolve()
                })
                .catch(e => {
                    if (e) {
                        this.$toast.error(e.error)
                        this.captcha = ''
                        this.captchaKey = ''
                    }
                    this.setTime(0)
                    return Promise.reject()
                })
        },
        setTime(num) {
            this.sendNum = num
            if (this.timer) {
                clearTimeout(this.timer)
            }

            if (num <= 0) {
                this.isSend = false
                return
            } else {
                this.timer = setTimeout(() => {
                    this.setTime(num - 1)
                }, 1000)
            }
        },
        verifyMsg(phone, code) {
            return this.$http
                .get('/sms/verify', {
                    phone: phone,
                    code: code
                })
                .catch(e => {
                    if (e) {
                        this.$toast.error(e.error)
                    }
                    return Promise.reject()
                })
        },
        loginByPhone(phone, psd) {
            return this.$http
                .post('/auth/phonePwdLogin', {
                    phone: phone,
                    password: psd
                })
                .catch(e => {
                    if (e) {
                        this.$toast.error(e.error)
                    }
                    return Promise.reject()
                })
                .then(res => {
                    localStorage.setItem('nineToken', res)
                    return this.$store.dispatch('getUserInfo')
                })
        }
    }
}
