var reqList = [];
new Vue({
    el: "#main",
    data: {
        appname: "评价分析",
         //页面请求参数
        index: 28,
        level: '',
        area: '',
        startDate: '',
        endDate: '',
        avg: 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,
                index: this.index,
                endDate: this.endDate,
                startDate: this.startDate,
                lowLevel: this.lowLevel
            })
        }
    },
    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);
        });
        $("#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();
   
    vm.endDate = now.format("yyyy-M-dd");
    vm.startDate = "2017-01-01"; //评价功能是2017年才上线的
}

function initReqParams(vm){
    var param = [{
        url: "/statistics/getAVGSocre",
        data: {level: vm.level, area: vm.area}
    },{
        url: "/statistics/getAVGSocreByMonth",
        data: {level: vm.level, area: vm.area, statDate: vm.startDate, endDate: vm.endDate}
    },{
        url: "/statistics/lowlevel_all",
        data: {level: vm.level, area: vm.area, index: vm.index, sort: 1, date: vm.endDate, lowLevel: vm.lowLevel}
    }];
    
    return param;
}

function loadData(loadArr, vm){
    //获取其他请求的参数
    var reqParams = initReqParams(vm),
        reqPromise = [],
        sendPanelReq = [];
    
    for(i=0; i< loadArr.length; i++){
        var j = loadArr[i];
        var param = reqParams[j];
        if(j == 1){
            sendPanelReq.push(param);
        }else{
            reqPromise.push(httpRequest.get(param.url, {data: param.data}));
        }
    }
    
    //因为中间区域的请求时间较长，所以另外放出来处理
    if(sendPanelReq.length > 0){
        //删除loadArr里的1
        var index = loadArr.indexOf(1);
        loadArr.splice(index, 1);
        statisticAPI.getAVGSocreByMonth(sendPanelReq[0].data).then(function(res){
            if(res.status == 200){
                handleSecondPanelData(res.data, vm);
            }else{
                console.log(res.msg);
            }
        });
    }
    if(reqPromise.length > 0){
        Promise.all(reqPromise).then(function(ress){
            var res1, res2, res3;
            for(var i=0; i<loadArr.length; i++){
                var j = loadArr[i] + 1;
                if(j == 1){
                    res1 = ress[i];
                }
                
                if(j == 3){
                    res3 = ress[i];
                }
                
            }
            if(res1){
                if(res1.status == 200){
                    vm.avg = res1.data.rs.avgCount;
                }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 handleSecondPanelData(data, vm){
    var xData = [],
        yData = [];
    for(i=0; i<data.length; i++){
        var item = data[i];
        xData.push(item.month);
        yData.push(item.socre);
    }
    drawLine(xData, yData, '平均评分', '#12b7f5');
}

function listHandle(data, vm){
    for(i in data){
        var data2 = JSON.parse(data[i]);
        var list = data2.data;
        var topArr = soreRank(getKeyValueArr(list, 'avgCount'));
        var arr = _.map(list, function(o, index){
            var cols = [o.name, o.avgCount || '暂无评分'];
            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,
            cityLevelNoShowTeamTab: true,
            districtLevelNoShowTeamTab: true
        });
    }
}

function drawLine(xData, yData, name, color){
    var lineCharts = echarts.init(document.getElementById('lineChart'));
    
    //处理数据, 数据按照10条数一屏展示
    var lastIndex = xData.length % 10;
    if(xData.length >10 ){  
        dataZoom_end = 100-(9/xData.length)*100;  
    }else{  
        dataZoom_end = 0;
    }
    
    var options = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            top: '0px',
            data: [name],
            borderColor: "#f1f1f1"
        },
        grid: {
            show: false,
            left: '10px',
            right: '30px',
            bottom: '40px',
            top: '20px',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: xData,
            axisLabel: {
                interval:0,//横轴信息全部显示  
                formatter: function (value, index) {
                    return value+"月";
                }
            }
        },
        yAxis: {
            type: 'value',
            axisPointer: {
                snap: true
            },
            scale: true,
            minInterval: 1,
            boundaryGap: ['10%', '30%'],
            splitLine: {show:false}
        },
        dataZoom: [{//给x轴设置滚动条  
            start: dataZoom_end,
            end: 100,
            type: 'slider',
            zoomLock: true,
            showDetail: false
        },{ //下面这个属性是内容区域配置
            start: dataZoom_end,
            end: 100,
            type: 'inside',
            zoomLock: true,
        }],
        series: [{
            name: name,
            type: 'line',
            smooth: true,
            data: yData,
//          color: color,
            lineStyle:{
                normal:{
                    color: color
                }
            },
            itemStyle: {
                normal: {
                    color: color
                }
            }
        }]
    };
    
    $("#lineChart").removeAttr('_echarts_instance_')
    lineCharts.setOption(options);
    window.onresize = function(){
        lineCharts.resize();
    }
}