klsfct

又惘又怠

页首Html代码

搞一下抽奖代码分析

 

这次研究,主要是有个抽奖机制,我觉得可以利用,

一个是api申请使用抽奖次数

另一个是pid返回中奖信息

在一个是传回json数据,即获奖信息

三处测得均可利用,有意思得自己搞搞

 

 

 

 

 

 

!(function($) {

    //当前域名
    var curDomain = window.location.host;
    var getInfoSucc = false; //判断是否得到用户信息


    shear_go( "我正在参加ADI谁是闯关王等你来战有奖活动,有趣、有料、有奖品等你一起来玩!" , "我正在参加ADI谁是闯关王等你来战有奖活动,有趣、有料、有奖品等你一起来玩!" ,'http://www.elecfans.com/company/adi201907/img/share.png')

    /* 分享到出去的数据及在不同环境的分享操作   */
    function shear_go( title , desc , imgUrl ){

        //在微信中使用微信自己的分享
        var setWeixinShare={};//定义默认的微信分享信息,页面如果要自定义分享,直接更改此变量即可
        var d={
            title: title || "" ,//标题
            desc: desc || "" , //描述
            imgUrl: imgUrl || "http://www.elecfans.com/company/adi201907/img/share.png" ,// 分享图标,默认是logo
            link:'',//链接
            type:'',// 分享类型,music、video或link,不填默认为link
            dataUrl:'',//如果type是music或video,则要提供数据链接,默认为空
            success:'', // 用户确认分享后执行的回调函数
            cancel:''// 用户取消分享后执行的回调函数
        }
        setWeixinShare=$.extend(d,setWeixinShare);
        $.ajax({
            url:"http://www.elecfans.com/app/wechat/index.php?s=Home/ShareConfig/dingtalk&share_url=http://t.elecfans.com/123.html&format=json",
            data:"share_url="+encodeURIComponent(location.href)+"&format=jsonp",
            type:'get',
            dataType:'jsonp',
            success:function(res) {
                if (res.status != "successed") {
                    return false;
                }
                $.getScript('http://g.alicdn.com/dingding/open-develop/1.6.9/dingtalk.js',function(result,status) {

                    if (status != "success") {
                        return false;
                    }

                    var getWxCfg=res.data;
                    dd.config({
                        //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                        agentId:getWxCfg.appId, // 必填,公众号的唯一标识
                        timeStamp:getWxCfg.timestamp, // 必填,生成签名的时间戳
                        nonceStr:getWxCfg.nonceStr, // 必填,生成签名的随机串
                        signature:getWxCfg.signature,// 必填,签名,见附录1
                        jsApiList:['runtime.info', 'biz.contact.choose',
                            'device.notification.confirm', 'device.notification.alert',
                            'device.notification.prompt', 'biz.ding.post',
                            'biz.util.openLink','biz.util.share'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                    });


                });
            }
        });

        if(window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger'){
            $(".bdsharebuttonbox").hide();
            $.ajax({
                url:"http://www.elecfans.com/app/wechat/index.php?s=Home/ShareConfig/index",
                data:"share_url="+encodeURIComponent(location.href)+"&format=jsonp",
                type:'get',
                dataType:'jsonp',
                success:function(res){
                    if(res.status!="successed"){
                        return false;
                    }

                    $.getScript('http://res.wx.qq.com/open/js/jweixin-1.0.0.js',function(result,status){

                        if(status!="success"){
                            return false;
                        }
                        var getWxCfg=res.data;
                        wx.config({
                            //debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                            appId:getWxCfg.appId, // 必填,公众号的唯一标识
                            timestamp:getWxCfg.timestamp, // 必填,生成签名的时间戳
                            nonceStr:getWxCfg.nonceStr, // 必填,生成签名的随机串
                            signature:getWxCfg.signature,// 必填,签名,见附录1
                            jsApiList:['onMenuShareTimeline','onMenuShareAppMessage','onMenuShareQQ','onMenuShareWeibo','onMenuShareQZone'] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                        });

                        wx.ready(function(){

                            //获取“分享到朋友圈”按钮点击状态及自定义分享内容接口
                            wx.onMenuShareTimeline({
                                title: setWeixinShare.title, // 分享标题
                                link: setWeixinShare.link, // 分享链接
                                imgUrl: setWeixinShare.imgUrl, // 分享图标
                                success: function () {
                                    setWeixinShare.success;
                                    // 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
                                    setWeixinShare.cancel;
                                    // 用户取消分享后执行的回调函数
                                }
                            });

                            //获取“分享给朋友”按钮点击状态及自定义分享内容接口
                            wx.onMenuShareAppMessage({
                                title: setWeixinShare.title, // 分享标题
                                desc: setWeixinShare.desc, // 分享描述
                                link: setWeixinShare.link, // 分享链接
                                imgUrl: setWeixinShare.imgUrl, // 分享图标
                                type: setWeixinShare.type, // 分享类型,music、video或link,不填默认为link
                                dataUrl: setWeixinShare.dataUrl, // 如果type是music或video,则要提供数据链接,默认为空
                                success: function () {
                                    setWeixinShare.success;
                                    // 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
                                    setWeixinShare.cancel;
                                    // 用户取消分享后执行的回调函数
                                }
                            });

                            //获取“分享到QQ”按钮点击状态及自定义分享内容接口
                            wx.onMenuShareQQ({
                                title: setWeixinShare.title, // 分享标题
                                desc: setWeixinShare.desc, // 分享描述
                                link: setWeixinShare.link, // 分享链接
                                imgUrl: setWeixinShare.imgUrl, // 分享图标
                                success: function () {
                                    setWeixinShare.success;
                                    // 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
                                    setWeixinShare.cancel;
                                    // 用户取消分享后执行的回调函数
                                }
                            });
                            //获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口
                            wx.onMenuShareWeibo({
                                title: setWeixinShare.title, // 分享标题
                                desc: setWeixinShare.desc, // 分享描述
                                link: setWeixinShare.link, // 分享链接
                                imgUrl: setWeixinShare.imgUrl, // 分享图标
                                success: function () {
                                    setWeixinShare.success;
                                    // 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
                                    setWeixinShare.cancel;
                                    // 用户取消分享后执行的回调函数
                                }
                            });
                            //获取“分享到QQ空间”按钮点击状态及自定义分享内容接口
                            wx.onMenuShareQZone({
                                title: setWeixinShare.title, // 分享标题
                                desc: setWeixinShare.desc, // 分享描述
                                link: setWeixinShare.link, // 分享链接
                                imgUrl: setWeixinShare.imgUrl, // 分享图标
                                success: function () {
                                    setWeixinShare.success;
                                    // 用户确认分享后执行的回调函数
                                },
                                cancel: function () {
                                    setWeixinShare.cancel;
                                    // 用户取消分享后执行的回调函数
                                }
                            });
                        });
                    });
                }

            });
        }else{

            /*百度分享*/
            window._bd_share_config = {
                common : {
                    bdText : title || "" ,//自定义分享内容
                    bdComment: '我正在参加ADI谁是闯关王等你来战有奖活动,有趣、有料、有奖品等你一起来玩!',
                    bdDesc : '',//自定义分享摘要
                    bdUrl : window.location.href,//自定义分享url地址
                    bdPic : imgUrl || ''
                },
                share: {}
            }
            with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
            /*百度分享*/
        }
    }




    /*登录信息*/
    //获得是否登录
    var isLogin = false;
    var userID = "";
    var uID = null; //获得用户ID
    var urlTitle = "";//获得来源
    var showForm = true; //是否显示表单

    /* 抽奖信息 */
    var usedChance = null;//用户已用抽奖次数
    var getChance = 0;//用户获得的抽奖次数
    var nowChange = 0;

    var answerIsGetChance = false;
    var videoIsGetChance = false;
    var isStep = false;   //是否闯关成功

    //设置BBS的域名
    var bbs = window.location.host.split(".");
    bbs[0] = "bbs";
    bbs = bbs.join(".");

    $.get(ElecfansApi_checklogin, function(data, textStatus) {
        if(data != "") {
            isLogin = true;
            var data = JSON.parse(data);
            userID = data.uid;
            getInfo(); //获得用户信息
        }
    });

    function checkLogin() {
        if(!isLogin) {
            $.ssoDialogLogin(); //单点登录
            return false; //弹出登录
        }
        isLogin = true;
        if(!getInfoSucc) {
            getInfo(); //获得用户信息
        }
        return true;
    }

    //获得用户信息
    function getInfo() {
        /*
         * 检查登录
         */
        $.ajax({
            url: "/webapi/user/info",
            type: "get",
            success: function(res) {
                if(res["status"] == "successed") {
                    checkJoin(res)
                } else {
                    //没有登录的情况
                    $.ssoDialogLogin(); //弹出登录窗口
                }
            }
        });
    }

    function getInfoCallback(res){
        var getUser = res["data"]["user"];
        //检查cookie,如果有cookie,则优先调取 cookie内容
        uID = getUser["uid"];
        var getCookie = localStorage.getItem("adi201907_info" + uID);
        if(!!getCookie) {
            //资料齐全,就不显示弹窗口
            showForm = false;
            getCookie = decodeURI(getCookie).split("&"); //先转码汉字,再分割成数组
            for(var i = 0; i < getCookie.length; i++) {
                var getData = getCookie[i].split("=");
                var getName = getData[0];
                var getContent = getData[1];

                //输出
                switch(getName) {
                    case "province":
                        $("[name=province]").val(getContent.replace("省", "")).change(); //
                        break;
                    case "city":
                        $("[name=city]").val(getContent.replace("市", "")).change(); //
                        break;
                    default:
                        $("[name=" + getName.replace(/[\[\]]/g, "") + "]").val(getContent); //循环输出
                        $('[name="' + getName + '"][value="' + getContent + '"]').attr("checked", "checked");
                        break;
                }
            }
        } else {
            $("[name=username]").val(getUser["realname"]); //姓名
            $("[name=mobile]").val(getUser["mobile"]); //手机
            $("[name=email]").val(getUser["email"]); //email
            $("[name=company]").val(getUser["company"]); //公司
            if( getUser["resideprovince"] ){
                $("[name=province]").val(getUser["resideprovince"].replace("省", "")).change(); //
                $("[name=city]").val(getUser["residecity"].replace("市", "")).change(); //
            }
            $("[name=address]").val(getUser["address"]); //地址
        }

        $("#userID").val(uID);
        getInfoSucc = true;
        getStep(uID)
    }


    // 检测是否已经填过表单
    function checkJoin(data){
        $.ajax({
            url: "http://" + bbs + "/topicform/index.php?s=/home/ajaxpost/checkJoin",
            type: "post",
            data: {
                fid: 151,
                uid: uID,
                check: 0,
                product: "已填表单"
            },
            dataType: "jsonp",
            success: function (res) {
                if( res.joined == 1 ){
                    var arr = res.data;
                        delete arr.field5;
                        delete arr.product;
                        delete arr.uid;
                        delete arr.type;
                    var newarr = []
                    for(var i in arr){
                        newarr.push(i + "=" + arr[i])
                    }
                    var setCookieVal = encodeURI(newarr.join("&"));
                    localStorage.setItem("adi201907_info" + uID, setCookieVal);
                    showForm = false;
                }
                getInfoCallback(data)    
            }
        });
    }

    /*表单验证*/
    function check() {
        var getDataArr = $("#submit_form").serializeArray();
        //验证个人信息
        for(var i = 0; i < getDataArr.length; i++) {
            var getVal = getDataArr[i]["value"];
            var getName = getDataArr[i]["name"];
            var errorMsg = null;
            //检查填写是否正确
            if(!$(".jc_price").is(":hidden")) {
                if(getName == 'guessprice' && getVal == "") {
                    errorMsg = "请填写竞猜价格";
                }
            }
            switch(getName) {
                case "username":
                    if(getVal == "") {
                        errorMsg = "请填写姓名";
                    }
                    break;
                case "phone":
                    if(getVal == "") {
                        errorMsg = "请填写手机号码";
                    } else if(!(/^0?(13|15|16|18|14|17)[0-9]{9}$/.test(getVal))) {
                        errorMsg = "手机号码不正确";
                    }
                    break;
                case "email":
                    if(getVal == "") {
                        errorMsg = "请填写邮箱";
                    } else if(!(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/.test(getVal))) {
                        errorMsg = "邮箱格式不正确";
                    }
                    break;
                case "company":
                    if(getVal == "") {
                        errorMsg = "请填写公司名";
                    }
                    break;
                case "department":
                    if(getVal == "") {
                        errorMsg = "请填写部门";
                    }
                    break;
                case "telephone":
                    if(getVal == "") {
                        errorMsg = "请填写座机";
                    }
                    break;
                case "industry":
                    if(getVal == "") {
                        errorMsg = "请填写行业";
                    }
                    break;
                case "profession":
                    if(getVal == "") {
                        errorMsg = "请选择您的职业";
                    }
                    break;
                case "stage":
                    if(getVal == "") {
                        errorMsg = "请选择您的产品阶段";
                    }
                    break;
                case "province":
                    if(getVal == "") {
                        errorMsg = "请选择省份";
                    }
                    break;
                case "city":
                    if(getVal == "") {
                        errorMsg = "请选择市/区";
                    }
                    break;
                default:
                    break;
            }

            if(!!errorMsg) {
                layer.msg(errorMsg);
                var getOffTop = $('[name=' + getName + ']').focus().offset().top;
                return false;
            }

        }
        return true;
    }

    var action = new Object; //定义点击之后的操作

    function submit_form(callback){
        $("#submit_form").on("click", "#form_submit_button", function() {
            //验证用户信息
            if(!check()) {
                $("#form_window").show();
                showForm = true;
                return false;
            }
            //验证通过,发送表单
            $("#form_window").hide();
            if(typeof(action) == "function") {
                action();
            } else {
                sendForm(callback); //直接发送表单
            }

        });
    }

    function sendForm( callback ) {
        $.ajax({
            type: 'POST',
            url: ELECFANS_BBS + "/topicform/index.php?s=/Home/Ajaxpost/handle",
            data: $('#submit_form').serialize() + encodeURI("&product=" + urlTitle),
            dataType: 'jsonp',
            async: false,
            beforeSend: function() {
                if(!check()) {
                    $("#form_window").show();
                    showForm = true;
                    return false;
                }
            },
            success: function(data) {
                if(data.status == 'successed') {
                    //保存用户信息
                    var setUserInfoVal = [];
                    $("#info_inputs [name],.user_info_cookie [name]:checked").each(function(index, element) {
                        var getName = $(element).attr("name");
                        var getVal = $(element).val();
                        setUserInfoVal.push(getName + "=" + getVal);
                    });
                    var setCookieVal = encodeURI(setUserInfoVal.join("&"));
                    localStorage.setItem("adi201907_info" + uID, setCookieVal);
                    getStep(uID, function(res){
                        var data = res.data
                        //用户当前在第一步
                        if(Object.getOwnPropertyNames(data).length == 1 && data.step1.length > 0){
                            var str = data.step1.join("");
                            var videoCount = str.split("视频").length - 1;
                            if(videoCount > 0){
                                if(getChance == 0){
                                    updateChance(1)
                                }
                                $('.aside_pc ul>li:lt(1)').addClass('passed')
                                localStorage.setItem('step'+ uID, 1)
                            }
                        }
                        //用户当前在第二步,且点击了三个不一样的视频或下载了资料
                        if(Object.getOwnPropertyNames(data).length > 1 && data.step2.length >= 3){
                            var str = data.step2.join("");
                            var videoCount = str.split("视频").length - 1,
                                fileCount = str.split("资料").length - 1;
                            if(videoCount >= 2 && fileCount >= 1){            //用户看了两次视频并且下载了一次文件
                                if(getChance == 1){
                                    updateChance(1)
                                }
                                $('.aside_pc ul>li:lt(2)').addClass('passed')
                                localStorage.setItem('step'+ uID, 2)
                            }
                        }
                        //用户当前在第三步,且点击了三个不一样的视频或下载了资料
                        if(Object.getOwnPropertyNames(data).length > 2 && data.step3.length >= 3){
                            if(getChance == 2){
                                updateChance(1)
                            }
                            $('.aside_pc ul>li:lt(3)').addClass('passed')
                            localStorage.setItem('step'+ uID, 3)
                        }
                    })
                    if(showForm){
                        layer.open({
                            type: 1,
                            skin: 'lotter_alert run_out', //样式类名
                            area: ["160px", "130px"],
                            closeBtn: 1,
                            shift: 2, //入场动画
                            shadeClose: true, //开启遮罩关闭
                            content: '<big style="margin-top: 40px;font-size:20px;color:#d22222">恭喜提交成功</big> <a class="pop_desc">去闯关</a>'
                        });
                    }
                    showForm = false; //是否显示表单
                    if(typeof(callback) == "function") {
                        callback();
                    }
                } else {
                    if( data.msg == "您已提交该表单!" ){
                        if(typeof(callback) == "function") {
                            callback();
                        }
                    }
                }
            },
            complete: function() {
            }
        });
    }
    //头部hover的样式问题
    $("#website_nav").mouseover(function() {
        $(".wraplist_title").css({
            "color": "#666",
            "background": "#fff"
        })
    }).mouseout(function() {
        $(".wraplist_title").css({
            "color": "",
            "background": ""
        })
    });


    $(".close-dialog").click(function() {
        $("#form_window").hide();
        $("#s_tip_box").hide();
    });


    //监听滚动条
    $(window).scroll(function(e){
        var _top = $(window).scrollTop();
        if( screen.width < 800 ){
            $(".m_floor").each(function(i){
                   var _height = $(this).offset().top + $(this).height();
                   if(_height > _top){
                       $(".m_head li").eq(i).addClass("mh_active").siblings().removeClass("mh_active");
                       return false;
                   }
            });
        }else {
            $(".floor").each(function(i){
                   var _height = $(this).offset().top + $(this).height();
                   if(_height > _top + 500){
                       $(".pc_nav li").eq(i).addClass("ac").siblings().removeClass("ac");
                       return false;
                   }
            });
        }
    });


    /*
     * 视频播放窗口方法
     */
     function alertVideoPlay(videoUrl, title) {
         var content = '';

         if( screen.width > 800 ){
             content = '<div id="video_player"></div>'
         }else{
             content = '<video class="video" width="100%" height="200px" src="'+videoUrl+'" controls="controls"></video>'
         }
         layer.open({
             id: "video_box",
             type: 1,
             title: title.replace("&type=2",""),
             shade: 0,
             area: isMobile ? "100%" : '600px',
             content: content,
             end:function(){
                 player.videoPause()
                 $('video').trigger('pause');
             }
         });
         var videoObject = {
            container: '#video_player',
            variable: 'player',
            autoplay: true,
            html5m3u8: true,
            allowFullScreen: false,
            video: videoUrl
        };
         var player = new ckplayer(videoObject);
        if($(".video")){
            $(".video").trigger('play');
        }
     }



    // 资料下载前的判断限制
    $(".is_allow").each(function(){
        $(this).click(function(){
            sendGA(urlTitle);
            if( checkLogin() ){
                var this_herf = $(this).attr("data-href"),
                    this_video = $(this).attr("data-video"),
                    this_title = $(this).attr("data-title");
                var type = ""     //第几步

                switch (+$(this).parents('.step_box').attr("data-step")) {
                    case 1:
                        type = 1
                        break;
                    case 2:
                        type = 2
                        break;
                    case 3:
                        type = 3
                        break;
                    default:
                        break;
                }
                if(this_herf){
                    urlTitle ='资料-' + this_title + "&type=" + type;
                }else{
                    urlTitle ='视频-' + this_title + "&type=" + type;
                }

                var step = +localStorage.getItem("step" + uID);
                //用户只闯关到了第一步,但是点击了第三步 type: 当前第几步
                if((step == 1 & type == 3) || (!step && type != 1) && !isStep){
                    layer.open({
                        type: 1,
                        skin: 'lotter_alert run_out', //样式类名
                        area: ["160px", "130px"],
                        closeBtn: 1,
                        shift: 2, //入场动画
                        shadeClose: true, //开启遮罩关闭
                        content: '<big style="margin-top: 40px;">请按顺序闯关,不要跳级哦</big> <a class="pop_desc">去闯关</a>'
                    });
                    return false;
                }
                sendForm(function(){
                    if(this_herf){
                        window.open(this_herf);
                    }else if(this_video){
                        alertVideoPlay(this_video,urlTitle);
                    }
                })
                submit_form(function(){
                    if(this_herf){
                        window.open(this_herf);
                    }else if(this_video){
                        alertVideoPlay(this_video,urlTitle);
                    }
                })


            }
        })
    })

    //答题
    // $(".a_btn").click(function(){
    //     var isp = 0;
    //     var cval = [];
    //     var c_val = [];
    //     var answerArr = ['A','F','F'];
    //     var num_right = 1;
    //     if( checkLogin() ){
 //            $(".a_list li").each(function(index){
    //             var val = $('input[name="'+(index/1+1/1)+'"]:checked').val();
    //             var one_c = $(this).find('input[name=1]')
    //             if( index < 3 && val == answerArr[index] ){
    //                 num_right ++
 //                }
    //             if( one_c.length > 0 ){
    //                 one_c.each(function() {
    //                     if (this.checked) {
    //                         if( $(this).val() == 'I' ){
    //                             $(this).val('I'+ $(".c_wVal").val())
    //                         }
    //                         c_val.push($(this).val())
    //                     }
    //                 });
    //             }
    //             if(!val){
    //                 layer.msg("全部答完才能提交哦!");
    //             }else{
    //                 cval.push(val)
    //                 isp ++
    //             }
    //         })
 //            cval[0] = c_val.join('-');
 //            urlTitle = $(this).attr("data-title")+'&type=3&check=1&answer='+cval.join("|");
 //            if( isp == 4 ){
 //                if(  c_val.indexOf("I") != -1  && $(".c_wVal").val() == '' ){
 //                    layer.msg("请填写!");
    //                 $(".c_wVal").focus();
 //                }else{
    //                 sendForm(function(r){
    //                     _submitAfter();
    //                 });
    //                 function _submitAfter(){
    //                     $(".a_btn").attr("disabled","disabled");
    //                     $(".a_btn").css({
    //                         'background':'#ccc'
    //                     })
    //                     $(".a_btn").text("已提交");
    //                     var tiplayer = layer.open({
    //                         type: 1,
    //                         skin: 'lotter_alert no_chance', //样式类名
    //                         shift: 2, //入场动画
    //                         shadeClose: true, //开启遮罩关闭
    //                         content: '</br><big>提交成功</big></br><span>恭喜答对'+num_right+'题</span>'
    //                     })
    //                 }
 //                }
 //            }
 //        }
    // })

    //更新机会
    function updateChance(num){
        $.ajax({
            url: "/webapi/lottery/updateChance",
            type: "post",
            data: "prizetype=adi201907&chancename="+ Math.random() +"&num="+num,
            success: function (res) {
                getLotteryChance()
            }
        });
    }


    // 获取步骤
    function getStep(uid, callback){
        $.ajax({
            url: "http://" + bbs + "/topicform/index.php?s=/Home/ajaxpost/checkAdi",
            type: "get",
            dataType: "jsonp",
            data: {
                fid: 151,
                uid: uid
            },
            success: function (res) {
                if(res.status === "success"){
                    var data = res.data
                    if(typeof(callback) == "function") {
                        callback(res);
                    }
                    var step = Object.getOwnPropertyNames(data).length;   //用户闯到第几关
                    if(step == 1 && data.step1 && data.step1.length > 0){
                        var str = data.step1.join("");
                        var videoCount = str.split("视频").length - 1;
                        if(videoCount > 0){
                            $('.aside_pc ul>li:lt(1)').addClass('passed')
                        }
                    }
                    //用户当前在第二步,且点击了两个不一样的视频且下载了资料
                    if(step > 1){
                        if(data.step2.length >= 3){
                            var str = data.step2.join("");
                            var videoCount = str.split("视频").length - 1,
                                fileCount = str.split("资料").length - 1;
                            if(videoCount >= 2 && fileCount >= 1){            //用户看了两次视频并且下载了一次文件
                                $('.aside_pc ul>li:lt(2)').addClass('passed')
                            }
                        } else {
                            $('.aside_pc ul>li:lt(1)').addClass('passed')
                        }
                    }

                    //用户当前在第三步,且点击了三个不一样的视频或下载了资料                        
                    if(step > 2){
                        if(data.step3.length >= 3){
                            $('.aside_pc ul>li:lt(3)').addClass('passed')                        
                            isStep = true
                        } else {
                            $('.aside_pc ul>li:lt(2)').addClass('passed')
                        }
                    }
                }
            }
        });
    }


     // google 分析代码
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
    ga('create', 'UA-135920854-1', 'elecfans.com');
    ga('send', 'pageview');

    function browser(){
        var rwebkit = /(webkit)\/([\w.]+)/,
        ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
        rmsie = /(msie) ([\w.]+)/,
        rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
        ua = window.navigator.userAgent.toLowerCase();
        var match = rwebkit.exec(ua) ||
        ropera.exec(ua) ||
        rmsie.exec(ua) ||
        ua.indexOf("compatible") < 0 && rmozilla.exec(ua) || [];
        return {
            browser: match[1] || "未知",
            version: match[2] || "0"
        }
    }

    function sendGA(content){
         //判断浏览器
         var  myBrowser=browser().browser+""+browser().version;
         //向谷歌发送数据
         if(typeof(ga)!="undefined"){
           ga('send', 'event', 'adi201907', 'click', '[adi201907]'+content);
       }
         //向百度发送数据
         if(typeof(_hmt)!="undefined"){
           _hmt.push(['_trackEvent', 'adi201907', 'click', '[adi201907]'+content]);
       }
    }

    /**
     * 获取用户抽奖机会
     * api:/webapi/lottery/getLotteryChance GET
     *
     * @param string $prizetype 抽奖分类
     * @return [type] [description]
     */
    getLotteryChance()
    function getLotteryChance(){
        $.get("/webapi/lottery/getLotteryChance", {"prizetype": "adi201907"}, function (res) {
            if (res["status"] == "successed") {
                var getData = res["data"];
                uID = getData["loginuid"];//获得登录用户ID
                getChance = getData["chance_count_user"];//获得用户已获得的抽奖次数
                usedChance = getData["used_count"];//获得用户已用抽奖次数
                nowChange = getChance - usedChance;
                $(".count").text(nowChange);
            }
        });
    }

    /*
     * 设置中奖名单
     */
    function getLotterList() {
        /** 中将者名单超出区域自动滚动*/
        var marqueeList = function () {
            var speed = 50;
            var getBox = $("#jq_marquee_box"); //获得容器高度
            var getItem = getBox.find("ul"); //获得列表项
            var getBoxH = getBox.height();
            var getItemH = getItem.height();
            //列表项高度大于容器高度,就滚动
            if (getBoxH < getItemH) {
                getBox.append(getItem.clone()); //复制一份
                var myMarquee = null;

                function Marquee() {
                    clearInterval(myMarquee);
                    if (getBox.get(0).scrollTop == getItemH)
                        getBox.get(0).scrollTop = 0;
                    else {
                        getBox.get(0).scrollTop++
                    }
                    myMarquee = setInterval(Marquee, speed);
                }

                Marquee();
                getBox.mouseover(function () {
                    clearInterval(myMarquee);
                }).mouseout(function () {
                    myMarquee = setInterval(Marquee, speed);
                });
            }
        };

        /**
         * 获取中奖名单

         * api:/webapi/topicapi/getLotteryUser/lotterytype/adi201907
         * @return [type] [description]
         */

        $(function () {
            $.ajax({
                url: "/webapi/topicapi/getLotteryUser/lotterytype/adi201907",
                type: "get",
                success: function (res) {
                    var setList = '<li class="null">≥▂≤数据加载失败</li>'; //初始化列表
                    var getListBox = $("#jq_marquee_box ul");
                    if (res["status"] == "successed") {

                        /*生成列表*/
                        var getList = res["data"]["user"];
                        if (getList.length > 0) {
                            setList = "";
                            for (var i = 0; i < getList.length; i++) {
                                var getOneData = getList[i];
                                var getUser = getOneData["username"];
                                var getPrize = getOneData["prizename"];

                                getUser = getUser.length > 5 ? getUser.substring(0, 5) + "..." : getUser; //截取超长用户名
                                getPrize = getPrize.length > 10 ? getPrize.substring(0, 10) + "..." : getPrize; //截取超长礼品名
                                setList += '<li>' + getUser + '&nbsp;&nbsp;<span>获得</span>&nbsp;&nbsp;' + getPrize +
                                    '</li>'
                            }
                        }
                        else {
                            //列表为空
                            setList = '<li class="null">当前还没有人抽奖<br/>快来抢沙发!</li>';
                        }
                    }
                    getListBox.html(setList); //置入文本
                    marqueeList(); //设置列表滚动
                }
            });
        })
    }

    getLotterList();

    /*
     * 通用抽奖接口
     * api:/lottery/comPrize
     * @access POST
     * @param string $prizetype 抽奖类型,如:tti
     * @param string $cookiekey cookie判断抽奖机会,如:tti_userinfo
     * @return [type] [description
     */

    $('#begin_btn').click(function () {

        var lotteryBtn = $(this);
        //判断登录
        if (!!!uID) {
            //没有登录的情况
            $.ssoDialogLogin(); //弹出登录窗口
            return false;
        }
        // if(!isStep){
        //     layer.open({
        //         type: 1,
        //         skin: 'lotter_alert run_out', //样式类名
        //         area: ["160px", "130px"],
        //         closeBtn: 1,
        //         shift: 2, //入场动画
        //         shadeClose: true, //开启遮罩关闭
        //         content: '<big style="margin-top: 40px;">请按顺序闯关,不要跳级哦</big> <a class="pop_desc">去闯关</a>'
        //     });
        //     return false;
        // }
        //判断是否有抽奖机会
        if (nowChange > 0) {

        } else {
            if( getChance > 0 && getChance == usedChance ){
                layer.open({
                   type: 1,
                   skin: 'lotter_alert not_winning no_chance', //样式类名
                   shift: 2, //入场动画
                   area: ["340", "240"],
                   closeBtn: 2,
                   shadeClose: true, //开启遮罩关闭
                   content: '<big class="mt20">抽奖结束</big><span>你的抽奖机会已用完</span>'
                });
                return false;
            } else {
                // var content = '';
                // if( answerIsGetChance == false ){
                //     content ='<big>你还没有抽奖机会</big><span>记得观看3个以上的视频哦</span>' +
                      //         '<p class="btns" id="no_chans_btns">' +
                      //           '<a href="#s_2" class="btn">看视频</a>' +
                      //         '</p>'
                // }else if( videoIsGetChance == false ){
                //     content ='<big>你还没有抽奖机会</big><span>记得先去答题专区答题哦</span>' +
                      //         '<p class="btns" id="no_chans_btns">' +
                      //           '<a href="#s_3" class="btn">去答题</a>' +
                      //         '</p>'

                // }else{
                //     content = '<big>你还没有抽奖机会哦</big><a class="pop_desc" href="#section1">去闯关</a>'
                // }
                var tiplayer = layer.open({
                    type: 1,
                    skin: 'lotter_alert no_chance', //样式类名
                    area: ["340", "240"],
                    closeBtn: 2,
                    shift: 2, //入场动画
                    shadeClose: true, //开启遮罩关闭
                    content: '<big>你还没有抽奖机会哦</big><a class="pop_desc">去闯关</a>'
                })
                $("#no_chans_btns a").on("click", function () {
                    layer.close(tiplayer);
                });
            }
            return false;
        }

        //满足条件,就可以抽奖
        $.ajax({
            type: 'post',
            url: '/webapi/lottery/comPrizeTotal',
            data: {
                "prizetype": "adi201907",
                "cookiekey": "adi201907_lotter_chance" + uID
            },
            dataType: 'json',
            cache: false,
            beforeSend: function () {
                if (lotteryBtn.attr("disabled") == "disabled") {
                    return false;
                }
                lotteryBtn.attr("disabled", "disabled");
            },
            success: function (res) {
                $("#prilist .roll.active").removeClass("active");
                if (res["error_code"] == 0) {
                    //抽奖跑马灯开始运行
                    lotteryFn(res["data"], function () {
                        lotteryBtn.removeAttr("disabled"); //解锁按钮
                        getLotterList(); // 更新中奖名单
                    });
                    var curDate = new Date();

                    //当前时间戳
                    var curTamp = curDate.getTime();

                    //当日凌晨的时间戳,减去一毫秒是为了防止后续得到的时间不会达到00:00:00的状态
                    var curWeeHours = new Date(curDate.toLocaleDateString()).getTime() - 1;

                    //当日已经过去的时间(毫秒)
                    var passedTamp = curTamp - curWeeHours;
                    //当日剩余时间
                    var leftTamp = 24 * 60 * 60 * 1000 - passedTamp;
                    var leftTime = new Date();
                    leftTime.setTime(leftTamp + curTamp);
                    $.cookie("prizeUsed" + uID, 1, {expires: leftTime});
                    //设置计数
                    var getTimes = Math.floor($.cookie("adi201907" + uID)) + 1;
                    $.cookie("adi201907" + uID, getTimes);

                    getLotteryChance()
                }
                else {
                    layer.alert(res["msg"]);
                    lotteryBtn.removeAttr("disabled"); //解锁按钮
                }
            },
            error: function () {
                lotteryBtn.removeAttr("disabled"); //解锁按钮
                layer.alert("网络出错了!请稍后再试");
                return false;
            }
        });
    });


    //lotteryFn({"prizename": "我靠","prizeid": "0"}, function() {}) //测试数据
    // 抽奖转盘转动
    function lotteryFn(data, lotterCallback) {
        var prize = data["prizename"]; //获得奖品名
        var pid = data["prizeid"]; //获得奖品ID
        // var noRamdom = Math.random() > 0.5 ? 5 : 7;
        // console.log(pid);
        switch (parseInt(pid)) {
            case 1 :
                pid = 1;//无线蓝牙耳机
                break;
            case 2 :
                pid = 2;//小米蓝牙音箱
                break;
            case 3 :
                pid = 3;//金士顿U盘
                break;
            case 4 :
                pid = 7;//手持小风扇
                break;
            case 5 :
                pid = 8;//伸缩数据线
                break;
            case 6 :
                pid = 4;//迷你榨汁机
                break;
            case 7 :
                pid = 5;//论坛10积分
                break;
            default:
                pid = 1;//没有中奖
                break;
        }
        //显示中奖结果
        var showPrize = function (pid) {
            if (pid == 6) {
                //没有中奖
                layer.open({
                   type: 1,
                   skin: 'lotter_alert not_winning', //样式类名
                   shift: 2, //入场动画
                   area: ["340", "240"],
                   closeBtn: 2,
                   shadeClose: true, //开启遮罩关闭
                   content: '<big class="mt20">很遗憾</big><span style="margin-bottom: 4px;">未抓到任何奖品!</span><p class="blue_color">听说手速够快就能抓到奖品</p>'
                });
            }
            else if (pid >= 1 && pid <= 8) {
                var content = '<big class="mt20">恭喜您<b>中奖了</b>!</big>' +
                            '<p>抓到' + prize + '</p>' +
                            '<span>活动结束后统一发放奖品</span>';

                if( pid == 5 ){
                    content = '<big class="mt20">恭喜您<b>中奖了</b>!</big>' +
                            '<p>' + prize + '</p>' +
                            '<span>论坛积分已通过系统自动发放</span>'
                }
                //中奖了
                layer.open({
                    type: 1,
                    skin: 'lotter_alert winner', //样式类名
                    shift: 2, //入场动画
                    area: ["340", "240"],
                    closeBtn: 2,
                    shadeClose: true, //开启遮罩关闭
                    content: content

                });
            }
            else {
                layer.alert("抽奖程序出错了,请重新抽奖");
                //消除错误计数
                var getTimes = Math.floor($.cookie("adi201907" + uID)) - 1;
                getTimes = getTimes < 0 ? 0 : getTimes;
                $.cookie("adi201907" + uID, getTimes);
            }
            lotterCallback(); //执行回调函数
        }

        //抽奖程序
        var lottery = {
            index: 1, //起点
            speed: 200, //初始速度
            roll: 0, //定时器id
            cycle: 1, //已跑的圈速
            times: 5, //至少跑几圈
            prize: pid, //中奖索引
            btn: 0,
            total: 8, //奖品数
            run: function () {
                var before = lottery.index == 1 ? lottery.total : lottery.index - 1;
                $(".roll-" + lottery.index).addClass("active");
                $(".roll-" + before).removeClass("active");

                //初步加快的过程
                lottery.upSpeed();
                lottery.downSpeed();
                lottery.index += 1;
                lottery.index = lottery.index > lottery.total ? 1 : lottery.index;
            },
            //提速
            upSpeed: function () {
                if (lottery.cycle < 2 && lottery.speed > 100) {
                    lottery.speed -= lottery.index * 8;
                    lottery.stop();
                    lottery.start();
                }
            },
            //降速
            downSpeed: function () {
                if (lottery.index == lottery.total) {
                    lottery.cycle += 1;
                }
                if (lottery.cycle > lottery.times - 1 && lottery.speed < 400) {
                    lottery.speed += 20;
                    lottery.stop();
                    lottery.start();
                }

                if (lottery.cycle > lottery.times && lottery.index == lottery.prize) {
                    lottery.stop();
                    //先停止再显示结果 按钮显示出来
                    setTimeout(function () {
                        showPrize(lottery.prize);
                    }, 700);
                }
            },
            start: function () {
                lottery.roll = setInterval(lottery.run, lottery.speed);
            },
            stop: function () {
                clearInterval(lottery.roll);
            }
        }
        lottery.start();
    }


    $(document).on("click", '.pop_desc', function(){
        $('html, body').animate({scrollTop: $("#section2").offset().top}, 100)
        layer.closeAll()
    })
})(jQuery)

 

posted @ 2019-10-02 19:02  klsfct  阅读(535)  评论(0编辑  收藏  举报