var beforUrl = null;
/* // 自己封装的验证码插件
var instanceVerify = new VerifyImg({
    el: '#imgVer',
    width: '260',
    height: '140',
    done(event) {
        commonLoginVue.handleSendCode(event)
    }
}) */
var commonLoginVue = new Vue({
    el: '#commonLogin',
    data() {
        return {
            timecs: 1,
            loginShow: 2,
            mobile: '',
            code: '',
            ValiImage: '',
            show: true,
            timer: null,
            count: '',
            codeArr: [],
            codeShow: false,
            dialingCode: '+86',
            password: '',
            rPasswordShow: false,
            smSuccess: false,
            name: '',
            qrcodeInfo: '',
            openid: '',
            gender: 'male',
            genderArr: [
                {
                    label: '男',
                    value: 'male',
                    isChecked: true,
                },
                {
                    label: '女',
                    value: 'female',
                    isChecked: false,
                },
            ],
            qcodeTimer: null,
            sxer: false,
            hasPushu: false,
            zpImgCode: '/captcha.jpg',

            verifyBg: '/captcha2.jpg',
            verifyShard: '/captcha3.jpg',
            debouncedSendClick: this.debounce(this.sendClick, 500)
        }
    },
    mounted() {
        // 加载完成后出现
        this.$nextTick(() => {
            $('#include-common-login').addClass('zp-cloak')
        })
        console.log('实例化完成')
        let url = this.GetQueryString('redirectUrl')
        beforUrl = url == '/login' ? false : url
        this.getCode()
    },
    methods: {
        // 自定义防抖函数
        debounce(func, delay) {
            let timeoutId;
            return function (...args) {
                clearTimeout(timeoutId);
                timeoutId = setTimeout(() => {
                    func.apply(this, args);
                }, delay);
            };
        },
        cleanParams() {
            this.loginShow = 2
            this.mobile = ''
            this.ValiImage = ''
            this.password = ''
            this.code = ''
            this.codeShow = false
            if (this.qcodeTimer) {
                clearTimeout(this.qcodeTimer)
                this.qcodeTimer = null
            }
        },
        changeImgCode() {
            this.zpImgCode = '/captcha.jpg?time=' + new Date().getTime()
        },
        /* 登录相关 */
        handlerCode() {
            this.codeShow = !this.codeShow
        },
        wxLogin: function () {
            var that = this
            that.timecs = 1
            that.qrcodeInfo = ''
            that.sxer = false
            $('#qrcode-reg').html('')
            if (this.qrcodeInfo == '') {
                $.ajax({
                    url: '/weixin/get_qrcode',
                    type: 'POST',
                    success: function (res) {
                        that.qrcodeInfo = res.data
                        if (res.data) {
                            $('#qrcode-reg').qrcode({
                                render: 'image',
                                text: res.data.url,
                                background: '#ffffff',
                                foreground: '#000000',
                            })
                            that.queryResult(res.data.ticket)
                        }
                    },
                })
            }
        },
        queryResult: function (ticket) {
            var that = this
            that.timecs++
            if (that.timecs == 90) {
                that.sxer = true
                clearTimeout(that.qcodeTimer)
                that.qcodeTimer = null
                return
            }
            $.ajax({
                url: '/weixin/queryResult',
                type: 'POST',
                data: { ticket: ticket },
                success: function (res) {
                    if (res.code == 0) {
                        layer.msg('登录成功，欢迎回家!', { icon: 1, time: 1000 })
                        if (beforUrl) {
                            window.location.href = beforUrl
                        } else if (window.location.pathname == '/login') {
                            window.location.href = '/u/' + res.cardNumber;
                        } else {
                            window.location.reload();
                        }

                        // var beforUrl = that.GetQueryString("redirectUrl")
                        //   ? that.GetQueryString("redirectUrl")
                        //   :  '/u/'+res.cardNumber;
                        // window.location.href = beforUrl ? beforUrl : '/u/'+res.cardNumber;
                    } else if (res.code == 2) {
                        //绑定手机号
                        that.openid = res.openid
                        that.loginShow = 2
                    } else {
                        that.qcodeTimer = setTimeout(function () {
                            that.queryResult(ticket)
                        }, 2000)
                    }
                },
            })
        },
        check: function (index) {
            // 先取消所有选中项
            this.genderArr.forEach(function (item) {
                item.isChecked = false
            })

            //再设置当前点击项选中
            this.gender = this.genderArr[index].value
            // 设置值，以供传递
            this.genderArr[index].isChecked = true
        },
        //获取区号
        getCode: function () {
            var that = this
            $.post('/common/getFamilyCountry', function (result) {
                that.codeArr = result.data
            })
        },
        codeSelect: function (item) {
            this.dialingCode = item.tel
            this.codeShow = false
        },
        openZp: function () {
            var that = this
            if (!that.name) {
                layer.msg('请填写姓名!', { icon: 2, time: 1000 })
                return false
            }
            $.ajax({
                url: '/updateUserInfo',
                type: 'POST',
                dataType: 'json',
                data: {
                    name: that.name,
                    gender: that.gender,
                },
                success: function (res) {
                    if (res.code == 0) {
                        // setTimeout('window.location.href="/"', 1000)
                        layer.msg('登录成功，欢迎回家!', { icon: 1, time: 1000 })
                        if (beforUrl) {
                            window.location.href = beforUrl
                        } else if (window.location.pathname == '/login') {
                            window.location.href = '/u/' + res.cardNumber;
                        } else {
                            window.location.reload();
                        }
                    } else {
                        layer.msg(res.message, { icon: 2, time: 1000 })
                    }
                },
            })
        },
        //弱密码判断
        checkPassword: function () {
            var that = this
            let mobile = that.mobile.replace(/\s+/g, '')
            if (!mobile) {
                layer.msg('请输入手机号/族谱号', { icon: 2 })
                return
            }
            if (mobile.length < 6 || mobile.length > 11) {
                layer.msg('请输入正确的手机号/族谱号', { icon: 2 })
                return
            }
            if (!that.password) {
                layer.msg('请输入密码', { icon: 2 })
                return
            }
            $.ajax({
                url: `/checkWeakPassword?password=${that.password}&userName=${mobile}`,
                type: 'GET',
                success: function (res) {
                    if (res.isWeakPassword) {
                        that.rPasswordShow = true
                    } else {
                        that.pwLogion()
                    }
                },
            })
        },
        //账号密码登录
        pwLogion: function () {
            var that = this
            if (!that.ValiImage) {
                layer.msg('请输入图片验证码', { icon: 2 })
                return
            }
            var data = {
                mobile: that.mobile.replace(/\s+/g, ''),
                ValiImage: that.ValiImage,
                password: that.password,
            }
            layer.load("正在登录...")
            $.ajax({
                url: '/loginByPassword',
                type: 'POST',
                data: data,
                success: function (res) {
                    layer.closeAll("loading");
                    if (res.code == 0) {
                        // window.open('/u/'+res.data.cardNumber)

                        // window.location.href = '/u/'+res.data.cardNumber
                        // window.location.href = beforUrl ? beforUrl : '/u/' + res.data.cardNumber
                        if (beforUrl) {
                            window.location.href = beforUrl
                        } else if (window.location.pathname == '/login') {
                            window.location.href = '/u/' + res.data.cardNumber;
                        } else {
                            window.location.reload();
                        }
                    } else {
                        that.changeImgCode()
                        layer.msg(res.message, { icon: 2, time: 1000 })
                    }
                },
            })
        },
        bdClick: function () {
            var that = this
            var reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
            let mobile = that.mobile.replace(/\s+/g, '')
            if (!mobile) {
                layer.msg('请输入手机号', { icon: 2 })
                return false
            }
            if(that.dialingCode == '+86') {
                if (!reg.test(mobile)) {
                    layer.msg('手机号码错误', { icon: 2 })
                    return false
                }
            }
            // if (!that.ValiImage) {
            //     layer.msg('请输入图片验证码', { icon: 2 })
            //     return false
            // }
            if (!that.code) {
                layer.msg('请输入短信验证码', { icon: 2 })
                return false
            }
            layer.load("正在登录...")
            $.ajax({
                url: '/login/registerJiTang',
                type: 'POST',
                dataType: 'json',
                data: {
                    mobile: that.mobile.replace(/\s+/g, ''),
                    code: that.code,
                    openid: that.openid,
                    ValiImage: that.ValiImage,
                    dialingCode: that.dialingCode,
                },
                success: function (res) {
                    layer.closeAll("loading");
                    if (res.code == 0) {
                        layer.msg('登录成功，页面刷新中', { icon: 1, time: 3000 })
                        setTimeout(function () {
                            // window.open('/u/'+res.data)
                            // window.location.href = '/u/'+res.data;
                            // window.location.href = beforUrl;
                            if (beforUrl) {
                                window.location.href = beforUrl
                            } else if (window.location.pathname == '/login') {
                                window.location.href = '/u/' + res.data;
                            } else {
                                window.location.reload();
                            }
                        }, 1000)
                    } else if (res.code == 1) {
                        that.loginShow = 4
                    } else {
                        that.changeImgCode()
                        layer.msg(res.message, { icon: 2, time: 1000 })
                    }
                },
            })
        },
        backClick: function () {
            window.location.href = '/login'
        },
        sendClick: function () {
            var that = this
            var reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/
            let mobile = that.mobile.replace(/\s+/g, '')
            if (!mobile) {
                layer.msg('请输入手机号', { icon: 2 })
                return false
            }
            if (that.dialingCode == '+86') {
                if (!reg.test(mobile)) {
                    layer.msg('手机号码错误', { icon: 2 })
                    return false
                }
            }

            // if (!that.ValiImage) {
            //     layer.msg('请输入图片验证码', { icon: 2 })
            //     return false
            // }

            /* 自己封装的验证码 */
            // instanceVerify.init()

            /* 触发阿里云验证 */
            console.log('触发阿里云验证')
            $('#sendSMSCode').trigger('click');
        },
        handleSendCode(captchaCode) {
            let that = this
            $.ajax({
                url: '/sendCode',
                type: 'POST',
                dataType: 'json',
                data: {
                    mobile: that.mobile.replace(/\s+/g, ''),
                    captchaCode: captchaCode
                },
                success: function (res) {
                    if (res.code == 0) {
                        /* 自己封装的验证码 */
                        // instanceVerify.success()
                        setTimeout(() => {
                            layer.msg('获取验证码成功,请注意查收', { icon: 1 })
                        }, 2500)
                        that.sixDjs()
                    } else {
                        // instanceVerify.fail()
                        if (res.message != '请填写有效的校验码') {
                            layer.msg(res.message, { icon: 2 })
                        }
                    }
                },
            })
        },
        sendSuccess() {
            setTimeout(() => {
                layer.msg('获取验证码成功,请注意查收', { icon: 1 })
            }, 600)
            this.sixDjs()
        },
        //60秒倒计时
        sixDjs: function () {
            var TIME_COUNT = 60
            var that = this
            if (!this.timer) {
                this.count = TIME_COUNT
                this.show = false
                this.timer = setInterval(function () {
                    if (that.count > 0 && that.count <= TIME_COUNT) {
                        that.count--
                    } else {
                        that.show = true
                        clearInterval(that.timer)
                        that.timer = null
                    }
                }, 1000)
            }
        },
        GetQueryString: function (key) {
            // 获取参数
            var url = window.location.search
            // 正则筛选地址栏
            var reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)')
            // 匹配目标参数
            var result = url.substr(1).match(reg)
            //返回参数值
            return result ? decodeURIComponent(result[2]) : null
        },

    },
    watch: {
        loginShow(flag) {
            if (flag != 1) {
                if (this.qcodeTimer) {
                    clearTimeout(this.qcodeTimer)
                    this.qcodeTimer = null
                }
            }
            if (flag == 1) {
                this.wxLogin()
            }
            this.mobile = ''
            this.code = ''
            this.ValiImage = ''
            this.password = ''
        }
    }
})

