$(function(){
    var circlechart = echarts.init($("[chart='homePage_OverviewcircleChart']").get(0));
    var axischart = echarts.init($("[chart='homePage_StatisticlineChart']").get(0));// 初始化图
    // 折线统计图
    $.ajax({
 		url:"/queryStatsManagement/queryAccountStatistics",
 		cache:false,
 		type:"POST",
 		data:{},
 		error:function(){
 			layer.msg("获取失败");
 		},
 		success:function(data){
 			if(data.success){
 				axisChart(data.data);
 			}
 		}
 	});
    
    function axisChart(obj){
	    axischart.hideLoading();
	    axischart.setOption({
	    	title: {// 标题组件
		        text: '银科保理三年内营业收入对比',
		        x:"center",
		        textStyle:{// 提示文字样式
		    		fontSize:16
		    	}
		    },
		    tooltip: {// 提示框组件
		        trigger: 'axis',
		        formatter:function(params){
		        	var srtDate=[];
		        	for(var i=0;i<params.length;i++){
		        		srtDate[i]=getdata(params[i].seriesIndex,params[i].dataIndex);
		        	}
		        	return params[0].name+"<br/>"+params[0].seriesName+"&nbsp;收入:"+params[0].data+"&nbsp;同比:"+srtDate[0][1]+"<br/>"+
		        		params[1].seriesName+"&nbsp;收入:"+params[1].data+"&nbsp;同比:"+srtDate[1][1]+"<br/>"+
		        		params[2].seriesName+"&nbsp;收入:"+params[2].data+"&nbsp;同比:"+srtDate[2][1]+"<br/>"
		        }
		    },
		    legend: {// 图例
		    	orient:"vertical",
		    	right:"3%",
		    	top:"-1%",
		    	solid:"quare",
		        data:[obj[0].name.toString(),obj[1].name.toString(),obj[2].name.toString()],
		        selectedMode:false
		    },
		    grid: {// 直角坐标系内绘图网格
		        left: '3%',
		        right: '4%',
		        bottom: '3%',
		        containLabel: true
		    },
		    xAxis: {// 直角坐标系grid 中的 x 轴
		        type: 'category',
		        boundaryGap: false,
		        data: ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
		    },
		    yAxis: {// 直角坐标系grid 中的 y 轴
		        type: 'value',
		        name:"千万",
	        	nameLocation:'end',
	        	nameGap:'10'
			},
		    series:obj
	    });
		function getdata(i,j){
			var str=[];
			str[0]=obj[i].name;
			str[1]=obj[i].percent[j];
			str[2]=obj[i].data[j];
			return str;	
		};
	};
	
	// 环形统计图
	var nowdate=getnowDate();
	var loadtime=$('#thisWeekTime').val();
	var piebymysef='<div class="maxdiv"><ul class="week_key"><li><i class="workState_pause"></i>暂停</li><li><i class="workState_continue_next_week"></i>下周继续</li><li><i class="workState_finsh"></i>完成</li><li><i class="workState_overdue"></i>逾期</li><li><i class="workState_stop"></i>终止</li><li><i class="workState_working"></i>进行中</li></ul><div class="largediv"><div class="smalldiv"></div></div></div>';
	 var onload = function onload(thistime){
	 	$.ajax({
	 		url:"/weekwork/queryStatWeekWork",
	 		cache:false,
	 		type:"POST",
	 		data:{'date':thistime},
	 		error:function(){
	 			layer.msg("获取失败");
	 		},
	 		success:function(data){
	
	 			if(data.success){
	 				var dat=eval('('+data.data+')');
	 				$.loadcircleChart(dat);
	 			}
	 		}
	 	});
	 }
	 onload(loadtime);
	// 填充环形图数据--方法
	$.loadcircleChart = function(obj){
		if(obj){
			$("#statistical_chart").find(".maxdiv").remove();
			// 除本周、上周、下周的其他周title的显示方式
			$('#lastWeek').val(obj[0].lastWeek);
			$('#nextWeek').val(obj[0].nextWeek);
			$('#thisWeekTime').val(obj[0].thisWeek)
			circlechart.showLoading();			
	    	circlechart.hideLoading();
	    	var option={
			    color:["#a1a1a1","#fddf87","#83af6e","#000","#d15a44","#3a87ad","#fff"],// 图例颜色// 暂停#a1a1a1 完成#83af6e 终止#d15a44 下周继续#fddf87 进行中#3a87ad 逾期#000
			    tooltip : {// 提示信息
			    	showContent:true,// 是否显示
			    	textStyle:{// 提示文字样式
			    		align:"left",
			    		color:"#fff"
			    	},
			    	showDelay:10,// 显示延迟
			    	enterable:true,// 鼠标是否可提示信息框
			    	borderWidth:2,// 提示框边框
			    	borderColor:"#fff",
			        trigger: 'item',// 提示框触发方式.'item':数据项图形触发，主要在散点图，饼图等无类目轴的图表中使用.'axis':坐标轴触发，主要在柱状图，折线图等会使用类目轴的图表中使用
			        // formatter:
					// "{b}<br/>所占比例:({d}%)<br/>本周数量:{c}<br/>相比上周:"+//提示框格式,这种是字符串模板,其中饼图、仪表盘、漏斗图:
					// {a}（系列名称），{b}（数据项名称），{c}（数值）, {d}（百分比）
			        formatter: function(params,ticket,callback){	        	
			        	return "计划状态:"+params.data.name+"<br/>所占比例:"+params.data.percent+"<br/>本周数量:"+params.data.value	
			        }
			    },
			    legend: {// 图例
			        orient: 'vertical',// 图例排列方式,竖排.horizontal:横排.
			        left: '80%',
			        top:"35%",
			        data:['暂停','下周继续','完成','逾期','终止','进行中']
			    },	    
			    series : [
			        {
			            name: '工作状态',// 提示系列名称
			            type: 'pie',
			            // radius : '60%',//图的大小(缩放) 饼图
			            radius : ['35%','70%'],// 内圈和外圈大小 环形图
			            avoidLabelOverlap: true,// ...
			            center: ['45%', '55%'],// 图(在容器中)的位置
			            //data:obj[1].data,// 数据
			            data:(function(){
			            	fn();
			            	if(obj[1].data.length!=0){			         
			            		return obj[1].data
			            	}else {
			            		return [{value:0, name:'暂停',compare:"1",percent:"0%"},
										{value:0,name:'完成',compare:"2",percent:"0%"},
				    					{value:0,name:'终止',compare:"3",percent:"0%"},
										{value:0,name:'下周继续',compare:"4",percent:"0%"},
				    					{value:0,name:'进行中',compare:"5",percent:"0%"},
				    					{value:0,name:'逾期',compare:"6",percent:"0%"},
				    					{value:1,name:'无计划',compare:"7",percent:"100%",
				    					itemStyle: 
				    						{normal: 
				    							{borderColor:'rgba(193,35,43,1)',
				    							backgroundColor:'white',
				    							label:{
				    								show:true,
				    								color:'rgba(193,35,43,1)',
				    								position:'center', 
													textStyle:{ 
														fontSize:16, 
														color:'black' 
													}, 
												}
											}
										},tooltip:{show:false}
									}
								]		
			            	}
			            	function fn(){
			            		var sum=0;
			            		for(var i=0;i<obj[1].data.length;i++){
									sum+=obj[1].data[i].value;
								}
								var sumdiv='<div class="numofall"><div class="numb"></div><div class="numfont">周计划总量</div></div>';
								$(".homePage_OverviewcircleChart").find(".numofall").remove().end().append(sumdiv);
								if(sum>9999){sum="9999+"}
								$(".numb").empty().text(sum);
			            	}	
			            })(),
			            label: {
			                normal: {
			                    show: false
			                },
			                emphasis: {
			                    show: false
			                }
			            },
			            itemStyle: {
			                emphasis: {// 鼠标 hover 时的高亮样式
			                    shadowBlur: 10,
			                    shadowOffsetX: 0,
			                    shadowColor: 'rgba(0, 0, 0, 0.5)'
			                }
			            }
			        }
			    ]
		    };
		    circlechart.setOption(option);
		}else {
			alert("获取周任务列表失败");
			return;
		}
		//title设置
		var centertitle="52周工作计划"+"(第"+obj[0].thisWeekth+"周)";
		var titlediv='<div class="week_timebox"><span class="week_timebefore"><i class="fa fa-angle-double-left"></i></span><span class="week_time">'+centertitle+'</span><span class="week_timeafter"><i class="fa fa-angle-double-right"></i></span></div>';
		$(".homePage_OverviewcircleChart").find(".week_timebox").remove().end().append(titlediv);
		var setpos=($(".homePage_OverviewcircleChart").width()-$(".week_timebox").width())/2+"px";
		$(".week_timebox").css({"left":setpos})
	}
	// 前一周点击事件
	$("#statistical_chart").delegate(".week_timebefore","click",function(){
		onload($('#lastWeek').val());//重新渲染数据
	})
	//后一周点击
	$("#statistical_chart").delegate(".week_timeafter","click",function(){
		onload($('#nextWeek').val());//后一周重新渲染数据
	})
	circlechart.on('click', function (params) {
		var thisweek=$('#thisWeekTime').val();
		var userId=$('#loginUserId').val();
		$.ajax({
			url:"/weekwork/viewWeekWork",
			cache:false,
			type:"POST",
			error:function(){
				layer.msg("获取数据失败");
			},
			success:function(data){
				if(data){
					$("#loadContent").load("/weekwork/dept_list",function(){
						$(".submenu").hide();
						$("#officeManagement").parent().find(".submenu").eq(0).show();						
						$('#sidebarMenu li').removeClass('active open');
						$("#officeManagement").parent().addClass('active open');
						$("#officeManagement").parent().find(".submenu").eq(0).find("#fiftyTwoManage").parent().addClass('active open').find(".submenu").show();
						$("#officeManagement").parent().find(".submenu").eq(0).find("#fiftyTwoManage").parent().find(".submenu li").eq(2).addClass('active');
						$(".breadcrumb").empty().append("<li><i class='ace-icon fa fa-home home-icon icon_week'></i><a href='javascript:void(0)'>办公管理</a></li><li><a href='javascript:void(0)'>52周工作计划查看</a></li><li><a href='javascript:void(0)'>周计划查看</a></li>");
					});
				}else {
					$("#loadContent").load("/weekwork/page",function(){
						$(".submenu").hide();
						$("#officeManagement").parent().find(".submenu").eq(0).show();						
						$('#sidebarMenu li').removeClass('active open');
						$("#officeManagement").parent().addClass('active open');
						$("#officeManagement").parent().find(".submenu").eq(0).find("#fiftyTwoManage").parent().addClass('active open').find(".submenu").show();
						$("#officeManagement").parent().find(".submenu").eq(0).find("#fiftyTwoManage").parent().find(".submenu li").eq(1).addClass('active');
						$(".breadcrumb").empty().append("<li><i class='ace-icon fa fa-home home-icon icon_week'></i><a href='javascript:void(0)'>办公管理</a></li><li><a href='javascript:void(0)'>52周工作计划查看</a></li><li><a href='javascript:void(0)'>周工作计划</a></li>");
			    		$.ajax({
							url:"/weekwork/do_get_week_work_info",
							cache:false,
							type:"POST",
							data:{'date':thisweek,'userId':userId},
							error:function(){
								layer.msg("获取失败");
							},
							success:function(data){
								filldata(data.data);
							}
						});	
			    	});
				}
			}
		});		
	});
	// 网页高宽发生变化，图形resize一遍
	$(window).resize(function(){
		axischart.resize();
		circlechart.resize();
		var mywidth=$(".maxdiv").width();
		$(".maxdiv").height(mywidth);
		var setpos=($(".homePage_OverviewcircleChart").width()-$(".week_timebox").width())/2+"px";
		$(".week_timebox").css({"left":setpos});
	})
	// 生成当前日期礼拜中的礼拜一
	function getnowDate(){
		var mydate = new Date();
		var month=parseInt(mydate.getMonth())+1;
		var dayliy=parseInt(mydate.getDay());
		if(dayliy==0){
			dayliy=7;
		}
		var day=mydate.getDate()-dayliy+1;
		if (month<10) {month="0"+month}
		if(day<10){day="0"+day}
		return mydate.getFullYear()+'-'+month+'-'+day;
	}
	// 判断两个日期的差值
	function DateDiff(sDate1, sDate2) {  // sDate1和sDate2是yyyy-MM-dd格式
	    var aDate, oDate1, oDate2, iDays;
	    aDate = sDate1.split("-");
	    oDate1 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);  // 转换为yyyy-MM-dd格式
	    aDate = sDate2.split("-");
	    oDate2 = new Date(aDate[1] + '-' + aDate[2] + '-' + aDate[0]);
	    iDays = parseInt((oDate1 - oDate2) / 1000 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
	    return iDays;  // 返回相差天数
	}
	// 设置数字位数多出的位数省略显示
	function control_numbit(){
		$(".homePage_projectNumber").each(function(i){
			var pnum=$(this).text().length;
			if((!i||i==5)&&pnum>2){
				$(this).text('99+');
			}else if(pnum>11){
				$(this).text($(this).text().substring(0,10)+"...");
			}
		})
		$(".process_number").each(function(){
			var pnum=$(this).text().length;
			if(pnum>4){
				$(this).text('9999+');
			}
		})
	}
	control_numbit();
	// 光标移入“业务进行中”各个框
	$("#whole_process").delegate(".process_li","mouseover",function(){
		$(this).find(".process_name,.process_number").addClass("thishover")
	})
	// 业务进行中搜索点击
	$("#business_in_progress").delegate(".search_btn","click",function(){
		var search_txt=$(".search_text").val();
		var userId=$('#loginUserId').val();
		if(!search_txt){
			layer.alert('查询数据为空，查询失败',{"icon":"5"});
		}else{
			/*
			 * $.ajax({ url:"????", type:"POST", dataType:"JSONP",
			 * data:{txt:search_txt,userid:userId} error:function(){
			 * layer.alert("数据查询失败",{"icon":"5"}); }, success:function(data){
			 * if(!data){ layer.alert("查询失败或没有此项数据结果"); return; } } });
			 */
		}
	})
	// 移出
	$("#whole_process").delegate(".process_li","mouseout",function(){
		$(this).find(".process_name,.process_number").removeClass("thishover")
	})
	// 鼠标移入员工统计的各个框
	$("#employee_statistics").delegate(".employee_content","mouseover",function(){
		$(this).find("span").addClass("thishover")
	})
	// 移出
	$("#employee_statistics").delegate(".employee_content","mouseout",function(){
		$(this).find("span").removeClass("thishover")
	});
//业务跳转
	function businessSkip(ele,params){
		pageSkip(
			{
				"firstTarget":$(ele).attr("firstTarget"),//一级菜单id
				"firstTargetChild":$(ele).attr("firstTargetChild")//二级菜单id
			},
			//跳转到列表页时传的参数
			params
		);
	}
	var paramsArgument;
	$(".process_li").click(function(){
		if($(this).hasClass("home_credit")){// 综合授信
			skipParamsArgument = $("#creditStatus").val();
			businessSkip(this,{"statusId":skipParamsArgument});
		}
		if($(this).hasClass("home_financing")){// 项目融资申请
			skipParamsArgument = $("#infinancing").val();
			businessSkip(this,{"statusId":skipParamsArgument});
		}
		
		if($(this).hasClass("home_contract")){// 合同管理
			skipParamsArgument = $("#contractProcessing").val();
			businessSkip(this,{"status":skipParamsArgument});
		}
		if($(this).hasClass("home_postloan")){// 贷后管理
			skipParamsArgument = $("#repaymentloanProcessing").val();
			businessSkip(this,{"statusId":skipParamsArgument});
		}
		if($(this).hasClass("home_finish")){// 已完成项目
			skipParamsArgument = $("#repaymentloanComplete").val();
			businessSkip(this,{"statusId":skipParamsArgument});
		}
	})

	//员工跳转
	$(".employee_content").click(function(){
		if( $(this).attr("skip") ){
			pageSkip(
					{
						"firstTarget":$(this).attr("firstTarget"),//一级菜单id
						"firstTargetChild":$(this).attr("firstTargetChild")//二级菜单id
					}
			);
		}else{
			pageSkip(
					{
						"firstTarget":$(this).attr("firstTarget"),//一级菜单id
						"firstTargetChild":$(this).attr("firstTargetChild")//二级菜单id
					},
					{
						"type":$(this).attr("type")
					}
			);
		}
		
	})
	//待处理跳转
	$(".homePage_pending").click(function(){
		pageSkip(
				{
					"firstTarget":$(this).attr("firstTarget"),//一级菜单id
					"firstTargetChild":$(this).attr("firstTargetChild")//二级菜单id
				}
		);
	});
	//还款异常跳转
	$(".homePage_unusual").click(function(){
		pageSkip(
				{
					"firstTarget":$(this).attr("firstTarget"),//一级菜单id
					"firstTargetChild":$(this).attr("firstTargetChild")//二级菜单id
				},
				{
					"op":"exception"
				}
		);
		
	});

	
	
		
	function filldata(obj){//页面加载时填充本周和下周任务数据
		if(obj){
			//***************正中时间
			var thisWeekTime =  obj.thisWeekStart +' <i class="fa fa-exchange"></i> '+ obj.thisWeekEnd;
			var nextWeekTime =  obj.nextWeekStart +' <i class="fa fa-exchange"></i> '+ obj.nextWeekEnd;
			$('#lastWeek').val(obj.lastWeek);
			$('#nextWeek').val(obj.nextWeek);
			$('#thisWeekTime').val(obj.thisWeek)
			$(".week_time").html(thisWeekTime+'(第'+obj.thisWeekth+'周)');
			var now = moment();
			if(obj.thisWeekWork){//左边周
				$('#add_this_task').attr('weekth',obj.thisWeekth);
				var thisWeekT = moment(obj.thisWeek,"YYYY-MM-DD HH:mm:ss");
				if(thisWeekT>=now||isTimeThisWeek(thisWeekT,now)){
					$('#add_this_task').show();
				}else{
					$('#add_this_task').hide();
				}
				if(thisWeekT>now){
					$('.week_task').find(".week_taskstatus").hide();
				}else{
					$('.week_task').find(".week_taskstatus").show();
				}
				$('#add_this_task').attr('startWeekDay',obj.thisWeek);
				$(".week_task").find(".week_taskstatus i").text("全部");
				$(".week_task").find(".week_taskul").empty();
				$(".week_taskbox").find(".week_task .week_task_time").html(thisWeekTime);
				obj.thisWeekWork.forEach(function(val,index,arr){
					var task1li = '<li startWeekDay="'+obj.thisWeek+'" workId="'+val.id+'" class="week_task_'+(val.level|| '')+'"><p class="week_hidetheme">'+
						(val.title|| '')+'</p><p class="week_hideremark">'+(val.remark|| '')+
						'</p><p class="week_hidereason">'+(val.reason || '')+'</p></li>';
					$(".week_taskbox").find(".week_task .week_taskul").append($(task1li).addClass(val.workState.code).data(val));
				});
			}
			if(obj.nextWeekWork){//右边周
				$('#add_next_task').attr('weekth',obj.nextWeekth);
				var nextWeekT = moment(obj.nextWeek,"YYYY-MM-DD HH:mm:ss");
				if(nextWeekT>=now||isTimeThisWeek(nextWeekT,now)){
					$('#add_next_task').show();
				}else{
					$('#add_next_task').hide();
				}
				if(nextWeekT>now){
					$('.week_task2').find(".week_taskstatus").hide();
				}else{
					$('.week_task2').find(".week_taskstatus").show();
				}
				$('#add_next_task').attr('startWeekDay',obj.nextWeek);
				$(".week_task2").find(".week_taskstatus i").text("全部");
				$(".week_task2").find(".week_taskul").empty();
				$(".week_taskbox").find(".week_task2 .week_task_time").html(nextWeekTime);
				obj.nextWeekWork.forEach(function(val,index,arr){
					var task2li = '<li thisWeek="false" startWeekDay="'+obj.nextWeek+'" workId="'+val.id+'" class="week_task_'+(val.level|| '')+'"><p class="week_hidetheme">'+
						(val.title|| '')+'</p><p class="week_hideremark">'+(val.remark|| '')+
						'</p><p class="week_hidereason">'+(val.reason|| '')+'</p></li>';
					$(".week_taskbox").find(".week_task2 .week_taskul").append($(task2li).addClass(val.workState.code).data(val));
				});
			}
			//设置taskbox高度
			//var taskboxHeight = $(".week_taskbox").find(".week_task").height()>=$(".week_taskbox").find(".week_task2").height()?$(".week_taskbox").find(".week_task").height()+200:$(".week_taskbox").find(".week_task2").height()+200;
			//$(".week_taskbox").height(taskboxHeight);
		}else{
			layer.msg("获取周任务列表失败");
			return;
		}
	};
	function isTimeThisWeek(time,now){
		return time.week()==now.week()&&time.year()==now.year();
	}
	
	
})