
var windowWidth = $(window).width();
var windowHeight = $(window).height();
//  邮箱 公共方法
var accountVerifyCode = false
var valCodeInput = $("#val-code-input");
var valCodeItems = $("div[name='val-item']");
var regex = /^[\d]+$/;
var valCodeLength = 0;
var accountWarringTimeout = '';
var accountCurrectTimeout = '';
var nowlayerType = 'email'; //当前账号弹层为修改账号还是修改密码
var allli = $('.dggbMenu li');
var newemail = '';
var layerIndex = ''
$(document).ready(function () {
    valCodeInput = $("#val-code-input")
    valCodeItems = $("div[name='val-item']")
    allli = $('.dggbMenu li');

    $.each(allli, function (index, value) {
        // 访问当前元素

        // 在同一个函数上单击()
        $(this).mouseover(function () {
            $(this).find('.dggbSubMenuBg').show()
        });
        $(this).mouseleave(function () {
            $(this).find('.dggbSubMenuBg').hide()
        });
        let widths = $(this).find(".dggbMenuTitle").width()

        // $(this).find(".dggbMenuTitle").find('.menuline').css({'left':widths / 2})
    });

    if (windowWidth > 750) {
        $('.searchinputop .text1').click(function () {
            $('.closesearch').show()
            $('.searchLine').show()
            $('.searchCons').show()
            $('.serconTitle img').show()
            $('.searchinputop').css('z-index', '10')
            $('.serconTitleRight').hide()
            if ($('.searchinputop .text1').val() === '') {
                // input没有内容
                $(this).parent().parent().addClass('dggbDengSerTitlemouse')
            } else {
                $('.searchinputop').css('z-index', '1003')
            }
        })


        $(document).on('click', function (e) {
            var $searchCons = $('#searchCons');
            var $searchinputop = $('.searchinputop')

            var $closesearch = $('.closesearch')
            var $sercontopUlli = $('.sercontopUl li')
            if ($searchinputop.length > 0) {
                if (!$searchinputop.is(e.target) && $searchinputop.has(e.target).length === 0) {
                    if (!$searchCons.is(e.target) && $searchCons.has(e.target).length === 0) {
                        if ($('.searchinputop .text1').length > 0) {
                            if ($('.searchinputop .text1').val().length == 0) {
                                $('.closesearch').hide()
                                $('.searchLine').hide()
                                $('.searchCons').hide()
                                $('.dggbDengSerTitle').removeClass('dggbDengSerTitlemouse')
                                $('.searchinputop .text1').val('')
                            } else {
                                $('.searchLine').hide()
                                $('.searchCons').hide()
                            }
                        }
                    } else { }
                } else {
                    $('.closesearch').show()
                    $('.searchLine').show()
                    $('.searchCons').show()
                    $('.serconTitle img').show()
                    $('.searchinputop').css('z-index', '10')
                    $('.serconTitleRight').hide()
                    if ($('.searchinputop .text1').val() === '') {
                        // input没有内容
                        $(this).parent().parent().addClass('dggbDengSerTitlemouse')
                    } else {
                        $('.searchinputop').css('z-index', '1003')
                    }
                    if (!$closesearch.is(e.target) && $closesearch.has(e.target).length === 0) {
                    } else {
                        $('.closesearch').hide()
                        $('.searchLine').hide()
                        $('.searchCons').hide()
                        $(this).parent().parent().removeClass('dggbDengSerTitlemouse')
                        $('.searchinputop .text1').val('')
                    }
                }
            }

        });
        $('a').on('click', function () {
            if ($(this).parent().parent().find('.sercondownUl')) {
                $('.closesearch').hide()
                $('.searchLine').hide()
                $('.searchCons').hide()
                $('.dggbDengSerTitle').removeClass('dggbDengSerTitlemouse')
                $('.headnoindexRight').removeClass('headnoindexRightmouse')
                $('.searchinputop .text1').val('')

                $('.headnoindexRight').css('width', '262px');
                $('.headnoindexRight').css('margin', '0 26px 0 0');
            }
        })
        // 非首页顶部搜索
        $('.headnoindexRight').on('click', function () {
            $('.headnoindexRight').css('width', '980px');
            $('.headnoindexRight').css('margin', '0 26px 0 30px');
            $('.searchCons').show()
            $('.headnoindexRight').addClass('headnoindexRightmouse')
        })
        $(document).on('click', function (e) {
            var $searchCons = $('#searchCons');
            var $noindexsearchinput = $('.noindexsearchinput')
            var $headnoindexRight = $('.headnoindexRight')
            var $sercontopUlli = $('.sercontopUl li')

            if (!$headnoindexRight.is(e.target) && $headnoindexRight.has(e.target).length === 0) {

                if (!$searchCons.is(e.target) && $searchCons.has(e.target).length === 0) {
                    if ($('.searchinputop .text1').length > 0) {
                        if ($('.searchinputop .text1').val().length == 0) {
                            $('.headnoindexRight .searchLine').hide()
                            $('.headnoindexRight .searchCons').hide()
                            $('.headnoindexRight').removeClass('headnoindexRightmouse')
                            $('.searchinputop .text1').val('')
                            $('.headnoindexRight').css('width', '262px');
                            $('.headnoindexRight').css('margin', '0 26px 0 0');
                        } else {
                            $('.headnoindexRight .searchLine').hide()
                            $('.headnoindexRight .searchCons').hide()
                        }
                    }
                } else {

                }
            } else {
                $('.headnoindexRight .searchLine').show()
                $('.headnoindexRight .searchCons').show()
                $('.serconTitle img').show()
                $('.searchinputop').css('z-index', '10')
                $('.serconTitleRight').hide()
                if ($('.searchinputop .text1').val() === '') {
                    // input没有内容
                    $(this).parent().addClass('headnoindexRightmouse')
                } else {
                    $('.searchinputop').css('z-index', '1003')
                }
                if (!$closesearch.is(e.target) && $closesearch.has(e.target).length === 0) {
                } else {
                    $('.headnoindexRight .searchLine').hide()
                    $('.headnoindexRight .searchCons').hide()
                    $('.headnoindexRight').removeClass('headnoindexRightmouse')
                    $('.searchinputop .text1').val('')
                    $('.headnoindexRight').css('width', '262px');
                    $('.headnoindexRight').css('margin', '0 26px 0 0');
                }
            }

            if (!$headnoindexRight.is(e.target) && $headnoindexRight.has(e.target).length === 0) {

                if (!$searchCons.is(e.target) && $searchCons.has(e.target).length === 0) {
                    if ($('.searchinputop .text1').length > 0) {
                        if ($('.searchinputop .text1').val().length == 0) {
                            $('.headnoindexRight .searchLine').hide()
                            $('.headnoindexRight .searchCons').hide()
                            $('.headnoindexRight').removeClass('headnoindexRightmouse')
                            $('.headnoindexRight .text1').val('')
                            $('.headnoindexRight').css('width', '262px');
                            $('.headnoindexRight').css('margin', '0 26px 0 0');
                        } else {
                            $('.headnoindexRight .searchLine').hide()
                            $('.headnoindexRight .searchCons').hide()
                        }
                    }

                } else {

                }
            } else {
                $('.headnoindexRight .searchLine').show()
                $('.headnoindexRight .searchCons').show()
                $('.serconTitle img').show()
                $('.headnoindexRight').css('z-index', '10')
                $('.serconTitleRight').hide()
                if ($('.headnoindexRight .text1').val() === '') {
                    // input没有内容
                    $(this).parent().addClass('headnoindexRightmouse')
                } else {
                    $('.headnoindexRight').css('z-index', '1003')
                }
                if (!$closesearch.is(e.target) && $closesearch.has(e.target).length === 0) {
                } else {
                    $('.headnoindexRight .searchLine').hide()
                    $('.headnoindexRight .searchCons').hide()
                    $('.headnoindexRight').removeClass('headnoindexRightmouse')
                    $('.headnoindexRight .text1').val('')
                    $('.headnoindexRight').css('width', '262px');
                    $('.headnoindexRight').css('margin', '0 26px 0 0');
                }
            }

        });
        $('.searchCons').on('click', function (e) {
            e.stopPropagation(); // 阻止点击事件冒泡到document
        });
        $('.closesearch').click(function () {
            $('.closesearch').hide()
            $('.searchLine').hide()
            $('.searchCons').hide()
            $(this).parent().parent().removeClass('dggbDengSerTitlemouse')
            if ($(this).parent().parent().parent().parent().find('.bkTop').length <= 0) {
                $(this).parent().parent().removeClass('dggbDengSerTitlemouse')
            }
            $('.searchinputop .text1').val('')
            $('.searchinputopbk .text1').val('')
        })
    } else {
        $('.searchinputop').click(function () {
            $('.getMenuSearch').show()
            $('.searchinputop input').blur()
            $('.getMenuSearch .getMenuschTop .text1').focus()
        })
        $('.searchinputopbk').click(function () {
            $('.getMenuSearch').show()
            $('.searchinputopbk input').blur()
            $('.getMenuSearch .getMenuschTop .text1').focus()
        })
        // .searchdownCons .serconTitleRight,.searchdownCons .serconTitle.search img{display: none;}

        $('.schtopleft b').click(function () {
            $('.getMenuSearch').hide()
        })

        $('.getMenuSearch .getMenuschTop .text1').on('input', function () {
            if (!$(this).val()) { // 检查输入框是否为空
                $('.searchdownCons .serconTitleRight').hide()
                $('.getMenuschTop input.text1').css('color', '#A6B0C3')

                $(this).parent().parent().addClass('dggbDengSerTitlemouse')
            } else {
                $('.searchdownCons .serconTitleRight').show()
                $('.getMenuschTop input.text1').css('color', '#000000')

                $(this).parent().parent().removeClass('dggbDengSerTitlemouse')
            }

        });
        $('.schtopright').click(function () {
            $('.searchdownCons .serconTitleRight').hide()
            $('.getMenuschTop input.text1').css('color', '#A6B0C3')
            $('.getMenuschTop input.text1').val('')
            $(this).parent().parent().addClass('dggbDengSerTitlemouse')
        })

    }
    $('.sercondownUl li').mouseover(function () {
        $(this).addClass('checked')
    })
    $('.sercondownUl li').mouseout(function () {
        $(this).removeClass('checked')
    })

    if ($('.searchinputop .text1').val() !== '') {
        // input有内容

    } else {
        // input没有内容

    }
    $('.searchinputop .text1').on('input', function () {
        if (!$(this).val()) { // 检查输入框是否为空
            $('.serconTitleRight').hide()

            $(this).parent().parent().addClass('dggbDengSerTitlemouse')
            $('.searchLine').show()
            $('.searchinputop').css('z-index', '10')
        } else {
            get_search_coin_list(6, 'pc');
        }
    });

    $('.searchinputopbk .text1').on('input', function () {
        if (!$(this).val()) { // 检查输入框是否为空
            $('.serconTitleRight').hide()

            $(this).parent().parent().addClass('dggbDengSerTitlemouse')
            $('.searchLine').show()
            $('.searchinputop').css('z-index', '10')
        } else {
            get_search_wiki_list(6, 'pc');
        }
    });
    //手机版搜索加载
    $('.getMenuschTop .text1').on('input', function () {
        if (!$(this).val()) { // 检查输入框是否为空
            $('.serconTitleRight').hide()

            $(this).parent().parent().addClass('dggbDengSerTitlemouse')
            $('.searchLine').show()
            $('.searchinputop').css('z-index', '10')
        } else {
            get_search_coin_list(6, 'mob');
        }
    });

    //手机版搜索加载
    $('.getMenuschTop .wikitest').on('input', function () {
        if (!$(this).val()) { // 检查输入框是否为空
            $('.serconTitleRight').hide()

            $(this).parent().parent().addClass('dggbDengSerTitlemouse')
            $('.searchLine').show()
            $('.searchinputop').css('z-index', '10')
        } else {
            get_search_wiki_list(6, 'mob');
        }
    });

    $('.serconTitleRightPc').click(function () {
        get_search_coin_list(100, 'pc');
        $('.serconTitleRight').hide();
    })

    $('.serconTitleRightMob').click(function () {
        get_search_coin_list(100, 'mob');
        $('.serconTitleRight').hide();
    })

    function get_search_coin_list(size, device) {
        if (device == 'pc') {
            var search_keyword = $('.searchinputop .text1').val();
        } else {
            var search_keyword = $('.getMenuschTop input.text1').val();
        }
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/index/get_search_coin_list?page=1&size=" + size + '&search_keyword=' + search_keyword + '&doge_language=' + doge_language + '&timestamp=' + timestamp,
            type: 'GET',
            success: function (res) {
                $('.sercontopUl').html(res);
            },
            error: function (error) {
                // 处理错误  
                console.error('Error fetching data: ', error);
            }
        });
        $('.serconTitleRight').show()

        $(this).parent().parent().removeClass('dggbDengSerTitlemouse')
        $('.searchLine').hide()
        $('.searchinputop').css('z-index', '1003')
    }

    function get_search_wiki_list(size, device) {
        if (device == 'pc') {
            var search_keyword = $('.searchinputopbk .text1').val();
        } else {
            var search_keyword = $('.getMenuschTop input.wikitest').val();
        }
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/wiki/get_search_wiki_list?page=1&size=" + size + '&search_keyword=' + search_keyword + '&doge_language=' + doge_language + '&timestamp=' + timestamp,
            type: 'GET',
            success: function (res) {
                if (device == 'pc') {
                    $('.bksearchList').html(res);
                } else {
                    $('.bksearchListweb').html(res);
                }
            },
            error: function (error) {
                // 处理错误  
                console.error('Error fetching data: ', error);
            }
        });
        $('.serconTitleRight').show()

        $(this).parent().parent().removeClass('dggbDengSerTitlemouse')
        $('.searchLine').hide()
        $('.searchinputop').css('z-index', '1003')
    }

    //   login  登录 
    $('.pwdSee').click(function () {
        $(this).toggleClass('pwdShow pwdnotShow')
        if ($(this).parent().find('.passwords').attr('type') == 'password') {
            $(this).parent().find('.passwords').prop('type', 'text');
        } else {
            $(this).parent().find('.passwords').prop('type', 'password');
        }
        // if ($('.rigestBody .passwords').attr('type') == 'password') {
        //     $('.rigestBody .passwords').prop('type', 'text');
        // } else {
        //     $('.rigestBody .passwords').prop('type', 'password');
        // }
        if ($(this).parent().hasClass('newPwddiv')) {
            if ($('.pwdNew .newpwdInput').attr('type') == 'password') {
                $('.pwdNew .newpwdInput').prop('type', 'text');
            } else {
                $('.pwdNew .newpwdInput').prop('type', 'password');
            }
        } else if ($(this).parent().hasClass('againnewPwddiv')) {
            if ($('.pwdNew .againnewpwd').attr('type') == 'password') {
                $('.pwdNew .againnewpwd').prop('type', 'text');
            } else {
                $('.pwdNew .againnewpwd').prop('type', 'password');
            }
        }
    })

    function validateEmail(email) {
        const emailPattern = /^[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*@[a-zA-Z0-9]+([-_.][a-zA-Z0-9]+)*\.[a-zA-Z]{2,}$/;
        return emailPattern.test(email);
    }
    function validatePassword(password) {
        // 验证密码的规则：包含至少一个大写字母、一个小写字母和一个数字，长度在8到16之间
        const regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/;
        return regex.test(password);
    }

    //验证邮箱密码格式是否正确
    $('.lrconLogin').click(function () {
        // let emails = $('.inputsEmail input').val()
        // warAndcurrect($('.lrCons'))
        // if (!validateEmail(emails)) {
        //     accountWarring('邮箱格式错误！')
        //     // alert('邮箱格式错误！')
        //     return;
        // }
        // let pwds = $('.inputsPwd input').val()
        // if (!validatePassword(pwds)) {
        // accountWarring('密码格式错误！至少一个大写字母、一个小写字母和一个数字，长度在8到16之间')
        // alert('密码格式错误！至少一个大写字母、一个小写字母和一个数字，长度在8到16之间')
        // return;
        // }
        // alert('邮箱密码格式正确！')
    })

    //输入框点击样式
    $('.changeShadow').on('focusin', function () {
        $(this).addClass('check')
    }).on('focusout', function () {
        $(this).removeClass('check')
    })

    $('.sendemail-again').click(function () {
        //重新发送邮件
        var email = $('#email').val();
        // var newemail = $('#newemail').val();
        // 这里验证邮箱验证码是否正确
        if (newemail) {
            sendEmail(newemail);
        } else {
            sendEmail(email);
        }
    });

    let targetTime = ''
    let intervalId = 0
    let daojishi = false
    let codeError = false
    if ($('.verifyCodeBody').length > 0) {
        // 显示初始倒计时
        // 设置间隔ID
        // let intervalId = setInterval(updateCountdown, 1000);
        // targetTime = new Date().getTime() + 60 * 1000 //当前时间
        // setCookie('targetTime', targetTime, 1);
        // updateCountdown();
        // 重新获取验证码   verifycode-again

    }
    $('.verifycode-again').click(function () {
        accountLayuiInit();
        // 设置目标时间（这里59秒）
        // targetTime = new Date().getTime() + 60 * 1000; // 当前时间
        // setCookie('targetTime', targetTime, 1);
        // let intervalNum = 0
        // updateCountdown()
        // intervalId = setInterval(updateCountdown, 1000);
    })
    // 更新倒计时函数
    function updateCountdown() {
        var currentTime = new Date().getTime();
        let targetTime = getCookie('targetTime');
        var timeLeft = targetTime - currentTime;
        // console.log(timeLeft);

        // if (timeLeft < 0) {
        //     targetTime = new Date().getTime() + 60 * 1000 //当前时间
        //     setCookie('targetTime', targetTime, 1);
        //     clearInterval(intervalId);
        // }

        if ((timeLeft - 3) >= 0) {
            let minutes = Math.floor(((timeLeft - 3) / 1000 / 60) % 60);
            let seconds = Math.floor(((timeLeft - 3) / 1000) % 60);
            // 格式化显示
            document.getElementById('verirfycodetimes').innerText = minutes + ":" + seconds;
            $('.verifycode-time').show()
            $('.verifycode-again').hide()
        } else {
            daojishi = true;
            clearInterval(intervalId);
            document.getElementById('verirfycodetimes').innerText = "00:00";
            $('.verifycode-again').show()
            $('.verifycode-time').hide()
        }
    }

    $(document).on('click', '.lrCons', function () {
        // $('#val-code-input').val('');
        // $("div[name='val-item']").empty();
        // $("div[name='val-item']").removeClass('available')
        $("div[name='val-item']").removeClass('errorCode');

    })
    // $(document).on('click', function(e) {
    //     var $sercontopUlli = $('.val-item')
    //     if(!$sercontopUlli.is(e.target) && $sercontopUlli.has(e.target).length === 0){
    //         if (!$sercontopUlli.is(e.target) && $sercontopUlli.has(e.target).length === 0) {

    //             }else{

    //             }
    //     }

    // })
    // 账号安全 弹层 初始化
    function accountLayuiInit() {
        // console.log(accountWarringTimeout)
        // console.log(accountCurrectTimeout)
        // 重置验证码输入框
        $('#val-code-input').val('');
        $("div[name='val-item']").empty();
        $("div[name='val-item']").removeClass('available')
        $("div[name='val-item']").removeClass('errorCode');
        $(".newEmailsinput").val('');
        $(".newpwdInput").val('');
        $(".againnewpwd").val('');
        // $(".securityCode").css('margin','25px 0')
        // $('.accountlayCon .lrconCreate').css('margin','0 33px 33px 33px')
        clearAllTimeout();
        closeAllLayer();
    }
    // 清除定时器
    function clearAllTimeout() {
        clearTimeout(accountWarringTimeout)
        clearTimeout(accountCurrectTimeout)
    }
    //关闭所有 提示
    function closeAllLayer() {
        $('.correct').hide()
        $('.warring').hide()
    }
    // 输入错误 输入框 改颜色
    function warnChangeinput() {
        $('.newEmails').addClass('inputWarn')
        setTimeout("$('.newEmails').removeClass('inputWarn')", 3000)
    }

    // 警告 成功弹窗
    function warAndcurrect(dom) {

        var domTop = Math.ceil(dom.offset().top)
        var domLeft = Math.ceil(dom.offset().left)
        var domInnerwidth = Math.ceil(dom.innerWidth())
        var warAdnCorrwidth = Math.ceil($('#warring').innerWidth())
        var warAdnCorrheight = Math.ceil($('#warring').innerHeight())
        if (dom.find('.titles').length > 0) { // 修改邮箱 修改密码操作
            var titleTop = Math.ceil(dom.find('.titles').offset().top)
        } else { // 登录验证码
            var titleTop = domTop
        }
        if (windowWidth <= 1024) {
            $('#warring').css('top', (titleTop - warAdnCorrheight) / 2)
            $('#warring').css('left', Math.ceil(((windowWidth - warAdnCorrwidth) / 2) + 10))
            $('#correct').css('top', (titleTop - warAdnCorrheight) / 2)
            $('#correct').css('left', Math.ceil(((windowWidth - warAdnCorrwidth) / 2) + 10))
        } else {
            $('#warring').css('top', (titleTop - warAdnCorrheight) / 2)
            $('#warring').css('left', Math.ceil((domInnerwidth / 2) + domLeft) - (warAdnCorrwidth / 2))
            $('#correct').css('top', (titleTop - warAdnCorrheight) / 2)
            $('#correct').css('left', Math.ceil((domInnerwidth / 2) + domLeft) - (warAdnCorrwidth / 2))
        }
    }



    function countdown(targetDate) {
        const target = new Date(targetDate).getTime(); // 目标时间的时间戳
        const interval = setInterval(() => {
            const now = new Date().getTime(); // 当前时间的时间戳
            const distance = target - now; // 时间差
            const days = Math.floor(distance / (1000 * 60 * 60 * 24));
            const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
            const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
            const seconds = Math.floor((distance % (1000 * 60)) / 1000);
            // 更新倒计时显示
            // document.getElementById("countdown").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s ";
            if (distance < 0) {
                clearInterval(interval);
                // document.getElementById("countdown").innerHTML = "EXPIRED";
            }
        }, 1000);
    }
    //Demo
    layui.use('form', function () {
        var form = layui.form;

        //监听提交
        form.on('submit(formDemo)', function (data) {
            layer.msg(JSON.stringify(data.field));
            return false;
        });
    });
    var clipboardData1 = null; //复制粘贴验证码

    if ($('.securityCode').length > 0) {
        // var vCode = new VerifyCode()
        var activeIndexs = 0
        var verifycodelen = 0

        // vCode.init(() => {
        //   verifycodelen = vCode.passWord.join('')
        //   if(verifycodelen.length == 6){
        //     codeError = true
        //   }
        // })
        function VerifyCode() {
            this.domCont = null
            this.spans = []
            this.passWord = []
            this.activeIndex = 0

            this.initDomSpans = () => {
                this.domCont = document.querySelector('#securityCode')
                this.spans = this.domCont.getElementsByTagName('span')
                return this
            }
            this.clear = function () {
                this.passWord.length = 0
                this.activeIndex = 0
                let { spans } = this
                for (var i = 0, len = spans.length; i < len; i++) {
                    spans[i].setAttribute('contenteditable', i == 0 ? true : false)
                    spans[i].innerHTML = ''
                }
            }
            // 监测验证码输入
            this.init = function (cb) {
                let { spans, passWord, domCont } = this.initDomSpans()
                //   spans[0].focus()
                domCont.addEventListener('click', e => {
                    let acIndex = this.activeIndex !== 6 ? this.activeIndex : 5
                    spans[acIndex].focus()
                })
                // 监测输入
                domCont.addEventListener('keypress', e => {
                    123456
                    if (e.target.tagName.toLowerCase() === 'span') {
                        // clipboardData1 = e.originalEvent.clipboardData.getData('text');

                        // console.log(e.charCode)
                        // console.log(clipboardData1)
                        e.preventDefault()
                        if (e.target.innerHTML.length === 0 && this.activeIndex < spans.length && e.keyCode !== 8) {
                            var k = String.fromCharCode(e.charCode)
                            if (/\d/.test(k)) {
                                if (this.activeIndex !== spans.length - 1) {
                                    this.go(this.activeIndex + 1)
                                }
                                passWord.push(k)
                                spans[this.activeIndex].innerHTML = k

                                this.activeIndex++
                                activeIndexs++

                                cb()
                            } else {
                                alert('请输入数字')
                            }
                        }
                    }
                }, false)
                // 中文输入法 监测
                domCont.addEventListener('compositionend', e => {
                    if (e.charCode == undefined) {
                        alert('请输入数字')
                        spans[this.activeIndex].innerHTML = ''
                    }
                })
                domCont.addEventListener('keyup', e => {
                    e = e || window.event
                    if (e.keyCode === 8) {
                        if (this.activeIndex > 0) {
                            this.activeIndex--
                            activeIndexs--
                            this.back(this.activeIndex)
                        }
                    }
                }, false)
            }

            this.go = function (index) {
                let { spans } = this
                for (var i = 0, len = spans.length; i < len; i++) {
                    spans[i].setAttribute('contenteditable', i == index ? true : false)
                }
                spans[index].focus()
                //   el = spans[index]; // jquery 对象转dom对象  
                // el.focus();
                // var range = document.createRange();
                // range.selectNodeContents(el);
                // range.collapse(false);
                // var sel = window.getSelection();

                // sel.removeAllRanges();
                // sel.addRange(range);
            }
            this.back = index => {
                let { spans, passWord } = this
                if (index >= 0 && index < spans.length) {
                    for (var i = 0, len = spans.length; i < len; i++) {
                        spans[i].setAttribute('contenteditable', i == index ? true : false)
                    }
                    spans[index].innerHTML = ''
                    spans[index].focus()
                    passWord.pop()
                }
            }
        }
    }


    // next step  监测验证码是否输入完全
    $('.securicodebtn').click(function () {
        let length = Math.floor(Math.log10(activeIndexs)) + 1;
        if (activeIndexs == 0) {
            alert('请输入验证码1')
            return;
        }
        if (activeIndexs != 6) {
            alert('请输入验证码2')
        }
    })

    $('.lrconCreate').click(function () {
        let doms = ''
        let classs = ''
        if ($(this).data('id')) {
            classs = $(this).data('id').split("-")
            doms = $('.' + classs[0] + ' .lrCons')
        } else {
            doms = $('.lrCons')
        }
        warAndcurrect(doms)
    })

    $('.accountLaybtn').click(function () {
        $('.pwduploading').addClass('showUpload');
        $('.lrconCreate').addClass('noclick');
        $('.verifycode-again').hide();
        $('.verifycode-time').show();
        document.getElementById('verirfycodetimes').innerText = "01:00";

        if (windowWidth <= 1024) {  //iPad  web 
            $('.layuiDivaccount').show()
            $('.layuiDivaccount').addClass('weblayuiDivaccount')
            $('.accountlayCon').addClass('accountlayConWeb')
            var fixedElement = $('.accountlayCondiv'); // 获取layer位置
            if ($(this).hasClass('accountChange')) {
                nowlayerType = 'email'
                $('.emailTitle').show()
                $('.pwdTitle').hide()
                //账号 密码修改
            } else if ($(this).hasClass('accountChangepwd')) {
                nowlayerType = 'pwd'
            }
            warAndcurrect(fixedElement)
        } else {
            $('.layuiDivaccount').removeClass('weblayuiDivaccount')
            $('.accountlayCon').removeClass('accountlayConWeb')
            layerIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: false,
                shadeClose: false,
                area: ['497px'],
                // maxHeight:heights + 'px',
                offset: '',
                scrollbar: true,
                content: $('#layuiDivaccount') //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
            });
            var email = $('#email').val();
            sendEmail(email);
            // 账号 邮箱修改
            if ($(this).hasClass('accountChange')) {
                nowlayerType = 'email'
                $('.emailTitle').show()
                $('.pwdTitle').hide()
                //账号 密码修改
            } else if ($(this).hasClass('accountChangepwd')) {
                nowlayerType = 'pwd'
            }
            var fixedElement = $('#layuiDivaccount').parent().parent(); // 获取layer位置
            var domWidth = Math.ceil(fixedElement.css('width').slice(0, -2))
            var domLeft = Math.ceil(fixedElement.css('left').slice(0, -2))
            var domTop = Math.ceil(fixedElement.css('top').slice(0, -2))
            $(valCodeInput).focus();
            $(valCodeItems[0]).addClass('available');
            $('#warring').css('top', domTop - 20 - 64)
            $('#warring').css('left', domLeft + Math.ceil(((domWidth - 368) / 2)))
            $('#correct').css('top', domTop - 20 - 64)
            $('#correct').css('left', domLeft + Math.ceil(((domWidth - 368) / 2)))

        }
        // let intervalId = setInterval(updateCountdown, 1000);
        // let targetTime = getCookie('targetTime');
        // if (targetTime - (new Date().getTime()) <= 0) {
        //     targetTime = new Date().getTime() + 60 * 1000 //当前时间
        // }
        // setCookie('targetTime', targetTime, 1);
        // updateCountdown();
        $('#layuiDivaccount').parent().css('overflow-y', 'hidden')
    })

    function sendEmail(email) {
        
        accountVerifyCode = false;
        $('.lrconCreate').addClass('noclick');
        $('.lrconCreate').prop('disabled', true);

        var logemail = replaceEmailMiddleChars(email);
        $('.logemail').text(logemail);
        var timestamp = new Date().getTime();
        $('.pwduploading').addClass('showUpload');
        $.ajax({
            url: "/index/user/forgetpwd_send_email?doge_language=" + doge_language + '&timestamp=' + timestamp,
            type: 'POST',
            data: {
                'email': email,
            },
            dataType: 'json',
            success: function (res) {
                if (res.code) {
                    accountCurrect(res.msg);
                    // var currentTime = new Date().getTime();
                    // let targetTime = getCookie('targetTime');
                    // var timeLeft = targetTime - currentTime;
                    // if (timeLeft < 0) {
                    //     targetTime = new Date().getTime() + 60 * 1000 //当前时间
                    //     setCookie('targetTime', targetTime, 1);
                    // }

                    $('.verifycode-again').hide();
                    $('.verifycode-time').show();
                    document.getElementById('verirfycodetimes').innerText = "01:00";

                    targetTime = new Date().getTime() + 60 * 1000 //当前时间
                    setCookie('targetTime', targetTime, 1);
                    intervalId = setInterval(updateCountdown, 1000);
                } else {
                    $('.verifycode-again').show();
                    $('.verifycode-time').hide();
                    deleteCookie('targetTime');
                    accountWarring(res.msg);
                }
                $('.pwduploading').removeClass('showUpload');
            },
            error: function (error) {
                // console.error('Error fetching data: ', error);
            }
        });
    }

    function checkEmailCpatcha(email, captcha) {
        $('.lrconCreate').addClass('noclick');
        $('.pwduploading').addClass('showUpload');
        var timestamp = new Date().getTime();
        $.ajax({
            url: "/index/user/forgetpwd_check_captcha?doge_language=" + doge_language + '&timestamp=' + timestamp,
            type: 'POST',
            data: {
                'email': email,
                'captcha': captcha,
            },
            dataType: 'json',
            success: function (res) {
                if (res.code) {
                    accountVerifyCode = true
                    accountCurrect(res.msg)
                    $('.lrconCreate').removeClass('noclick');
                    $('.lrconCreate').prop('disabled', false);
                } else {
                    accountWarring(res.msg)
                    accountVerifyCode = false
                    $(valCodeItems).addClass('errorCode');
                    setTimeout(function () {
                        accountLayuiInit()
                    }, 3000)
                }
                $('.pwduploading').removeClass('showUpload');
            },
            error: function (error) {
                return false;
                // console.error('Error fetching data: ', error);
            }
        });
    }
    $(document).on("click", '.accountlayCon .lrconTop b', function () {
        if ($('.personalBody')) {
            $('.emailVerifycode').show()
            $('.emailNew').hide()
            $('.pwdNew').hide()
            $('.emaliSuccess').hide()
            $('.lrconCreate.verifycodeNext').removeClass('newemialCode')
            accountLayuiInit()
            layer.close(layerIndex)
            if (windowWidth <= 1024) {  //iPad  web 
                $('.layuiDivaccount').hide()
            } else {

            }
        }
    })

    $('#val-code-input').on('paste', function (e) {
        // 阻止默认行为
        e.preventDefault();
        // 获取剪贴板中的数据
        var clipboardData = e.originalEvent.clipboardData || window.clipboardData;
        var verificationCode = clipboardData.getData('text');
        valCodeInput.focus();
        $('#val-code-input').val(verificationCode)
        // console.log($('#val-code-input').val())
        //这里验证验证码
        if (valCodeInput.val().length == 6) {
            var captcha = valCodeInput.val();
            var email = $('#email').val();
            // var newemail = $('#newemail').val();
            // 这里验证邮箱验证码是否正确
            if (newemail) {
                checkEmailCpatcha(newemail, captcha);
            } else {
                checkEmailCpatcha(email, captcha);
            }

            // 这里验证密码是否正确
            // if (valCodeInput.val() == '888888') {
            //     accountVerifyCode = true
            //     accountCurrect('验证码正确')
            //     $('.lrconCreate').removeClass('noclick');
            //     $('.lrconCreate').prop('disabled', false);
            // } else {
            //     accountWarring('验证码错误')
            //     accountVerifyCode = false
            //     $(valCodeItems).addClass('errorCode');
            //     setTimeout(function(){
            //         accountLayuiInit()
            //     },3000)
            // }
        } else if (valCodeInput.val().length < 6) {
            $(this).prop('disabled', false);
        } else {
            // 超出长度截取前六位
            valCodeInput.val($(this).val().substring(0, 6))
        }

        valCodeLength = valCodeInput.val().length;
        $.each(verificationCode, function (index, value) {
            // 对获取到的数字进行操作
            $(valCodeItems).removeClass('available');
            $(valCodeItems[index]).addClass('available');
            $(valCodeItems[index]).text(value);
        });
    });
    // 点击获取验证码或点击第一个数字输入框时获取焦点,添加available类样式
    $(".val-box div").on("click", function () {
        if ($(".val-box").find(".available").length < 1) {
            $(valCodeInput).focus();
            $(valCodeItems[0]).addClass('available');
        }
    })

    // 当我们点四个小格的时候，会把焦点放在input输入框中
    $('#val-box').on('click', function () {
        if ($(".val-box").find(".available").length == 1) {
            valCodeInput.focus();
        }
        warAndcurrect($(this).closest('.lrCons'))
    })

    // 输入框改变后，把里面的数字取出来，分别显示到四个div中
    valCodeInput.on('input propertychange change', function (e) {
        valCodeLength = valCodeInput.val().length;
        if (valCodeInput.val() && regex.test(valCodeInput.val())) {
            $(valCodeItems).removeClass('available');
            $(valCodeItems[valCodeLength - 1]).addClass('available');
            $(valCodeItems[valCodeLength - 1]).text(valCodeInput.val().substring(valCodeLength - 1, valCodeLength));
        }
    })
    var that = this

    // 删除键，每删除输入框中一个数字valCodeLength计算的长度就会减少一个
    // 就去删除对应小格中的数字，并且移走available类样式
    $(this).on('keyup', function (e) {
        if (e.keyCode === 8) {
            $(valCodeItems[valCodeLength]).text("");
            if (valCodeLength !== 0) {
                $(valCodeItems[valCodeLength]).removeClass('available');
                $(valCodeItems).removeClass('errorCode');
            }
        }
    });
    // 当验证码输入满四个数字的时候，就开始判断是否正确
    $(valCodeInput).on("input propertychange", function () {
        if (valCodeInput.val().length == 6) {
            var captcha = valCodeInput.val();
            var email = $('#email').val();
            // var newemail = $('#newemail').val();
            // 这里验证邮箱验证码是否正确
            // console.log(newemail)
            if (newemail) {
                checkEmailCpatcha(newemail, captcha);
            } else {
                checkEmailCpatcha(email, captcha);
            }

            //这里验证密码是否正确
            // if (valCodeInput.val() == '888888') {
            //     accountVerifyCode = true
            //     accountCurrect('验证码正确')
            //     $('.lrconCreate').removeClass('noclick');
            //     $('.lrconCreate').prop('disabled', false);
            // } else {
            //     accountWarring('验证码错误')
            //     accountVerifyCode = false
            //     $(valCodeItems).addClass('errorCode');
            //     setTimeout(function(){
            //         accountLayuiInit()
            //     },3000)
            // }
        } else if (valCodeInput.val().length < 6) {
            $(this).prop('disabled', false);
        } else {
            // 超出长度截取前六位
            valCodeInput.val($(this).val().substring(0, 6))
        }
    })
    $('#val-code-input').blur(function () {
        // $(valCodeItems).removeClass('available');
    });

    // 1. 修改账号 弹层第一次显示  验证是否正确-跳转输入邮箱
    $('.accountlayCon .verifycodeNext').click(function () {
        $('.accountlayCon .verifycodeNext').addClass('noclick');
        $('.pwduploading').addClass('showUpload');
        $('.accountlayCon .verifycodeNext').prop('disabled', true);
        if (accountVerifyCode == true) {
            // 重置验证码输入框
            accountLayuiInit()
            $('.emailVerifycode').hide()
            if (nowlayerType == 'email') {
                // 监测上一步是新/旧邮箱验证码
                if ($(this).hasClass('newemialCode')) {
                    $('.emailNew').hide()
                    $('.emaliSuccess').show()
                } else {
                    $('.emailNew').show()
                }
            } else {
                $('.emailTitle').hide()
                $('.pwdTitle').show();
                $('.pwdNew').show()
            }
        } else {
            accountWarring()
        }
        $('.pwduploading').removeClass('showUpload');
        $('.accountlayCon .verifycodeNext').prop('disabled', false);
    })
    // 2. 新邮件  跳转-发送验证码
    $('.accountlayCon .newemailNext').click(function () {
        if (nowlayerType == 'email') {
            newemail = $('#newemail').val();
            if (!validateEmail($('.newEmailsinput').val())) {
                accountWarring(email_format_error);
                warnChangeinput()
            } else {
                clearInterval(intervalId);
                deleteCookie('targetTime');
                //发送新邮箱验证码
                sendEmail(newemail);
                
                // targetTime = new Date().getTime() + 60 * 1000 //当前时间
                // setCookie('targetTime', targetTime, 1);
                // updateCountdown()
                $('.emailVerifycode').show()
                $('.emailNew').hide()
                $('.lrconCreate.verifycodeNext').addClass('newemialCode')
                $('.lrconCreate.newemialCode').removeClass('verifycodeNext')
            }
        } else if (nowlayerType == 'pwd') {
            $('.lrconCreate').addClass('noclick');
            $('.pwduploading').addClass('showUpload');
            $('.lrconCreate').prop('disabled', true);
            var email = $('#email').val();
            var newpassword = $('#newpassword').val();
            var renewpassword = $('#renewpassword').val();

            if ($('.newpwdInput').val() === $('.againnewpwd').val()) {
                //这里修改密码提交
                var timestamp = new Date().getTime();
                $.ajax({
                    url: "/index/user/forgetpwd?doge_language=" + doge_language + '&timestamp=' + timestamp,
                    type: 'POST',
                    data: {
                        'email': email,
                        'newpassword': newpassword,
                        'renewpassword': renewpassword,
                    },
                    dataType: 'json',
                    success: function (res) {
                        if (res.code) {
                            accountCurrect(res.msg);
                            $('.pwdNew').hide()
                            $('.emaliSuccess').show()
                            $('.emailchangeSuccess').hide()
                            $('.pwdchangeSuccess').show()
                            accountLayuiInit();
                            clearInterval(intervalId);
                            deleteCookie('targetTime');
                        } else {
                            accountWarring(res.msg);
                        }
                        $('.pwduploading').removeClass('showUpload');
                        $('.lrconCreate').removeClass('noclick');
                        $('.lrconCreate').prop('disabled', false);
                    },
                    error: function (error) {
                        // console.error('Error fetching data: ', error);
                    }
                });

            } else {
                accountWarring(the_two_password_inputs_are_inconsistent);
                $('.pwduploading').removeClass('showUpload');
                $('.lrconCreate').removeClass('noclick');
                $('.lrconCreate').prop('disabled', false);
            }
        }
    })

    // 3. 新邮箱验证码正确
    $(document).on('click', '.accountlayCon .newemialCode', function () {
        $('.accountlayCon .newemialCode').addClass('noclick');
        $('.accountlayCon .newemialCode').prop('disabled', false);
        // var captcha = valCodeInput.val();
        // var email = $('#email').val();
        // var newemail = $('#newemail').val();
        // if (newemail) {
        //     checkEmailCpatcha(newemail, captcha);
        // } else {
        //     checkEmailCpatcha(email, captcha);
        // }
        if (accountVerifyCode) {
            var timestamp = new Date().getTime();
            $.ajax({
                url: "/api/user/profile?doge_language=" + doge_language + '&timestamp=' + timestamp,
                type: 'POST',
                data: {
                    'email': newemail,
                },
                dataType: 'json',
                success: function (res) {
                    if (res.code) {
                        $('.emailVerifycode').hide()
                        $('.emailNew').hide()
                        $('.emaliSuccess').show()
                        accountLayuiInit();
                        clearInterval(intervalId);
                        deleteCookie('targetTime');
                        // window.location.reload();
                    }
                },
                error: function (error) {
                }
            });
        }
    })



    $('.accountlayCon .Closure').click(function () {
        accountLayuiInit()
        $('.emailVerifycode').show()
        $('.emailNew').hide()
        $('.emaliSuccess').hide()
        $('.lrconCreate.verifycodeNext').removeClass('newemialCode')
        if (windowWidth <= 1024) {  //iPad  web 
            $('.layuiDivaccount').hide()
        } else {
            $('.layuiDivaccount').show()
        }
        layer.close(layerIndex)
        window.location.reload();
    })

    setInterval(function () {
        $('.width3.blue').addClass('red')
        $('.width3.blue').removeClass('blue')
    }, 3000)
    $('.avatarDiv').mouseover(function () {
        $('.avaSelect').show()
    })
    $('.avatarDiv').mouseout(function () {
        $('.avaSelect').hide()
    })


    $('.coloridiv').mouseover(function () {
        $('.coloridivnod').show()
    })
    $('.coloridiv').mouseout(function () {
        $('.coloridivnod').hide()
    })

})

