var basic={form:'Erlo',err:{ok:'确认',cl:'取消',tit:'系统提示',reset:'重新请求',sx:'刷新页面',suc:'操作成功',fail:'服务器响应失败',maxtime:'【处理数据过大，请等待】'},load:'erloLoad',email:'lj_f123@126.com',www:'//www.deyuad.com/',loadimg:'style/img/load.gif',path:'/',version:'2.4'},ljTimes,nophone=['passwd','old','set','sq'],fdata=[];
var ue;
$(function(){
    /*****************************************************/
    /*****************************************************/

    $(document).on('keydown',function(e){
        let keyCode = e.keyCode || e.which || e.charCode;
        if(keyCode===13 || keyCode ===32){
            if($('.alertSure').length>0){
                $('.alertSure').click();return false;
            }
        }else{
            // if($('body').hasClass('debug')){
            //     return true;
            // }
            // let ctrlKey = e.ctrlKey || e.metaKey;
            // if(ctrlKey && $.inArray(keyCode,[85,83])>-1){//源码、保存
            //     return false;
            // }
            // if(e.keyCode===123){//F12
            //     return false;
            // }
        }
    });
    $(document).on('click','.ljImg',function(){
        var html='<img src="'+$(this).attr('src')+'">';
        alertLj(html,{img:true});
    })
    $(document).on('click','.ljSub',function(){
        $(this).parents('form').submit();
    })
    $('.hcodeImg').click(function(){
        $(this).show();
        $(this).attr('src',$(this).data('src')+'&t='+Math.floor(Math.random()*100000+1))
    })
    $('.hcodeForm input').focus(function(){
        if(!$('.hcodeImg').attr('src')){
            $('.hcodeImg').click();
        }
    })
    $(document).on('submit','.ljForm',function(){
        var obj=$(this),data=obj.data();
        if(obj.attr('action'))data.action=obj.attr('action');
        if(obj.attr('fun')){
            return false;
        }
        data=getFormDataa(obj,data);
        if(!data)return false;
        ajaxForm(obj,data,function(msg){
            if(msg && msg.error=='0'){
                if(msg.url){
                    if(msg.url=='/vip' && obj.attr('url')){
                        window.location.href=obj.attr('url');
                    }else{
                        window.location.href=msg.url;
                    }
                }else{
                    if(obj.attr('ourl'))
                    alertLj(msg.html?msg.html:basic.err.suc,{click:'window.location.href=\''+obj.attr('ourl')+'\';'});
                    else
                    alertLj(msg.html?msg.html:basic.err.suc,{click:'window.location.reload();'});
                }
            }else{
                alertLj(msg?(msg.html?msg.html:basic.err.fail):basic.err.fail);
                obj.removeClass(basic.load);
                if(obj.find('.codeClick').length>0)obj.find('.codeClick').click();
            }
        },false,function(){
            alertLj(basic.err.fail)
        })
        return false;
    });
    var srcs=[],wx=$('meta[name="wx"]').length>0?$('meta[name="wx"]').attr('content'):'';
    $('.ljimgshow img').each(function(){
        srcs.push(wx+$(this).attr('src'))
    })
    $('.ljimgshow img').click(function(){
        var src=$(this).attr('src'),img='<img src="'+src+'" style="max-width:100%;">';
        wx=false;
        if(wx){
              var n=$(this).index();
              WeixinJSBridge.invoke('imagePreview', {
                'current' : n,
                'urls' : srcs
            });
        }else{
            var box='<div class="boxlj" style="z-index:2;position:fixed;top:0;left:0;background:rgba(0,0,0,.5);width:100vw;height:100vh;text-align:center;padding:20px 0;"><div style="/*top:30%;transform: translateY(-50%);position: relative;*/display: flex;align-items: center;justify-content: center;height: 100%;">'+img+'</div><a href="javascript:" style="display:block;text-align:center;line-height:35px;color:#fff;position:fixed;bottom:0;left:0;width:100%">关闭</a></div>';
            $('body').append(box);
        }

    })
})
function ajaxForm(obj,data,suc,bef,err){//异步请求
    if($('meta[name="web"]').length>0)data['ljweb']=true;
    if(obj.hasClass(basic.load))return false;
    $.ajax({
        type:'post',data:data,dataType:data.__?'text':'json',beforeSend:function(){
            if(bef)bef();
            obj.addClass(basic.load);
        },error:function(){
            if(err)err();
            obj.removeClass(basic.load);
        },success:function(msg){
            obj.removeClass(basic.load);
            if(data.__ && typeof msg === 'string'){
                try{
                    msg=formDataDe(msg,false,true);
                }catch (e) {
                    try{
                        msg=JSON.parse(msg);
                    }catch (e){
                        // msg={error:1,html:basic.err.fail};
                    }
                }
            }
            if(suc)suc(msg)
        }
    })
}

