var reqList = []; //记录请求的参数和url，用于后退时使用
Vue.use(Vuedals.default);
new Vue({
	el: "#main",
	data: {
		appname: "退改签",
		isback: true,
		isrefresh: true,
		isfilter: false,
		isopen: false,
		//请求页面所需参数
		level: '',
		area: '',
		areaTitle: '',
		index: '9',
		selectedDateType: 1, //折线图坐标值1-日，2-周，3-月
		endDate: '',
		startDate: '',
		lowLevel: '',
		chooseYear: '',
		userRole: '',
		//数据结果
		topDatas: {
			index_2: 0,
			index_9: 0,
			index_10: 0
		}
	},
	components: {
		vuedals: Vuedals.Component
	},
	methods: {
		changeTag: function(val) {
			this.index = val;
			loadData([1, 2], this);
			//存储请求所带的参数
			reqList.push({
				level: this.level,
				area: this.area,
				areaTitle: this.areaTitle,
				index: this.index,
				date:this.endDate,
				endDate: this.endDate,
				startDate: this.startDate,
				lowLevel: this.lowLevel
			})
		},
		getNewLineData: function(arg) {
			this.selectedDateType = arg.dateType;
			loadData([1], this);
		},
		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) {
			EventBus.$emit('update-statistics-time', {}); //更新统计时间
			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;
	var now = new Date();
	if(now.getMonth() >= 6) {
		vm.chooseYear = now.getFullYear();
	} else {
		vm.chooseYear = now.getFullYear() - 1;
	}
	vm.startDate = getStartDate(vm.chooseYear);
	vm.endDate = getEndDate(vm.chooseYear);
	//更新头部信息
	EventBus.$emit('update-all-prompt-info', {
		areaName: vm.areaTitle,
		selectDate: "",
		dimensionVal: vm.analysisName
	});
}

function getTopReqParams(index1, vm) {
	var url = "/statistics/index_all",
		data = {
			index: index1,
			level: vm.level,
			area: vm.area,
			startDate: vm.startDate,
			endDate: vm.endDate
		};
	return {
		url: url,
		data: data
	};
}

function getTopTagDatas(vm) {
	var reqs = [],
		indexs = ['2', '9', '10'];
	for(i = 0; i < indexs.length; i++) {
		var item = getTopReqParams(indexs[i], vm);
		reqs.push(httpRequest.get(item.url, {
			data: item.data
		}));
	}
	Promise.all(reqs).then(function(ress) {
		for(i = 0; i < ress.length; i++) {
			var res = ress[i];
			if(res.status == 200) {
				for(key in res.data) {
					vm.topDatas[key] = res.data[key];
				}
			} else {
				console.log(res.msg);
			}
		}
	})
}

function initReqParams(vm) {
	reqParam = [{
		url: "/statistics/interval_total",
		reqType: 'get',
		data: {
			index: vm.index,
			level: vm.level,
			area: vm.area,
			startDate: vm.startDate,
			endDate: vm.endDate,
			interval: vm.selectedDateType
		}
	}, {
		url: "/statistics/lowlevel_all",
		reqType: 'get',
		data: {
			sort: 1,
			date: vm.endDate,
			level: vm.level,
			index: vm.index,
			area: vm.area
		}
	}];
	if(vm.lowLevel) {
		reqParam[1].data.lowLevel = vm.lowLevel;
	}

	return reqParam;
}

function loadData(loadArr, vm) {
	if(loadArr.indexOf(0) > -1) {
		getTopTagDatas(vm);
	}
	//获取其他请求的参数
	var reqParams = initReqParams(vm),
		reqPromise = [],
		newArr = []; //记录非顶部请求的请求数组
	for(i = 0; i < loadArr.length; i++) {
		if(loadArr[i] == 0) {
			// do nothing
		} else {
			var j = loadArr[i] - 1;
			var param = reqParams[j];
			reqPromise.push(httpRequest.get(param.url, {
				data: param.data
			}));
			newArr.push(loadArr[i]);
		}
	}
	if(reqPromise.length > 0) {
		Promise.all(reqPromise).then(function(ress) {
			var res1 = [],
			res2 = [];
			if(ress.length==2){
				res1 = ress[0] || [],
				res2 = ress[1] || [];
			}
			if(loadArr[0]==1){//点击日周月
				res1 = ress[0] || [];
			}
			if(loadArr[0]==2){//点击区、社区
				res2 = ress[0] || [];
			}
			if(res1 && res1.status == 200) {
				handleSecondPanelData(res1.data, vm);
			}
			if(res2) {
				if(res2.status == 200) {
					listHandle(res2.data, vm);
				} else {
					console.log(res2.msg);
				}
			}

		})
	}
}

function handleSecondPanelData(data, vm) {
	var xDatas = [],
		yDatas = [],
		names = [],
		colors = ['#12b7f5'],
		labels = {
			'2': '退签人数新增趋势',
			'9': '待审核数新增趋势',
			'10': '改签人数新增趋势'
		},
		index_names = {
			'index_2': '退签人数',
			'index_9': '待审核数',
			'index_10': '改签人数'
		};
	for(var p in data) {
		names.push(index_names[p]);
		var xData = _.map(data[p].data, function(o) {
			return o.range;
		});
		var yData = _.map(data[p].data, function(o) {
			return o.amount;
		});

		xDatas.push(xData);
		yDatas.push(yData);
	}
	EventBus.$emit("draw-line-chart", {
		panelName: labels[vm.index],
		quotaNames: names,
		xData: xDatas[0],
		yDatas: yDatas,
		colors: colors
	});
}

function listHandle(data, vm) {
	for(i in data) {
		var list = data[i];
		var topArr = [];
		topArr = soreRank(getKeyValueArr(list, 'amount'));
		var arr = _.map(list, function(o, index) {
			var cols = [o.name];
			cols.push(o.amount);

			return {
				rank: topArr[index],
				code: o.code,
				name: o.name,
				cols: cols
			}
		});

		var headers = {
			'2': ["排名", "退签人数"],
			'9': ["排名", "待审核数"],
			'10': ["排名", "改签人数"]
		};

		EventBus.$emit("render-area-data", {
			level: vm.level,
			area: vm.area,
			lowLevel: vm.lowLevel,
			headers: headers[vm.index],
			rows: arr
		});
	}
}