// 邮箱验证 错误提示
function accountWarring(msg) {
    clearTimeout(accountCurrectTimeout);
    $('.correct').hide();

    clearTimeout(accountWarringTimeout);
    $('.warring p').html(msg);
    $('.warring').show();
    accountWarringTimeout = setTimeout("$('.warring').hide()", 5000);
}
// 邮箱验证 正确提示
function accountCurrect(msg) {
    clearTimeout(accountWarringTimeout);
    $('.warring').hide();

    clearTimeout(accountCurrectTimeout);
    $('.correct p').html(msg);
    $('.correct').show();
    accountCurrectTimeout = setTimeout("$('.correct').hide()", 5000);
}

function replaceEmailMiddleChars(email) {
    // 分割邮箱为用户名和域名两部分
    const [username, domain] = email.split('@');

    // 如果用户名长度小于5，则无法替换中间四个字符（至少需要8个字符才能替换中间四个）  
    if (username.length < 5) {
        return email; // 或者返回一些错误消息  
    }

    // 替换中间四个字符为****  
    // 注意：如果用户名长度为8，我们替换第2到第5个字符；  
    // 如果用户名更长，我们替换从第(长度/2 - 2)到第(长度/2 + 1)的字符（向上取整）  
    // 这里为了简化，我们假设总是替换第2到第5个字符（适用于大部分情况）  
    const start = 1; // 索引从0开始，所以第2个字符的索引是1  
    const end = 5; // 替换到第5个字符（不包括）  

    // 拼接新的用户名部分  
    let newUsername = username.slice(0, start) + '****' + username.slice(end);

    // 返回新的邮箱地址  
    return newUsername + '@' + domain;
}