function getFormDataa(obj,data){
    var e;
    data['sign']=$('meta[name="sign"]').attr('content');
    obj.find('.formValt').each(function(){
        if(data[$(this).attr('name')]){
            data[$(this).attr('name')]+=' - '+$(this).val();
        }else{
            data[$(this).attr('name')]=$(this).val();
        }
    })
    obj.find('.formVal').each(function(){
        if(!e && $(this).attr('nonull') && !$(this).val()){
            if(isNaN($(this).attr('nonull'))){
                e=$(this).attr('nonull');
            }else{
                e=$(this).attr('data-placeholder')?$(this).attr('data-placeholder'):$(this).attr('placeholder');
            }
        }
        if($(this).val()!=$(this).attr('data-placeholder')){
            data[$(this).attr('name')]=$(this).val();
        }
    })
    obj.find('.formVals:checked').each(function(){
        if(data[$(this).attr('name')]){
            data[$(this).attr('name')]+=$(this).val()+',';
        }else{
            data[$(this).attr('name')]=','+$(this).val()+',';
        }
    })
    obj.find('.formValz.on').each(function(){
        if(data[$(this).attr('name')]){
            data[$(this).attr('name')]+=','+$(this).attr('val');
        }else{
            data[$(this).attr('name')]=$(this).attr('val');
        }
    })
    obj.find('.formValLi').each(function(){
        if($(this).find('li.on').length>0){
            data[$(this).attr('name')]=$.trim($(this).find('li.on').text());
        }
    })
    obj.find('.formValc:checked').each(function(){
        data[$(this).attr('name')]=$(this).val();
    })
    if(ue)data['cont']=ue.getContent();
    if(e){
        alertLj(e);
        //alertLj(e+'不能为空');
        return false;
    }
    return {__:formDataEn(JSON.stringify(data),data.__key)};
}
function formDataKey(key){
    if(key)basic.__key=key;
    if(!basic.__key){
        basic.__key=$('meta[name="__key"]').attr('content');
    }
    return basic.__key;
}
//DES加密
function formDataEn(message, key){
    let l = CryptoJS.enc.Utf8.parse(message);
    let e = CryptoJS.enc.Utf8.parse(formDataKey(key));
    let a = CryptoJS.DES.encrypt(l, e, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    })
    return a.toString()+formDataKey(key)  // 此方式返回base64
    // return a.ciphertext.toString() // 返回hex格式的密文
}
//DES解密
function formDataDe(ciphertext, key,json,ckey=false){
    let e = CryptoJS.enc.Utf8.parse(ckey?ckey:formDataKey(key));
    // var WordArray = CryptoJS.enc.Hex.parse(ciphertext);  // 如果text是base64形式，该行注释掉
    // ciphertext = CryptoJS.enc.Base64.stringify(WordArray);  // 如果text是base64形式，该行注释掉
    let a = CryptoJS.DES.decrypt(ciphertext, e, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });
    let r=CryptoJS.enc.Utf8.stringify(a).toString();
    if(json){
        return JSON.parse(r);
    }
    return r;
}