$(document).ready(function () {
    $('#signIn').hover(function () {
        if (specialPages.includes(window.location.pathname)) return
        $('#commonLogin').show()
        $(this).addClass('active')
    })

    $('.bot-item1').hover(
        () => {
            $('.bot-img1-1').hide()
            $('.bot-img1-2').show()
        },
        () => {
            $('.bot-img1-2').hide()
            $('.bot-img1-1').show()
        }
    )

    $('.bot-item2').hover(
        () => {
            $('.bot-img2-1').hide()
            $('.bot-img2-2').show()
        },
        () => {
            $('.bot-img2-2').hide()
            $('.bot-img2-1').show()
        }
    )

    $('.mark-close').click(() => {
        $('#commonLogin').hide().removeClass('mark')
        commonLoginVue.cleanParams()
    })
})

document.addEventListener('click', function (event) {
    if ($('#commonLogin').is(':hidden') || specialPages.includes(window.location.pathname) || $("#aliyunCaptcha-window-popup").is(':visible') || $('.layui-layer-msg').is(':visible')) return
    let $commonLogin = $('.zp-login');
    // 检查点击的目标是否不是按钮本身
    if (!$commonLogin.is(event.target) && !$commonLogin.has(event.target).length) {
        $('#commonLogin').hide().removeClass('mark')
        $('#signIn').removeClass('active')
        // commonLoginVue.loginShow = 2
        commonLoginVue.cleanParams()
    }
});

// 登录回车事件
document.onkeyup = function (event) {
    if ($('#commonLogin').is(':hidden')) return
    var e = event || window.event || arguments.callee.caller.arguments[0];//兼容IE
    if (e && e.keyCode == 13) {// enter 键
        if (commonLoginVue.loginShow == 2) {
            commonLoginVue.bdClick()
        } else if (commonLoginVue.loginShow == 3) {
            commonLoginVue.checkPassword()
        }
    }
};