var reqList = [];
new Vue({
    el: "#main",
    data: {
        appname: "咨询分析",
        isback: true,
        isrefresh: true,
        isfilter: true,
        isopen: true,
        //页面请求参数
        level: '',
        area: '',
        areaTitle: '',
        lowLevel: '',
        chooseYear: '',
        endDate: '',
        topDatas: {
            total: 0,
            noRelyCount: 0,
            noRelyRate: 0,
            relyRate: 0
        }
    },
    components: {
        vuedals: Vuedals.Component
    },
    methods:{
        getAreaData: function(arg){
            //如果level改变，则需要重新加载整个页面的数据，否则只需加载底部区域数据
            if(arg.level == this.level){
                this.lowLevel = arg.lowLevel;
                loadData([2], this);
            }else{
                this.level = arg.level;
                this.lowLevel = arg.lowLevel;
                this.area = arg.area;
                this.areaTitle = arg.areaTitle;
                loadData([0,1,2], this);
            }
            EventBus.$emit('update-area-name', {areaName: this.areaTitle});
            //存储请求所带的参数
            reqList.push({
                level: this.level,
                area: this.area,
                areaTitle: this.areaTitle,
                lowLevel: this.lowLevel,
                endDate: this.endDate
            })
        }
    },
    mounted: function(){
        //初始化数据
        initData(this);
        
        //获得顶部各tab的值
        loadData([0,1,2], this); //参数组数表示请求的区域为上中下
        
        //存储请求所带的参数
        reqList.push({
            level: this.level,
            area: this.area,
            areaTitle: this.areaTitle,
            index: this.index,
            endDate: this.endDate,
            startDate: this.startDate,
            lowLevel: this.lowLevel
        });
        
        //设置监听器， 监听折线图日期变化
        var vm = this;
        //监听后退按钮的操作
        EventBus.$on("back-click", function(arg){
            EventBus.$emit('update-statistics-time', {}); //更新统计时间
            if(reqList.length == 1){
                history.go(-1);
            } 
            else{
                var preInfo = reqList.pop();
                var info = reqList[reqList.length - 1];
                vm.level = info.level;
                vm.area = info.area;
                vm.areaTitle = info.areaTitle;
                vm.lowLevel = info.lowLevel;
                vm.index = info.index;
                
                loadData([0,1,2], vm);
                EventBus.$emit('update-area-name', {areaName: vm.areaTitle});
            }
        });
        //监听页面刷新
        EventBus.$on("refresh-click", function(arg){
            loadData([0,1,2], vm);
        });
        //弹出筛选框
        EventBus.$on('filter-click', function(arg) {
            //弹框显示筛选条件
            Vuedals.Bus.$emit('new', {
                title: '条件筛选',
                onClose:function(data){
                    console.log(data);
                    vm.chooseYear = data.chooseYear;
                    vm.endDate = getEndDate(vm.chooseYear);
                    
                    loadData([0, 1, 2], vm);//刷新数据
                    EventBus.$emit('update-statistics-year', {selectDate: vm.chooseYear + "年"});//更新年份
                    EventBus.$emit('update-statistics-time', {});//更新统计时间
                },
                component: 'year-filter',
                props: {
                    selectedYear: vm.chooseYear
                }
            });
        });
        $("#main").removeClass("c-hide");
    }
});

function initData(vm){
    //获得缓存中缓存的角色权限
    var userRole = window.sessionStorage.getItem("selectedRole");
    if(!userRole){
        return false;
    }
    vm.userRole = JSON.parse(userRole);
    vm.level = vm.userRole.code == '350200' ? 4 : vm.userRole.code.length == 6 ? 3 : 2;
    vm.area = vm.userRole.code;
    vm.areaTitle = vm.userRole.name;
    EventBus.$emit('update-area-name', {areaName: vm.areaTitle});
    
    var now = new Date();
    if(now.getMonth() >= 6){
        vm.chooseYear = now.getFullYear();
    }else{
        vm.chooseYear = now.getFullYear() - 1;
    }
    vm.endDate = getEndDate(vm.chooseYear);
    EventBus.$emit('update-statistics-year', {selectDate: vm.chooseYear + "年"});
}