function decimal(number, dot = false, len = false) {
    var floatnumber = parseFloat(number);
    if (floatnumber > 1) {
        number = floatnumber.toFixed(2);
        if (len) {
            this.pricelen = number.toString().length;
        }
        return number;
    } else if (floatnumber < 1) {
        let numberString = number.toString(); // 将数字转换为字符串
        // console.log('numberString',numberString)
        let p = 0;
        let newnum = '';
        let no = false;
        for (let i = 0; i < numberString.length; i++) {
            if (p <= 2) {
                if (numberString[i] != '0' && numberString[i] != '.') {
                    no = true;
                }
                if (no) {
                    p++;
                }
                newnum += numberString[i];
            }
        }
        if (len) {
            this.pricelen = newnum.toString().length;
        }
        if (dot) {
            //0.000000098
            newnum = newnum.replace(".000000000000", ".0...0");
            newnum = newnum.replace(".00000000000", ".0...0");
            newnum = newnum.replace(".0000000000", ".0...0");
            newnum = newnum.replace(".000000000", ".0...0");
            newnum = newnum.replace(".00000000", ".0...0");
            newnum = newnum.replace(".0000000", ".0...0");
            newnum = newnum.replace(".000000", ".0...0");
        }
        // console.log('newnum',newnum)
        return newnum;
    } else {
        return '0.00';
    }


}