lottery.js 18.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
// var baseURL = 'https://yq.vchangyi.com/party/phpapi';
//var baseURL = 'http://dsc-b.vchangyi.com/party/phpapi';
var baseURL = 'http://party.vchangyi.com/phpapi';

let imgTimer = null;
let nameTimer = null;
let prizeNoTimer = null;
let prizeList = ['五等奖', '四等奖', '三等奖', '二等奖', '一等奖']
let defaultAvatar = './img/pc/default_avatar.png';

// 抽奖页面
let action = {
    prizeList: [], // 奖项列表
    curPrizeIndex: -1, // 正在抽奖的奖项的索引
    userList: [], // 抽奖用户列表
    currentUser: null, // 当前中奖的用户
    curUserIndex: -1, // 当前中奖的用户索引
    winnerList: [], // 中奖用户列表
    // 初始化数据
    init: function() {
        this.togglePage(true);
    },
    // 切换显示页面
    togglePage(isInit = true) {
        if (isInit) { // 进入选择奖项页
            action.curPrizeIndex = -1;
            $('.select-page').show();
            $('.result-page').hide();
            if (action.prizeList.length > 0) {
                $('.radio-group .radio-item').removeClass('active');
            } else {
                action.getPrizeList();
            }
        } else { // 进入抽奖页
            $('.select-page').hide();
            $('.result-page').css('display', 'flex');
            // 初始化变量
            action.userList = [];
            action.currentUser = null;
            action.winnerList = [];
            // 获取中奖记录
            action.getWinnerList(action.prizeList[action.curPrizeIndex].id);
            // 获取抽奖用户列表
            action.getUserList();
            // 初始化头像部分
            $('.avatar-img, .user-info .scroll-wrap').show();
            $('.winner, .winner-name, .winner-no').hide();
            // 初始化按钮
            $('.start-btn').show();
            $('.stop-btn, .continue-btn').hide();

            $('.result-title').html(action.prizeList[action.curPrizeIndex].prize_name);
        }
    },
    // 获取奖项列表
    getPrizeList: function() {
        let url = '/apicp.PrizeList.php';
        let callback = function(res) {
            action.prizeList = res.data.reverse();
            let html = template('prizeTmpl', {
                list: action.prizeList
            });
            $('.radio-group').html(html);
            $('.radio-group .radio-item').removeClass('active');
        };
        baseRquest.get(url, '', callback);
    },
    // 选择奖项
    selectPrize: function(index) {
        action.curPrizeIndex = index;
        $('.radio-group .radio-item').removeClass('active');
        $('.radio-group .radio-item').eq(index).addClass('active');
    },
    // 控制显示弹框
    switchDialog: function(isShow) {
        if (isShow) {
            $('.dialog').show();
        } else {
            $('.dialog').hide();
        }
    },
    // 进入抽奖页面
    goLottery: function() {
        if (this.curPrizeIndex == -1) {
            this.switchDialog(true);
            return;
        }
        this.togglePage(false);
    },
    // 获取中奖记录
    getWinnerList: function(prizeId) {
        let url = '/apicp.LotteryList.php';
        let data = {
            prize_id: prizeId
        };
        let callback = function(res) {
            action.winnerList = res.data;
            action.updateResultTmpl();
        };
        baseRquest.get(url, data, callback);
    },
    // 获取抽奖用户列表
    getUserList: function() {
        var url = '/apicp.UserList.php';
        var callback = function(res) {
            action.userList = res.data;
            action.initUserList();
        };
        baseRquest.get(url, '', callback);
    },
    initUserList() {
        let imgStr = '';
        let nameStr = '';
        let prizeNoStr = '';
        this.userList.map(user => {
            if (user.headimg) {
                imgStr += '<img class="avatar-item" src="' + user.headimg + '">';
            } else {
                imgStr += '<img class="avatar-item" src="' + defaultAvatar + '">';
            }
            nameStr += '<span class="scroll-item">' + user.realname + '</span>';
            prizeNoStr += '<span class="scroll-item">' + user.prize_no + '</span>';
        });
        $('.avatar-list').html(imgStr);
        $('.user-name .scroll-list').html(nameStr);
        $('.user-no .scroll-list').html(prizeNoStr);
        let imgListWidth = parseInt($('.avatar-list .avatar-item').css('width')) * this.userList.length + 'px';
        $('.avatar-list').css('width', imgListWidth);
        let nameListWidth = parseInt($('.user-name .scroll-item').css('width')) * this.userList.length + 'px';
        $('.user-name .scroll-list').css('width', nameListWidth);
        let prizeNoListWidth = parseInt($('.user-no .scroll-item').css('width')) * this.userList.length + 'px';
        $('.user-no .scroll-list').css('width', prizeNoListWidth);
    },
    // 开始
    start: function() {
        if (this.userList.length === 0) {
            alert('暂无数据');
            return;
        }
        $('.start-btn').hide();
        $('.continue-btn').hide();
        $('.stop-btn').show();

        // 开始抽奖动画
        imgTimer = this.lotteryAnimation($('.avatar-list'), '.avatar-item', 244);
        nameTimer = this.lotteryAnimation($('.user-name .scroll-list'), '.scroll-item', 146);
        prizeNoTimer = this.lotteryAnimation($('.user-no .scroll-list'), '.scroll-item', 146);
    },
    // 抽奖动画,speed: 每次移动多少像素
    lotteryAnimation: function(dom, child, speed) {
        var i = 0;
        var interval = 100; // 定时器的速度
        dom.append(dom.find(child).eq(0).clone());
        var size = dom.find(child).size();
        var itemWidth = parseInt($(child).css('width'));
        dom.css('width', itemWidth * size + 'px');
        var timer = setInterval(() => {
            var left = speed * i;
            if (left >= itemWidth * (size - 1)) {
                i = 0;
            }
            dom.css('left', -left + 'px');
            i += 1;
        }, interval);
        return timer;
    },
    // 继续抽奖
    continueLottery: function() {
        if (action.userList.length === 0) {
            alert('暂无数据');
            return;
        }

        // 初始化头像部分
        $('.avatar-img, .user-info .scroll-wrap').show();
        $('.winner, .winner-name, .winner-no').hide();
        // 初始化按钮
        $('.stop-btn').show();
        $('.continue-btn, .start-btn').hide();

        // 开始抽奖动画
        imgTimer = this.lotteryAnimation($('.avatar-list'), '.avatar-item', 244);
        nameTimer = this.lotteryAnimation($('.user-name .scroll-list'), '.scroll-item', 146);
        prizeNoTimer = this.lotteryAnimation($('.user-no .scroll-list'), '.scroll-item', 146);
    },
    // 停止
    stop: function() {
        // 按钮效果
        $('.start-btn').hide();
        $('.stop-btn').hide();
        $('.continue-btn').show();

        // 停止抽奖动画
        clearInterval(imgTimer);
        clearInterval(nameTimer);
        clearInterval(prizeNoTimer);

        // 生成中奖用户
        let random = Math.floor(Math.random() * (action.userList.length - 1 + 1)); // (0 ~ length-1)
        console.log('random: ', random);
        action.currentUser = action.userList[random];
        action.curUserIndex = random;
        // 保存中奖记录
        action.saveLottery();
        action.winnerList.push(action.currentUser);

        // 重置位置
        $('.winner').show();
        $('.avatar-list').css('left', '0');
        $('.avatar-img').hide();

        $('.winner-name').show();
        $('.user-name .scroll-list').css('left', '0');
        $('.user-name .scroll-wrap').hide();

        $('.winner-no').show();
        $('.user-no .scroll-list').css('left', '0');
        $('.user-no .scroll-wrap').hide();

        // 展示中奖用户
        var userAvatar = this.currentUser.headimg || defaultAvatar;
        $('.winner .avatar-item').attr('src', userAvatar);
        $('.winner-name').html(this.currentUser.realname);
        $('.winner-no').html(this.currentUser.prize_no);

        // 更新中奖名单模板
        action.updateResultTmpl();
        // 获取抽奖用户列表
        action.getUserList();
    },
    // 更新中奖名单模板
    updateResultTmpl: function() {
        let resultHtml = template('resultTmpl', {
            list: action.winnerList
        });
        $('.result-list').html(resultHtml);
    },
    // 保存中奖记录
    saveLottery: function() {
        let url = '/apicp.AddLottery.php';
        let data = {
            user_id: action.currentUser.id,
            prize_id: action.prizeList[this.curPrizeIndex].id
        };
        let callback = function(res) {
            // 获取中奖记录
            action.getWinnerList(action.prizeList[action.curPrizeIndex].id);
        };
        baseRquest.post(url, data, callback);
    },
    // 删除中奖用户
    delWinner: function(index) {
        var url = '/apicp.DelLottery.php';
        var data = {
            id: action.winnerList[index].user_id
        };
        var callback = function() {
            action.getWinnerList(action.prizeList[action.curPrizeIndex].id);
        };
        baseRquest.post(url, data, callback);
    }
}
// 系统设置动作
let setting = {
    //用户数据
    userData: null,
    // 登录
    login: function(){
        let pwd = $('#pwd').val();
        let url = "/apicp.AdminLogin.php";
        baseRquest.get(url, {id : pwd}, data => {
            localStorage['token'] = data.token;
            alert('登录成功');
        });
    },
    // 登录
    loginOut: function(){
        localStorage['token'] = '';
        alert('已退出');
    },
    // 用户列表
    userList: function(){
        let url = "/apicp.GetUserList.php";
        baseRquest.get(url, {}, data => {
            this.userData = data;
            dataListBind('user-bind', 'user', data);
        });
    },
    // 删除用户
    delUser: function(row){
        console.log(this.userData);
        let item = this.userData[row];
        let url = "/apicp.DelUser.php";
        baseRquest.post(url, {id : item.id}, data => {
            this.userList();
        });
    },
    // 组织更变
    editDep: function(row){
        console.log(this.userData);
        let item = this.userData[row];
        let url = "/apicp.DelUser.php";
        baseRquest.post(url, {id : item.id,dep: 1}, data => {
            this.userList();
        });
    },
    // 开始签到
    startSign: function(row){
        let url = "/apicp.Setting.php";
        baseRquest.post(url, {flag : 'isStopSign',value: 2}, data => {
            alert('设置成功');
        });
    },
    // 结束签到
    stopSign: function(row){
        let url = "/apicp.Setting.php";
        baseRquest.post(url, {flag : 'isStopSign',value: 1}, data => {
            alert('设置成功');
        });
    },
    // 开启投票
    startVote: function(row){
        let url = "/apicp.Setting.php";
        baseRquest.post(url, {flag : 'isStartVote',value: 1}, data => {
            alert('设置成功');
        });
    },
    // 结束投票
    stopVote: function(row){
        let url = "/apicp.Setting.php";
        baseRquest.post(url, {flag : 'isStartVote',value: 2}, data => {
            alert('提交成功');
        });
    },
    // 重置数据
    resetUser: function(row){
        let user = $('#user-id').val();
        if (user == '') {
            return;
        }
        let url = "/apicp.ResetUser.php";
        baseRquest.post(url, {id : user}, data => {
            alert('提交成功');
        });
    }
}

