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: '18',
		endDate: '',
		lowLevel: '',
		userRole: '',
		//数据结果
		topDatas: {
			sanShiData: 0,
			sanShiRate: '0.00%',
			gaoWeiData: 0,
			gaoWeiRate: '0.00%'
		}
	},
	components: {
		vuedals: Vuedals.Component
	},
	methods: {
		changeTag: function(val) {
			this.index = val;
			loadData([1], this);
			//存储请求所带的参数
			reqList.push({
				level: this.level,
				area: this.area,
				areaTitle: this.areaTitle,
				index: this.index,
				date: this.endDate,
				endDate: this.endDate,
				lowLevel: this.lowLevel
			})
		},
		getAreaData: function(arg) {
			//如果level改变，则需要重新加载整个页面的数据，否则只需加载底部区域数据
			if(arg.level == this.level) {
				this.lowLevel = arg.lowLevel;
				loadData([1], this);
			} else {
				this.level = arg.level;
				this.lowLevel = arg.lowLevel;
				this.area = arg.area;
				this.areaTitle = arg.areaTitle;
				loadData([0, 1], 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,
				lowLevel: this.lowLevel,
			})
		}
	},
	mounted: function() {
		//初始化数据
		initData(this);

		//获得顶部各tab的值
		loadData([0, 1], this); //参数组数表示请求的区域为上中下

		//存储请求所带的参数
		reqList.push({
			level: this.level,
			area: this.area,
			areaTitle: this.areaTitle,
			index: this.index,
			endDate: this.endDate,
			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], vm);
				EventBus.$emit('update-area-name', {areaName: vm.areaTitle});
			}
		});
		//监听页面刷新
		EventBus.$on("refresh-click", function(arg) {
			EventBus.$emit('update-statistics-time', {}); //更新统计时间
			loadData([0, 1], 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;
	vm.endDate = getDateBefore(1);
	//更新头部信息
	EventBus.$emit('update-all-prompt-info', {
		areaName: vm.areaTitle,
		selectDate: "",
		dimensionVal: ""
	});
}

function getTopTagDatas(vm) {
	var reqs = [],
		url = "/statistics/sszq_qwrq_info",
		data = {
			level: vm.level,
			area: vm.area,
			endDate: vm.endDate
		};
	reqs.push(httpRequest.get(url, {
		data: data
	}));
	Promise.all(reqs).then(function(ress) {
		for(i = 0; i < ress.length; i++) {
			var res = ress[i];
			if(res.status == 200) {
				var sszq = res.data.sszq;
				var gwrq = res.data.gwrq;
				vm.topDatas.sanShiData = sszq.amount + "/" + sszq.num;
				vm.topDatas.sanShiRate = sszq.rate == 0 ? '0.00%' : sszq.rate.toString().substring(0, sszq.rate.length - 2) + "%";
				vm.topDatas.gaoWeiData = gwrq.amount + "/" + gwrq.num;
				vm.topDatas.gaoWeiRate = gwrq.rate == 0 ? '0.00%' : gwrq.rate.toString().substring(0, gwrq.rate.length - 2) + "%";
				
				$('#sszql_canvas').waterbubble({
					//txt: res.signRate.rate.substring(0,res.signRate.rate.length-2) + "%",res.signRate.rate/100
					data: sszq.rate / 100,
					waterColor: '#12b7f5',
					lineWidth: 0,
					textColor: 'rgba(0, 0, 0, 0.8)',
					font: 'bold 25px arial'
				});
				
				$('#gaowei_canvas').waterbubble({
					//txt: res.signRate.rate.substring(0,res.signRate.rate.length-2) + "%",res.signRate.rate/100
					data: gwrq.rate / 100,
					waterColor: '#12b7f5',
					lineWidth: 0,
					radius: 75,
					textColor: 'rgba(0, 0, 0, 0.8)',
					font: 'bold 25px arial'
				});

			} else {
				console.log(res.msg);
			}
		}
	})
}

function initReqParams(vm) {
	reqParam = [{
		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[0].data.lowLevel = vm.lowLevel;
	}

	return reqParam;
}

function loadData(loadArr, vm) {
	if(loadArr.indexOf(0) > -1) {
		getTopTagDatas(vm);
	}
	if(vm.level == 2) { //社区管理员不显示团队信息
		return false;
	}
	//获取其他请求的参数
	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 res = ress[0] || [];
			if(res && res.status == 200) {
				listHandle(res.data, vm);
			}

		})
	}
}

function listHandle(data, vm) {
	for(i in data) {
		var list = data[i];
		var topArr = [];
		var resultData = soreQLY(list);
		topArr = soreRank(getKeyValueArr(resultData, 'rate'));
		var arr = _.map(resultData, function(o, index) {
			var cols = [o.name];
			var rate = o.rate ? parseFloat(o.rate).toFixed(2) + "%" : '0.00%';
			cols.push(rate);

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

		var headers = {
			'18': ["排名", "三师转签率"],
			'19': ["排名", "高危人数签约率"]
		};

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

//签约率排序
function soreQLY(arr) {
	var resArr = [];
	for(var i=0;i<arr.length;i++){
		var item = arr[i];
		item.rate = parseFloat(item.rate);
		resArr.push(item)
	}
	 var eventData = _.chain(resArr)
        // 根据date日期字段排序
        .sortBy("rate").reverse()
        // 对集合中每一对象进行处理，返回新的集合
       .map(function (item) {
            
            return {
                amount: item.amount,
                code: item.code,
                rate: item.rate,
                name: item.name,
                num: item.num
            }

        }).value();
	return eventData;
	
}