var reqList = [];
var agePie,
    ageBar;
Vue.use(Vuedals.default);
new Vue({
    el: "#main",
    data: {
        //页面请求参数
        level: '',
        area: '',
        areaTitle: '',
        userRole: {},
        lowLevel: '3', //市级对应lowLevel为3，逐级递减
        dateType: 1, //折线图坐标值1-日，2-周，3-月
        startDate: "",
        endDate: "",
        sDate: "", //折线图中自定义的时间
        eDate: "", //折线图中自定义的时间
        tagCode: 1, //顶部各个tag标签对应的值
        sumType: 1, //记录从筛选页面选择的统计维度 1-订单统计，2-费用统计，3-配送统计，4-年龄统计
        sumTypeName: "订单统计",
        disease: "", //疾病类型
        diseaseName: "全部",
        chooseYear: '',
        dateValue: [],
        orderTagDatas: {
            total: 0,
            finishCount: 0,
            patientCancelCount: 0,
            noReviewedCount: 0,
            processingCount: 0,
            payOuttimeCount: 0
        },
        paymentData: {
            sum: 0,
            avg: 0
        },
        expressData: {
            self: 0,
            doctor: 0,
            delivery: 0
        },
        ageDatas: [
            {name: "0~6岁", color: "#ff5442", value: 0},
            {name: "7~18岁", color: "#ffc800", value: 0},
            {name: "19~30岁", color: "#4ce428", value: 0},
            {name: "31~50岁", color: "#24bbfa", value: 0},
            {name: "51~64岁", color: "#fb5dab", value: 0},
            {name: "65岁以上", color: "#9b5ffd", value: 0}]
    },
    components: {
        vuedals: Vuedals.Component
    },
    mounted: function(){
        //初始化数据
        initData(this);
        
        //获得顶部各tab的值
        loadData([0,1,2], this); //参数组数表示请求的区域为上中下
        
        //存储请求所带的参数
        reqList.push({
            level: this.level,
            area: this.area,
            areaTitle: this.areaTitle,
            endDate: this.endDate,
            startDate: this.startDate,
            lowLevel: this.lowLevel,
            tagCode: this.tagCode,
            sumType: this.sumType,
            disease: this.disease,
            dateType: this.dateType
        });
        
        //设置监听器， 监听折线图日期变化
        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.tagCode = info.tagCode;
                vm.sumType = info.sumType;
                vm.disease = info.disease;
                vm.dateType = info.dateType;
                
                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){
                    vm.sumType = data.sumType;
                    vm.sumTypeName = data.sumTypeName;
                    vm.disease = data.disease;
                    vm.diseaseName = data.diseaseName;
                    var newYear = false;
                    if(vm.chooseYear != data.chooseYear){
                        newYear = true;
                    }
                    vm.chooseYear = data.chooseYear;
                    
                    vm.startDate = getStartDate(vm.chooseYear);
                    vm.endDate = getEndDate(vm.chooseYear)
                    if(newYear){
                        vm.dateValue = [vm.startDate, vm.endDate];
                    }
                    
                    vm.sDate = vm.dateValue[0];
                    vm.eDate = vm.dateValue[1];
                    
                    //将参数职位初始值
                    vm.level = vm.userRole.code == '350200' ? 4 : vm.userRole.code.length == 6 ? 3 : 2;
                    vm.lowLevel = vm.level - 1;
                    vm.area = vm.userRole.code;
                    vm.areaTitle = vm.userRole.name;
                    vm.dateType = 1;
                    vm.tagCode = 1;
                    EventBus.$emit('update-area-name', {areaName: vm.areaTitle});
                    
                    //然后清空请求列表数组
                    reqList.splice(0, reqList.length);
                    
                    loadData([0, 1, 2], vm);//刷新数据
                    //存储请求所带的参数
                    reqList.push({
                        level: vm.level,
                        area: vm.area,
                        areaTitle: vm.areaTitle,
                        endDate: vm.endDate,
                        startDate: vm.startDate,
                        lowLevel: vm.lowLevel,
                        tagCode: vm.tagCode,
                        sumType: vm.sumType,
                        disease: vm.disease,
                        dateType: vm.dateType
                    });
                    EventBus.$emit('update-statistics-year',{selectDate: vm.chooseYear} );//显示统计维度的名称
                    EventBus.$emit('update-dimension-name', {dimensionVal: vm.sumTypeName});//显示疾病类型的名称
                    EventBus.$emit('update-dimension2-name', {dimensionVal2: vm.diseaseName});//显示疾病类型的名称
                    EventBus.$emit('update-statistics-time', {});//更新统计时间
                },
                component: 'prescription-filter',
                props: {
                    sumType: vm.sumType,
                    disease: vm.disease,
                    chooseYear: vm.chooseYear
                }
            });
        });
        $("#main").removeClass("c-hide");
        window.onresize = function() {
            if(agePie){
                agePie.resize();
            }
            if(ageBar){
                ageBar.resize();
            }
            if(window.lineCharts){
                window.lineCharts.resize(); //日周月折线图
            }
            if(window.barCharts){
                window.barCharts.resize(); //日周月折线图
            }
        }
    },
    methods: {
        changeTagCode: function(val){
            this.tagCode = val;
            if(this.sumType == 2){
                //费用统计只查看人均费用的变化趋势
                loadData([2], this);
            }else{
                loadData([1,2], this);
            }
            //存储请求所带的参数
            reqList.push({
                level: this.level,
                area: this.area,
                areaTitle: this.areaTitle,
                endDate: this.endDate,
                startDate: this.startDate,
                lowLevel: this.lowLevel,
                tagCode: this.tagCode,
                sumType: this.sumType,
                disease: this.disease,
                dateType: this.dateType
            })
        },
        getBarData: function(arg){
            this.dateType = arg.dateType || this.dateType;
            var dateValue = arg.dateValue;
            if(dateValue){
                this.dateValue = arg.dateValue;
                this.sDate = dateValue[0];
                this.eDate = dateValue[1];
            }
            loadData([1], this);
        },
        getPaymentLineData: function(arg){
            this.dateType = arg.dateType;
            loadData([1], this);
        },
        getBottomAreaData: function(arg){
            //如果level改变，则需要重新加载整个页面的数据，否则只需加载底部区域数据
            if(arg.level == this.level){
                this.lowLevel = arg.lowLevel || 3;
                loadData([2], this);
            }else{
                this.level = arg.level;
                //长处方这边level改了lowLevel也需要跟着一起变
                this.lowLevel = arg.level - 1;
                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,
                endDate: this.endDate,
                startDate: this.startDate,
                lowLevel: this.lowLevel,
                tagCode: this.tagCode,
                sumType: this.sumType,
                disease: this.disease,
                dateType: this.dateType
            })
        },
        exportData: function(){
            var sheet = XLSX.utils.table_to_sheet($('#listTable')[0]);
            var disease = this.diseaseName == "全部" ? "" : this.diseaseName,
                areaName = this.area == "350200" ? "厦门市" : this.areaTitle,
                fileName = areaName + disease;
            switch(this.sumType){
                case 1:
                    var names = ["续方总量", "已完成", "居民取消", "审核未通过", "进行中", "其他原因取消"];
                    fileName += names[this.tagCode - 1];
                    if(this.tagCode > 1){
                        fileName += "订单";
                    }
                    break;
                case 2:
                    var names = ["费用总计", "人均费用"];
                    fileName += "续方"+names[this.tagCode -1];
                    break;
                case 3:
                    var names = ["居民自取", "物流配送", "健管师配送"];
                    fileName += names[this.tagCode - 1] + "订单";
                    break;
                case 4:
                    fileName += "续方人数";
                    break;
                default:
                    fileName += "续方情况";
                    break;
            }
            
            openDownloadDialog(sheet2blob(sheet), fileName+'.xlsx');
        }
    }
});

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.lowLevel = vm.level - 1;
    vm.area = vm.userRole.code;
    vm.areaTitle = vm.userRole.name;
    var now = new Date(),
        year = now.getFullYear();
    if(now.getMonth() < 6){
        vm.chooseYear = year - 1;
    }else {
        vm.chooseYear = year;
    }
    vm.startDate = vm.sDate = getStartDate(vm.chooseYear);
    vm.endDate = vm.eDate = getEndDate(vm.chooseYear);
    
    vm.dateValue = [vm.sDate, vm.eDate];
    
    EventBus.$emit('update-area-name', {areaName: vm.areaTitle});
    
    var now = new Date();
    vm.endDate = now.format("yyyy-MM-dd");
    
    EventBus.$emit('update-statistics-year',{selectDate: vm.chooseYear} );
    EventBus.$emit('update-dimension-name', {dimensionVal: vm.sumTypeName});//显示统计维度的名称
    EventBus.$emit('update-dimension2-name', {dimensionVal2: vm.diseaseName});//显示疾病类型的名称
}