// 山寨dom数据列表绑定控件,没有实现事件callback
// 要求设置容器名称z-for-container,设置循环列数据模板z-for-item
// 参数1:容器名称,存放列表数据的容器 2:设置的数据模板 3:json数据
let dataListBind = (container, itemName, data)=>{
    let trs = '';
    // 获取模板
    $('*[z-for-item="'+ itemName +'"]').show();
    let trTemplate = $('*[z-for-item="'+ itemName +'"]').prop("outerHTML");
    $('*[z-for-item="'+ itemName +'"]').hide();
    let trTemplateHide = $('*[z-for-item="'+ itemName +'"]').prop("outerHTML");
    for(let i = 0; data.length > i; i++) {
        // 创建一行dom
        let tr = trTemplate;
        // 模板需要赋值项
        let forDataItem = $(tr).find("*[z-for-data]");
        for(let j = 0; forDataItem.length > j; j++) {
            let item = $(forDataItem).eq(j).prop("outerHTML");
            // 获取dom标签绑定的映射名称
            let column = $(forDataItem).eq(j).attr("z-for-data");
            let tagName = $(forDataItem)[j].tagName.toLowerCase();
            // 列表中的img和input支持直接赋值,其他标签赋值到标签中间
            if (tagName == 'img') {
                $(forDataItem).eq(j).attr('src', data[i][column]);
            } else if (tagName == 'input') {
                $(forDataItem).eq(j).val(data[i][column]);
            } else {
                $(forDataItem).eq(j).html(data[i][column]);
            }
            tr = tr.replace(item,$(forDataItem).eq(j).prop("outerHTML"));
        }
        // 事件回调,默认返回当前行对象
        let forClickItem = $(tr).find("*[z-for-click]");
        for(let x = 0; forClickItem.length > x; x++) {
            let clickItem = $(forClickItem).eq(x).prop("outerHTML");
            let click = $(forClickItem).eq(x).attr("z-for-click");
            $(forClickItem).eq(x).attr('onClick', click + "("+ i +")");
            tr = tr.replace(clickItem,$(forClickItem).eq(x).prop("outerHTML"));
        }
        trs += $(tr).removeAttr('z-for-item').prop("outerHTML");
    }
    $('*[z-for-container="'+ container +'"]').html(trTemplateHide + trs);
}