function alertLj(str,obj,ppobj){
    if(ljTimes)clearInterval(ljTimes);
    if($('.alertLjBox').length)$('.alertLjBox').remove();
    if(!obj)obj={};
    if(typeof obj=='string')obj=o(obj);
    if(!obj.title)obj.title=basic.err.tit;
    if(!obj.ok)obj.ok=basic.err.ok;
    if(!obj.c)obj.c=basic.err.cl;
    var pobj=ppobj?ppobj:$('body'),pwobj=ppobj?(ppobj.attr('class')?ppobj:$(window)):$(window);
    var load='<img src="'+basic.path+'style/img/load.gif">',html,close='<a class="alertClose" onclick="alertLjClose()">关闭</a>',title='<div class="alertTitle">'+obj.title+'</div>',sure='<a class="alertSure">'+obj.ok+'</a>',cancel='<a class="alertCancel" onclick="alertLjClose()">'+obj.c+'</a>';
    var handle='<div class="alertHandle">'+sure+cancel+'</div>';
    html='<div class="alertBox">'+str+'</div>';
    html='<div class="alertLj">'+close+title+html+handle+'</div>';
    html='<div class="alertLjBox '+(obj.img?' ljImgBox" onclick="alertLjClose();':'')+'">'+html+'</div>';
    var cssLeft='-'+pwobj.width()+'px',cssTop=0;
    pobj.append(html).find('.alertLj').css({left:cssLeft,top:cssTop});
    if(obj.click){
	   $('.alertLj .alertSure').attr('onclick',obj.click);
    }else{
	   $('.alertLj .alertSure').attr('onclick','alertLjClose()');
    }
    if(obj.noClose)$('.alertLj .alertClose').remove();
    if(!obj.cancel)$('.alertLj .alertCancel').remove();
    if(obj.cancel && obj.cancelClick)$('.alertLj .alertCancel').attr('onclick',obj.cancelClick);
    if(str=='load'){
	   $('.alertLj').addClass('load').find('.alertBox').html(load).append('<span class="ljTimes"> </span>');
	   $('.alertLj .alertClose').remove();
	   ljLoadTimes();
    }
    cssLeft=(pwobj.width()-$(".alertLj").width())/2;
    cssTop=(pwobj.height()-$(".alertLj").height())/2.5+pwobj.scrollTop();
    $('.alertLj').css({left:cssLeft,top:cssTop}).fadeIn(300);
    $('.alertLjBox').height($(document).height());
}
function ljLoadTimes(res){
    var ljI=1;
    ljTimes=setInterval(ljTimesGo,1000);
    function ljTimesGo(){
        if($('.ljTimes').length>0){
            if(ljI>10){
                $('.ljTimes').html((ljI<10?("0"+ljI):ljI)+'s'+(ljI>10?('<br>'+basic.err.maxtime):''));
            }
            ljI++;
        }else{
            clearInterval(ljTimes);
        }
    }
}
function alertLjClose(fun,now){
    if(now) {
        $('.alertLjBox').hide();fun;
    }else{
        $('.alertLjBox').fadeOut(300,function(){
           $(this).remove();fun
        });
    }
}
function errHandle(error){
    if(error.status==810){
	   alertLj(error.responseText,{ok:basic.err.reset,click:'window.location.reload();',cancel:false,noClose:true});
    }else if(error.status==818){
	   alertLj(error.responseText,{ok:basic.err.sx,click:'window.location.reload();',cancel:false,noClose:true});
    }else{
	   alertLj(basic.err.fail)
    }
}
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    exdays=exdays?exdays:1;
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getTime(){
    let currentDate = new Date();
    let year = currentDate.getFullYear();
    let month = ("0" + (currentDate.getMonth() + 1)).slice(-2);
    let day = ("0" + currentDate.getDate()).slice(-2);
    let hour = ("0" + currentDate.getHours()).slice(-2);
    let minute = ("0" + currentDate.getMinutes()).slice(-2);
    let second = ("0" + currentDate.getSeconds()).slice(-2);
    let formattedDate = year + "-" + month + "-" + day;
    let formattedTime = hour + ":" + minute + ":" + second;
    let formattedDateTime = formattedDate + " " + formattedTime;
    return formattedDateTime;
}