mobile.js 14.1 KB
// var baseURL = 'http://dsc-b.vchangyi.com/party/phpapi';
// var baseURL = 'https://yq.vchangyi.com/party/phpapi';
var baseURL = 'http://party.vchangyi.com/phpapi';
var socketUrl = '//106.54.64.163:3000';
var defaultAvatar = './img/mobile/default_avatar.png';
var toastTimer = null;
var displayTimer = null;

// 页面数据绑定操作
var action = {
    isRun : 0, // 是否开始签到
    userInfo: null, // 用户信息
    mediaId: '',
    userAvatar: '', // 用户头像
    programList: [], // 节目列表
    init: function() {
        // 本地获取用户信息,判断跳转页面
        var userInfo = localStorage.getItem('userInfo');
        if (userInfo) {
            this.userInfo = JSON.parse(userInfo);
            var userAvatar = localStorage.getItem('userAvatar');
            if (userAvatar) {
                this.userAvatar = userAvatar;
                this.goHome();
            } else {
                this.goPic();
            }
        } else {
            this.goSignIn();
        }
        this.wechatJsSign(); // 微信 SDK config
    },
    // 获取微信jsapi签名
    wechatJsSign: function() {
        var WECHAT_JS_SIGN_URL = baseURL + '/api.WechatJsSign.php';
        var sign = function(data) {
            wx.config({
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: data.appId, // 必填,公众号的唯一标识
                timestamp: data.timestamp, // 必填,生成签名的时间戳
                nonceStr: data.nonceStr, // 必填,生成签名的随机串
                signature: data.signature,// 必填,签名
                jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage', 'hideAllNonBaseMenuItem'] // 必填,需要使用的JS接口列表
            });
            wx.ready(function() {
                wx.hideAllNonBaseMenuItem(); // 隐藏所有非基础按钮
            });
        };
        baseRquest.get(WECHAT_JS_SIGN_URL, {'url' : location.href}, sign);
    },
    // 获取年会开关设置
    getSetting: function(callback) {
        var url = baseURL + '/apicp.GetSetting.php';
        baseRquest.get(url, '', callback);
    },
    // 判断是否可以签到
    getSignInState: function() {
        var callback = function(res) {
            if (res.data.isStopSign == 2) { // 已开启签到
                var url = baseURL + '/apicp.SignIn.php';
                var realname = $('.sign-input').val().replace( /^\s*/, '');
                var data = { realname: realname };
                var callback = function(res) {
                    action.userInfo = res.data;
                    localStorage.setItem('userInfo', JSON.stringify(action.userInfo));
                    $('.sign-input').val('');
                    action.goPic();
                };
                baseRquest.post(url, data, callback);
            } else { // 未开启签到
                action.switchDialog('#stop_sign_dialog', true);
            }
        };
        action.getSetting(callback);
    },
    // 签到
    signIn: function() {
        var realname = $('.sign-input').val().replace( /^\s*/, '');
        if (!realname) {
            return;
        }
        action.getSignInState();
    },
    // 进入签到页
    goSignIn: function() {
        $('.sign-in').show();
        $('.pic').hide();
        $('.home').hide();
        $('.vote').hide();
        $('.seat').hide();
    },
    // 进入拍照页
    goPic: function() {
        $('.pic').show();
        $('.sign-in').hide();
        $('.home').hide();
        $('.vote').hide();
        $('.seat').hide();
        this.mediaId = '';
    },
    goHome: function() {
        $('.home').show();
        $('.sign-in').hide();
        $('.pic').hide();
        $('.vote').hide();
        $('.seat').hide();
        if (action.userInfo) {
            var userAvatar = action.userAvatar || defaultAvatar;
            $('#home_user_avatar').attr('src', userAvatar);
            $('#home_user_name').html(action.userInfo.realname);
            $('#home_prize_no').html(action.userInfo.prize_no);
            $('#home_table_no').html(action.userInfo.table_no);
        }
        this.initBarrage();
    },
    goSeat: function() {
        $('.seat').show();
        $('.sign-in').hide();
        $('.pic').hide();
        $('.home').hide();
        $('.vote').hide();
        this.getSeatList();
    },
    // 打开摄像头,type=1: 唤起摄像头,type=2: 打开相册
    openCamera: function(type) {
        console.log('type: ', type)
        var sourceType = [];
        if (type === 1) {
            sourceType = ['camera'];
        } else if (type === 2) {
            sourceType = ['album'];
        } else {
            sourceType = ['album', 'camera'];
        }
        console.log('sourceType: ', sourceType);
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['compressed'], // 'original', 'compressed'指定是原图还是压缩图,默认都有
            sourceType: sourceType, // 'album', 'camera'指定来源是相册还是相机,默认都有
            success: function(res) {
                var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
                wx.uploadImage({
                    localId: localIds.toString(), // 需要上传的图片的ID,由chooseImage接口获得
                    isShowProgressTips: 1, // 进度提示
                    success: function (res) {
                        $('.pic-avatar').attr('src', localIds);
                        action.mediaId = res.serverId; // 返回图片的服务器端ID,即 mediaId
                        console.log('action.mediaId: ', action.mediaId);
                        $('#upload_unavailable').hide();
                        $('#upload_available').show();
                    },
                    fail: function(res) {
                        alert('图片上传失败,请重试');
                    }
                });
            },
            cancel: function() {
                console.log('cancel chooseImage');
                var userAgent = navigator.userAgent.toLowerCase();
                if (/android/.test(userAgent)) {
                    // window.location.reload();
                }
            }
        });
    },
    // 上传头像
    uploadImage: function() {
        if (!action.mediaId) {
            return;
        }
        var data = {
            id: action.userInfo.id,
            mediaId : action.mediaId
        };
        var url = baseURL + '/apicp.UploadHeadImg.php';
        var callback = function(data) {
            action.userAvatar = data.headimg;
            localStorage.setItem('userAvatar', action.userAvatar);
            action.goHome();
        };
        baseRquest.post(url, data, callback);
    },
    // 获取座位列表
    getSeatList: function() {
        var url = baseURL + '/apicp.TablePositionList.php';
        var callback = function(data) {
            var html = template('seatListTmpl', {
                list: data.data,
                userSeat: action.userInfo.table_no
            });
            $('.seat-list').html(html);
        };
        baseRquest.post(url, '', callback);
    },
    // 判断是否开启投票通道
    getVoteState: function() {
        var callback = function(res) {
            if (res.data.isStartVote == 1) {
                action.getProgramList();
            } else {
                action.switchDialog('#home_dialog', true);
            }
        };
        action.getSetting(callback);
    },
    // 获取节目列表
    getProgramList: function() {
        var url = baseURL + '/apicp.ItemList.php';
        var callback = function(data) {
            var user_vote = data.data.user_vote;
            var items = data.data.item;
            if (user_vote && user_vote.length > 0) {
                action.showToast('你已经投过票了哦');
            } else {
                $('.vote').show();
                $('.home').hide();
                items.map(function(item) {
                    item.checked = false;
                });
                var html = template('programListTmpl', { list: items });
                $('.program-list').html(html);
            }
            action.programList = items;
        };
        baseRquest.get(url, {user_id: action.userInfo.id}, callback);
    },
    // 选择节目
    selectProgram: function(index) {
        if (this.programList[index].checked) {
            $('.program-item').eq(index).removeClass('active');
            $('.vote .tip').hide();
        } else {
            var selectedList = this.programList.filter(item => item.checked);
            if (selectedList.length >= 5) {
                $('.vote .tip').show();
                return;
            }
            $('.program-item').eq(index).addClass('active');
        }
        this.programList[index].checked = !this.programList[index].checked;
    },
    // 点击确认投票
    vote: function() {
        var selectedList = this.programList.filter(item => item.checked);
        console.log('selected: ', selectedList);
        if (selectedList.length === 0) {
            action.showToast('请先选择节目');
            return;
        }
        this.switchDialog('#vote_dialog', true);
    },
    // 投票请求
    submitVote: function() {
        let VOTE_URL = '/apicp.ItemVote.php';
        var itemIds = this.programList.filter(item => item.checked).map(item => item.id).join(',');
        console.log('itemIds: ', itemIds);
        var data = {
            user_id: action.userInfo.id,
            item_ids: itemIds
        };
        var callback = function() {
            action.showToast('投票成功!');
            action.switchDialog('#vote_dialog', false)
            setTimeout(function() {
                $('.home').show();
                $('.vote').hide();
            }, 1000);
        };
        baseRquest.post(VOTE_URL, data, callback);
    },
    // 发送弹幕
    initBarrage: function() {
        var socket = io(socketUrl);
        
        $('.send-btn').on('click', function() {
            if ($('.barrage-input').val() != '') {
                socket.emit('barrage', $('.barrage-input').val());
                $('.barrage-input').val('');
                $('.send-btn').removeClass('active');
            }
        });
    },
    resetPosition: function () {
        var currentPosition, timer;
        var speed = 1; // 页面滚动距离
        timer = setTimeout(function() {
            currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
            currentPosition -= speed;
            window.scrollTo(0, currentPosition); // 页面向上滚动
            currentPosition += speed;
            window.scrollTo(0, currentPosition); // 页面向下滚动
            clearTimeout(timer);
        }, 1);
    },
    // 改变发送按钮状态
    toggleBtnState: function() {
        if ($('.barrage-input').val()) {
            $('.send-btn').addClass('active');
        } else {
            $('.send-btn').removeClass('active');
        }
    },
    switchDialog: function(dom, isShow) {
        if (isShow) {
            $(dom).show();
            $('body, .home, .vote').css({
                height: '100vh',
                overflow: 'hidden'
            });
        } else {
            $(dom).hide();
            $('body, .home, .vote').css({
                'min-height': '100vh',
                overflow: 'auto'
            });
        }
    },
    // toast提示
    showToast: function(content, time = 1000) {
        if (toastTimer != null) {
            clearTimeout(toastTimer);
            clearTimeout(displayTimer);
        }
        if ($('#toast').get().length == 0) {
            $('body').append('<div id="toast" class="toast-tip"></div>');
        }
        $('#toast').show();
        $('#toast').css('opacity', 1);
        $('#toast').html(content);
        toastTimer = setTimeout(function() {
            $('#toast').css('opacity', 0);
            displayTimer = setTimeout(
                function() {
                    $('#toast').hide();
                }, 1000);
        }, time);
    },
}

// api接口数据请求,数据交互引用的axios
var 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) {
                        if (url.search('SignIn') !== -1) {
                            action.switchDialog('#sign_in_dialog', true);
                        } else {
                            alert(data.errmsg);
                        }
                    } else {
                        callback(data.result);
                    }
                }
            } else {
                alert('post无法访问接口');
            }
        }).catch(function(error) {
            console.log(error);
        });
    }
}