// 山寨版双向数据绑定
let doubleBind = ()=>{
    // 页面监听,改变的数据写入对象
    $(()=>{
        $('*[z-for-item]').hide();
        $('*[z-bind]').change(function(){
            dataBind.bindToData($this);
        })
    })
    // 动态数据自动绑定,bindData中的值必须是对象
    Object.keys(action.bindData).forEach((key)=>{
        Object.keys(action.bindData[key]).forEach((keyKey)=>{
            // bind初始值
            dataBind.bindToPage(key + '.' + keyKey, action.bindData[key][keyKey]);
            // 监听这个对象的每个值变化,动态改变页面数据
            let value = action.bindData[key][keyKey];
            Object.defineProperty(action.bindData[key], keyKey ,{
                enumerable: true,
                configurable: true,
                get:function (){
                    //当获取值的时候触发的函数
                    return value;
                },
                set:function(newValue){
                    if(value != newValue) {
                        value = newValue
                    }
                    let propertyValue = key + '.' + keyKey;
                    dataBind.bindToPage(propertyValue, newValue);
                },
            });
        })
    })
}

// 双向数据绑定事件
let dataBind = {
    // 数据动态绑定到页面
    bindToPage: (propertyValue, value)=>{
        let tag = $('*[z-bind="'+ propertyValue +'"]')[0];
        if ($('*[z-bind="'+ propertyValue +'"]').length == 0) {
            return;
        }
        let tagName = $('*[z-bind="'+ propertyValue +'"]')[0].tagName.toLowerCase();
        if (tagName == 'img') {
            $('*[z-bind="'+ propertyValue +'"]').attr('src', value);
        } else if (tagName == "select" || tagName == "input") {
            $('*[z-bind="'+ propertyValue +'"]').val(value);
        } else {
            $('*[z-bind="'+ propertyValue +'"]').html(value);
        }
    },
    // 页面数据动态绑定
    bindToData: (e)=>{
        let dataName = $(e).attr('z-bind');
        // 数据格式 z-bind = lottery.winnerCount
        // lottery为对象名,区分数据组,winnerCount为对象键
        let prop = dataName.split('.');
        if (prop.length != 2) {
            console.log('z-data数据格式不正确');
            return;
        }
        let tagName = $(e)[0].tagName.toLowerCase();
        if (tagName == 'img') {
            action.bindData[prop[0]][prop[1]] = $(e).attr('src');
        } else if (tagName == "select" || tagName == "input") {
            action.bindData[prop[0]][prop[1]] = $(e).val();
        } else {
            action.bindData[prop[0]][prop[1]] = $(e).html();
        }
    }
}
// 启动双向绑定监听
// $(()=>{doubleBind()});