function initReqParams(vm){
    //sumType: 1-订单统计，2-费用统计，3-配送统计，4-年龄统计
    var reqParam = [];
    switch(vm.sumType){
        case 1: 
            //tagCode: 1.总量，2.已完成，3.居民取消，4.审核不通过，5.进行中，6.其他原因取消
            reqParam = [{
                url: "/statistics/getPrescriptionCount",
                data: {level: vm.level, area: vm.area, disease: vm.disease, year: vm.chooseYear}
            },{
                url: "/statistics/getPrescriptionTotalHistogram",
                data: {level: vm.level, area: vm.area, disease: vm.disease, type: vm.tagCode, interval: vm.dateType, year: vm.chooseYear, startTime: vm.sDate, endTime: vm.eDate}
            },{
                url: "/statistics/getPrescriptionTotalLowLevel",
                data: {level: vm.level, lowlevel: vm.lowLevel, area: vm.area, disease: vm.disease, type: vm.tagCode, year: vm.chooseYear, startTime: vm.startDate, endTime: vm.endDate}
            }];
            break;
        case 2: 
            //dateType: 折线图坐标值1-日，2-周，3-月
            //tagCode: 1.总量，2.平均值
//          vm.startDate = getBeforeMonthStartDate(3, vm.dateType);
            reqParam = [{
                url: "/statistics/getPrescriptionCost",
                data: {level: vm.level, area: vm.area, disease: vm.disease, year: vm.chooseYear}
            },{
                url: "/statistics/getPrescriptionCostAvgLine",
                data: {level: vm.level, area: vm.area, disease: vm.disease, type: vm.dateType, year: vm.chooseYear, startDate: vm.startDate, endDate: vm.endDate}
            },{
                url: "/statistics/getPrescriptionCostLowLevel",
                data: {level: vm.level, lowlevel: vm.lowLevel, area: vm.area, disease: vm.disease, type: vm.tagCode, year: vm.chooseYear, startTime: vm.startDate, endTime: vm.endDate}
            }];
            break;
        case 3: 
            //tagCode: 1.自取，2.快递配送，3.健管师配送
            reqParam = [{
                url: "/statistics/getPrescriptionDispatchingTotal",
                data: {level: vm.level, area: vm.area, disease: vm.disease, year: vm.chooseYear}
            },{
                url: "/statistics/getPrescriptionDispatchingHistogram",
                data: {level: vm.level, area: vm.area, disease: vm.disease, type: vm.tagCode, interval: vm.dateType, year: vm.chooseYear, startTime: vm.sDate, endTime: vm.eDate}
            },{
                url: "/statistics/getPrescriptionDispatchingLowLevel",
                data: {level: vm.level, lowlevel: vm.lowLevel, area: vm.area, disease: vm.disease, type: vm.tagCode, year: vm.chooseYear, startTime: vm.startDate, endTime: vm.endDate}
            }];
            break;
        case 4: 
            reqParam = [{
                url: "/statistics/getPrescriptionAgeTotal",
                data: {level: vm.level, area: vm.area, disease: vm.disease, year: vm.chooseYear}
            },{
                url: "/statistics/getPrescriptionAgeHistogram",
                data: {level: vm.level, area: vm.area, disease: vm.disease, year: vm.chooseYear, startTime: vm.startDate, endTime: vm.endDate}
            },{
                url: "/statistics/getPrescriptionAgeLowLevel",
                data: {level: vm.level, lowlevel: vm.lowLevel, area: vm.area, disease: vm.disease, year: vm.chooseYear, startTime: vm.startDate, endTime: vm.endDate}
            }];
            break;  
        default:
            reqParam = [];
            break;
    };
    
    return reqParam;
}

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){
    switch(vm.sumType){
        case 1:
            vm.orderTagDatas = {
                total: data.total,
                finishCount: data.finishCount,
                patientCancelCount: data.patientCancelCount,
                noReviewedCount: data.noReviewedCount,
                processingCount: data.processingCount,
                payOuttimeCount: data.payOuttimeCount
            };
            break;
        case 2:
            vm.paymentData = {
                sum: data.sum,
                avg: data.avg
            }
            break;
        case 3:
            vm.expressData = {
                self: data.seltTotal,
                doctor: data.doctorTotal,
                delivery: data.deliveryTotal
            }
            break;
        case 4:
            var len = vm.ageDatas.length,
                color = ['#ff5442', '#ffc800 ','#4ce428', '#24bbfa','#fb5dab', "#9b5ffd"],
                objName = ['0age', '7age', '19age', '31age', '51age', '65age'],
                arr = [];
            for(i=0; i<len; i++){
                vm.ageDatas[i].value = data[objName[i]];
            }
            //绘制饼图
            agePie = drawPieChart("agePie", vm.ageDatas, color);
    }
}

