// pages/index.js
var urlPath = require('../../config.js');
const app = getApp();
Page({
    // 前往下一页
    picture(e) {
        wx.navigateTo({ 
            url: '../picture/picture?id=' + e.currentTarget.dataset.id
        });
    },
    rule() {
        wx.navigateTo({ 
            url: '../rule/rule'
        });
    },
    vote(e){
        var that = this;
        var id = e.currentTarget.dataset.id;
        if(id > 0){
            wx.request({
                url: urlPath.vote,
                header:{
                    'token' : wx.getStorageSync('token')
                },
                data:{
                    id : id
                },
                success(res){
                    if(res.data.code == 0){
                        wx.showToast({
                            title: '投票成功'
                        });
                        that.onLoad();
                    }else{
                        wx.showToast({
                            title:res.data.msg,
                            icon:'none'
                        });
                    }
                }
            })
        }
    },
    personal(e) {
        wx.navigateTo({ 
            url: '../personal/personal?id=' + e.currentTarget.dataset.uid
        });
    },
    sign() {
        wx.navigateTo({ url: '../sign/sign' });
    },
    /**
     * 页面的初始数据
     */
    data: {
        loadHidden : true, //
        img_url: wx.getStorageSync('img_url'),
        swiperCurrent:0,
        autoplay: false,
        interval: 3000,
        duration: 800,
        //倒计时数据
        endTime: '',
        tab_number: 0 ,//参与者
        tab_vote: 0,//投票数
        tab_visit: 0,//访问次数
        rule_text:['1、本次活动不收任何费用，不退稿。2、参赛作品需附有作品介绍，字数限100字以内。3、每位参赛者仅限提交不超过5幅3、每位参赛者仅限提交不超过5幅'],//活动规则
        //列表
        works_list: [],
        page : 1,
        pageSize : 6,
        rule:'',
        search_page:1,
        for_search:false,
        keyword:'',
        forMore:true,
    },
    swiperChange: function (e) {
        this.setData({
            swiperCurrent: e.detail.current
        })
    },
     /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        var that = this;
        that.setData({
            //倒计时数据
            endTime: '',
            tab_number: 0 ,//参与者
            tab_vote: 0,//投票数
            tab_visit: 0,//访问次数
            rule_text:['1、本次活动不收任何费用，不退稿。2、参赛作品需附有作品介绍，字数限100字以内。3、每位参赛者仅限提交不超过5幅3、每位参赛者仅限提交不超过5幅'],//活动规则
            //列表
            works_list: [],
            page : 1,
            pageSize : 20,
        });
        //登录状态
        wx.checkSession({
            success: function (res) {
                console.log("DDDDDDD");
                that.getVoteList();
                that.getSlideList();
                that.saveVisit();
                that.getBaseInfo();
                //var user = wx.getStorageSync('user') || [];
            },
            fail: function(){
                wx.login({
                    success: res => {
                        console.log(res);
                        wx.request({
                            url: urlPath.getopenid,
                            data: {
                                code: res.code
                            },
                            success(res) {
                                console.log(res);
                                if(res.data.code == 0){
                                    wx.setStorageSync('token', res.data.data.token);
                                    wx.setStorageSync('openid', res.data.data.openid);
                                    wx.setStorageSync('user', res.data.data.user);
                                    that.onLoad();
                                }else{
                                    console.log(res.data.msg);
                                }
                            }
                        });
                    }
                })
            }
        });
        
        
        //that.countDown()//倒计时监听
    },
    saveVisit:function(){
        wx.request({
            url: urlPath.saveVisit,
            header:{
                'token': wx.getStorageSync('token')
            },
            method:'post',
            success(res){
                console.log(res);
            }
        });
    },
// 倒计时
    countDown:function(){
        var that=this;
        var nowTime = new Date().getTime();//现在时间（时间戳）
        var endTime = new Date(that.data.endTime).getTime();//结束时间（时间戳）
        var time = (endTime-nowTime)/1000;//距离结束的毫秒数
        // 获取天、时、分、秒
        let day = parseInt(time / (60 * 60 * 24));
        let hou = parseInt(time % (60 * 60 * 24) / 3600);
        let min = parseInt(time % (60 * 60 * 24) % 3600 / 60);
        let sec = parseInt(time % (60 * 60 * 24) % 3600 % 60);
        day = that.timeFormin(day),
        hou = that.timeFormin(hou),
        min = that.timeFormin(min),
        sec = that.timeFormin(sec)
        that.setData({
            day: that.timeFormat(day),
            hou: that.timeFormat(hou),
            min: that.timeFormat(min),
            sec: that.timeFormat(sec)
        })
        // 每1000ms刷新一次
        if (time>0){
            that.setData({
                countDown: true
            })
            setTimeout(this.countDown, 1000);
        }else{
            that.setData({
                countDown:false
            })
        }
    },
    getSlideList:function(){
        var that = this;
        var slide_list = [];
        wx.request({
            url: urlPath.getSlideList,
            header:{
                'token': wx.getStorageSync('token')
            },
            success(res){
                if(res.data.code == 0){
                    if(res.data.data.length > 0){
                        res.data.data.forEach(function(item){
                            slide_list.push(urlPath.host + item.src);
                        });
                        that.setData({
                            img_url:slide_list
                        });
                        wx.setStorageSync('img_url', that.data.img_url);
                    }
                }else{
                    console.log(res.data.msg);  //失败
                }
            }
        });
    },
    getVoteList:function(){
        var that = this;
        if(!that.data.forMore){
            return;
        }
        var vote_list = [];
        wx.request({
            url: urlPath.getVoteList,
            header:{
                'token' : wx.getStorageSync('token')
            },
            data:{
                page:that.data.page,
                page_size:that.data.pageSize
            },
            success(res){
                if(res.data.code == 0){
                    if(res.data.data.length > 0){
                        res.data.data.forEach(function(item){
                            vote_list.push({
                                ids: item.id,
                                img: urlPath.host + item.pic,
                                text: item.explain,
                                name: item.user_name,
                                number: item.votes,
                                uid:item.uid
                            });
                        });
                        that.setData({
                            works_list:that.data.works_list.concat(vote_list)
                        });
                        that.setData({
                            page : that.data.page + 1
                        })
                    }else{
                        that.setData({
                            forMore:false
                        });
                    }
                }else{
                    console.log(res.data.msg);  //失败
                }
            }
        })
    },
    loadChange:function(){
        var that = this;
        if(that.data.for_search){
            that.search();
        }else{
            that.getVoteList();
        }
    },
    //小于10的格式化函数（2变成02）
    timeFormat(param) {
        return param < 10 ? '0' + param : param;
    },
    //小于0的格式化函数（不会出现负数）
    timeFormin(param) {
        return param < 0 ? 0: param;
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    onShow:function(){
        if (typeof this.getTabBar === 'function' &&
            this.getTabBar()) {
            this.getTabBar().setData({
                selected: 1
            })
        }
    },
    getBaseInfo:function(){
        var that = this;
        wx.request({
            url: urlPath.getBaseInfo,
            header:{
                'token' : wx.getStorageSync('token')
            },
            success(res){
                if(res.data.code == 0){
                    var voteNumber = res.data.data.voteNumber;
                    var numberOfPeople = res.data.data.numberOfPeople;
                    var vote = res.data.data.vote;
                    that.setData({
                        tab_number: numberOfPeople,
                        tab_vote: voteNumber,
                        endTime: vote.time,
                        rule_text: vote.rule_text,
                        tab_visit:vote.visits,
                        rule: vote.rule
                    });
                    wx.setStorageSync('baseInfo', res.data.data);
                    that.countDown()
                }else{
                    console.log(res.data.msg);  //失败
                }
            }
        })
    },
    search:function(){
        var that = this;
        if(that.data.keyword == ''){
            return;
        }
        if(!that.data.forMore){
            return;
        }
        wx.request({
            url: urlPath.search,
            data: {
                keyword: that.data.keyword,
                page:that.data.search_page,
                page_size:that.data.pageSize
            },
            header:{
                'token' : wx.getStorageSync('token')
            },
            success: function(res) {
                if(res.data.code == 0){
                    var type = res.data.data.type;
                    var items = res.data.data.items;
                    if(type== 'int'){
                        wx.navigateTo({ 
                            url: '../picture/picture?id=' + items.id
                        });
                    }else if(type == 'string'){
                        var vote_list = [];
                        items.forEach(function(item){
                            vote_list.push({
                                ids: item.id,
                                img: urlPath.host + item.pic,
                                text: item.explain,
                                name: item.user_name,
                                number: item.votes,
                                uid:item.uid
                            });
                        });
                        if(that.data.search_page == 1){
                            that.setData({
                                works_list:vote_list,
                                forMore:true
                            });
                        }else{
                            that.setData({
                                works_list:that.data.works_list.concat(vote_list)
                            });
                        }
                        if(items.length < that.data.pageSize){
                            that.setData({
                                forMore: false
                            });
                        }
                        that.setData({
                            search_page : that.data.search_page + 1,
                            for_search:true
                        })
                    }
                }else{
                    wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 1500
                    });
                }
            }
        });
    },
    goSearch:function(e){
        var that = this;
        var formData = e.detail.value;
        if (formData) {
            that.setData({
                keyword:formData,
                forMore: true
            });
            that.search();
        } else {
            wx.showToast({
                title: '输入不能为空',
                icon: 'none',
                duration: 1500
            });
        }
    }
})