// api接口数据请求,数据交互引用的axios
let baseRquest = {
    // get请求
    get: function(url, params, callback) {
        axios.defaults.baseURL = baseURL;
        axios.get(url, {
            params : params
        }).then(function(response) {
            if (response.status == 200) {
                data = response.data;
                if (!!data) {
                    // 过滤错误信息,统一抛出
                    if (data.errcode != 0 && data.errcode != 200) {
                        alert(data.errmsg);
                    } else {
                        callback(data.result);
                    }
                }
            } else {
                alert('get无法访问接口');
            }
        }).catch(function(error) {
            console.log(error)
        });
    },
    // post请求
    post: function(url, params, callback) {
        axios.defaults.baseURL = baseURL;
        let data = new URLSearchParams();
        Object.keys(params).forEach(function(key){
            data.append(key, params[key]);
        });
        axios.post(url, data, {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).then(function(response) {
            if (response.status == 200) {
                data = response.data;
                if (!!data) {
                    // 过滤错误信息,统一抛出
                    if (data.errcode != 0 && data.errcode != 200) {
                        alert(data.errmsg);
                    } else {
                        callback(data.result);
                    }
                }
            } else {
                alert('post无法访问接口');
            }
        }).catch(function(error) {
            console.log(error);
        });
    }
}