function handleSecondPanelData(data, vm){
    switch(vm.sumType){
        case 1:
        case 3:
            var color = "#17b3ec",
                xAxisData = [],
                seriesData = [];
            for(i=0; i<data.length; i++){
                var item = data[i];
                xAxisData.push(item.date);
                seriesData.push(item.count);
            }
            var names,panelName;
            if(vm.sumType == 1){
                names = ["续方总量", "已完成", "居民取消", "审核未通过", "进行中", "其他原因取消"];
                panelName = "续方订单趋势";
            }else if(vm.sumType == 3){
                panelName = "订单配送趋势";
                names = ["居民自取", "物流配送", "健管师配送"];
            }
//          EventBus.$emit("draw-bar-chart", {
//              panelName: "近半年统计",
//              xData: xAxisData,
//              yData: seriesData,
//              quotaName: names[vm.tagCode - 1],
//              color: color,
//              unit: "笔",
//              selectedDateType: vm.dateType
//          });
            
            EventBus.$emit("draw-line-chart", {
                panelName : panelName,
                quotaNames : ["订单数"],
                xData : xAxisData,
                yDatas : [seriesData],
                colors : [color],
                unit: "笔",
                selectedDateType: vm.dateType,
                dateValue: vm.dateValue,
                chooseYear: vm.chooseYear
            });
            break;
        case 2:
            var yDatas = [],
                colors = ['#12b7f5'];
                
            var xData = _.map(data, function(o){
                return o.date;
            });
            var yData = _.map(data, function(o){
                return o.avg;
            });
            yDatas.push(yData);
            
            EventBus.$emit("draw-line-chart", {
                panelName : "人均费用趋势",
                quotaNames : ["人均费用"],
                xData : xData,
                yDatas : yDatas,
                colors : colors,
                unit: "元",
                selectedDateType: vm.dateType
            });
            break;
        case 4: 
            var color = "#17b3ec",
                xAxisData = ['0~6岁', '7~18岁', '19~30岁', '31~50岁', '51~64岁', '65岁以上'],
                fieldName = ['0ageRate', '7ageRate', '19ageRate', '31ageRate', '51ageRate', '65ageRate']
                seriesData = [];
            for(i=0; i<6; i++){
                seriesData.push(data[fieldName[i]]);
            }
            
            ageBar = drawBarChart("ageBar", xAxisData, seriesData, color, "人均使用次数");
            break;
    }
}