function initReqParams(vm){
    var param = [{
        url: "/statistics/Consulting_Title",
        data: {level: vm.level, area: vm.area, year: vm.chooseYear}
    },{
        url: "/statistics/getCoutListByTime",
        data: {level: vm.level, area: vm.area, year: vm.chooseYear}
    },{
        url: "/statistics/Consulting_StatList",
        data: {level: vm.level, area: vm.area, year: vm.chooseYear, sort: 1, date: vm.endDate, lowlevel: vm.lowLevel}
    }];
    
    return param;
}

function loadData(loadArr, vm){
    //获取其他请求的参数
    var reqParams = initReqParams(vm),
        reqPromise = [];
    
    for(i=0; i< loadArr.length; i++){
        var j = loadArr[i];
        var param = reqParams[j];
        reqPromise.push(httpRequest.get(param.url, {data: param.data}));
    }
        
    if(reqPromise.length > 0){
        Promise.all(reqPromise).then(function(ress){
            var res1, res2, res2;
            for(var i=0; i<loadArr.length; i++){
                var j = loadArr[i] + 1;
                if(j == 1){
                    res1 = ress[i];
                }
                if(j == 2){
                    res2 = ress[i];
                }
                if(j == 3){
                    res3 = ress[i];
                }
                
            }
            if(res1){
                if(res1.status == 200){
                    handleTopPanelData(res1.data, vm);
                }else{
                    console.log(res1.msg);
                }
            }
            if(res2){
                if(res2.status == 200){
                    handleSecondPanelData(res2.data, vm);
                }else{
                   console.log(res2.msg);
                }
                
            }
            if(res3){
                if(res3.status == 200){
                    listHandle(res3.data, vm);
                }else{
                    console.log(res3.msg);
                }
            }
        })
    }
}

function handleTopPanelData(data, vm){
    var obj = data.result[0];
    vm.topDatas = {
        total: obj.total,
        noRelyCount: obj.noRelyCount,
        noRelyRate: obj.noRelyRate,
        relyRate: obj.relyRate
    }
}

function handleSecondPanelData(data, vm){
    var list = data.resultList,
        xData = [],
        yData = [];
    for(i=0; i<list.length; i++){
        var item = list[i];
        xData.push(item.name + "时");
        yData.push(item.num);
    }
    drawBarChart(xData, yData);
}

function listHandle(data, vm){
    var list = data.resultList;
    var topArr = soreRank(getKeyValueArr(list, 'noRelyDoubleRate'));
    var arr = _.map(list, function(o, index){
        var cols = [o.name, o.total, o.noRelyCount, o.noRelyRate];
        return {
            rank: topArr[index],
            code: o.code,
            name: o.name,
            cols: cols
        }
    });
    
    EventBus.$emit("render-area-data",{
        level: vm.level,
        area: vm.area,
        lowLevel: vm.lowLevel,
        headers: ["排名", "咨询数", "未回复数", "未回复率"],
        rows: arr
    });
}

function drawBarChart(xData, yData) {
    var myChart = echarts.init(document.getElementById('barChart'));
    var options = {
        calculable: true,
        tooltip: {
            trigger: 'item',
//          formatter: '{a}<br />{b} : {c}次'
        },
        toolbox: {
            dataZoom: true,
            show: true,
            orient: 'vertical',
            x: 'right',
            y: 'center'
        },
        grid: {
            left: '20px',
            right: '20px',
            bottom: '20px',
            top: '20px',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#dcdcdc',
                    width: 1
                }
            },
            axisLabel: {
                show: true,
                color: '#666'
            },
            splitLine: {
                show: false
            },
            data: xData
        }],
        yAxis: [{
            type: 'value',
            axisLine: {
                show: true,
                lineStyle: {
                    color: '#dcdcdc',
                    width: 1
                }
            },
            axisLabel: {
                show: true,
                color: '#666'
            },
            splitLine: {
                show: false
            },
        }],
        series: [{
            name: '回复次数',
            type: 'bar',
            barWidth: 40,
            itemStyle: {
                normal: {
                    color: function(params) {
                        var colorList = ['#12B7F5', '#FB5DAB', '#CD67FD', '#FFC800', '#61EB41'];
                        return colorList[params.dataIndex]
                    },
                    label: {
                        show: true,
                        position: 'top',
                        formatter: function(params) {
                            return params.value;
                        }
                    },
                    barBorderRadius: 0
                }
            },
            data: yData
        }]
    };
    myChart.clear();
    myChart.setOption(options);
    window.onresize = function() {
        myChart.resize();
    }
}