function listHandle(data, vm){
    var list = data;
    var topArr = soreRank(getKeyValueArr(list, 'val'));
    var arr = _.map(list, function(o, index){
        var cols = [o.name, o.val];
        return {
            rank: topArr[index],
            code: o.code,
            name: o.name,
            cols: cols
        }
    });
    var headers = {
        '1': ["排名", "续方总量", "已完成", "居民取消", "审核未通过", "进行中", "其他原因取消"],
        '2': ["排名", "费用总计", "人均费用"],
        '3': ["排名", "居民自取", "物流配送", "健管师配送"],
        '4': ["排名", "总人数"]
    };
    EventBus.$emit("render-area-data",{
        level: vm.level,
        area: vm.area,
        lowLevel: vm.lowLevel,
        headers:["排名", headers[vm.sumType][vm.tagCode]],
        rows: arr
    });
}

/*
 * months :  月份差距（例如months=3，则获取今天往前数3个月的那天的值）
 */
function getBeforeMonthStartDate(months,type){
    //type: 折线图坐标值1-日，2-周，3-月
    //从1号开始算每个月开始的时间
    var sDate = new Date(),
        now = new Date();
    
    sDate.setMonth(now.getMonth() - months + 1);// 包含本月算一个月
    
    var sDateStr = sDate.format("yyyy-MM-dd");
    var startDate = "";
    if(type == '3'){
        startDate = sDateStr.substr(0,8)+"01";
    }else{
        startDate = sDateStr;
    }
    return startDate;
}