$(function() {
	//根据年份获取本年的所有周数据
	function getWeekNumDetail(year){
		var weekdetail=[];
		$.ajax({
         	url: '/weekWorkPlan/do_getWeeks',
         	dataType: 'json',
         	async:false,
		 	data: {
             	'year':year
         	},
         	success: function(data) { // 获取当前月的数据
            	if(data.success){
            		weekdetail=data.data
            	}
         	},
        	error:function(error){
        		new $.zui.Messager('获取所有周出错：'+error, {
				    type: 'warning',
				    time:1500
				}).show();
        	}
    		});
		return weekdetail;
	}
	function loadData(obj) {
		if (obj) {
			// 本周周数
			if (!$("#presentWeekth").hasClass("presentWeekth")) {
				$("#presentWeekth").addClass("presentWeekth").val(obj.currentWeekth);
			}
			// 头部时间的渲染
			$("#thisWeekTime").val(obj.thisWeek);
			$("#lastWeek").val(obj.lastWeekFirstDay);
			$("#nextWeek").val(obj.nextWeekFirstDay);
			$(".weekwork-dateRange").text(obj.startTime + '~' + obj.endTime);
			if(parseInt(obj.weekth)<10){
				$(".weekwork-weekth-dropdown").text('0'+obj.weekth);
			}else {
				$(".weekwork-weekth-dropdown").text(obj.weekth);
			}
			if (!$("#weekYearth").hasClass("weekYearth")) {
				$("#weekYearth").addClass("weekYearth").val(obj.currentYear);
				$("#presentYearth").val(obj.currentYear);
			}
			$(".weekwork-yearth-dropdown").text($("#weekYearth").val());
			/* 头部下拉框的渲染 */
			//年的下拉框
		    var yearL='';
		    var weekL='';
		    for(var i=1970;i<=2116;i++){
		        if(parseInt($("#weekYearth").val())==i){
		            yearL+='<li class="actived" data-index="'+i+'"><a javascript:void(0)>'+i+'</a></li>';
		        }else {
		            yearL+='<li data-index="'+i+'"><a javascript:void(0)>'+i+'</a></li>';
		        }
		    }
		    $(".btn-group-weekcenter .year-dropdown-menu").empty().append(yearL);
		    //周的下拉框
		    var weekindex=obj.weekth;
		    var weekdetail=getWeekNumDetail($("#weekYearth").val());
		    for(var z=0;z<weekdetail.length;z++){
		    	if(weekindex==weekdetail[z].week){
		    		weekL+='<li class="actived" data-index="'+weekdetail[z].week+'"><a javascript:void(0)>'+weekdetail[z].week+'周<span class="dateSlot">('+weekdetail[z].startDate+'~'+weekdetail[z].endDate+')</span></a></li>';
		    	}else {
		    		weekL+='<li data-index="'+weekdetail[z].week+'"><a javascript:void(0)>'+weekdetail[z].week+'周<span class="dateSlot">('+weekdetail[z].startDate+'~'+weekdetail[z].endDate+')</span></a></li>';
		    	}
		    }
		    $(".btn-group-weekcenter .week-dropdown-menu").empty().append(weekL);
			//清空本周下周数据
			$(".thisWeek-work-plan").find(".week-plan_taskul").empty();
			$(".nextWeek-work-plan").find(".week-plan_taskul").empty();
			var thisweekth = parseInt(obj.weekth);
			var presentweekth = parseInt($("#presentWeekth").val());
			var thisYear=parseInt(obj.currentYear);
			var presentyearth=parseInt($("#weekYearth").val());
			var nowyear=parseInt($("#presentYearth").val());
			if(thisYear==nowyear){//属于本年
				if (thisweekth == presentweekth) {
					$(".thisWeek-work-plan").find(".work-plan-title").empty().html("本周");
					$(".nextWeek-work-plan").find(".work-plan-title").empty().html("下周");
				} else if (thisweekth + 1 == presentweekth) {
					$(".thisWeek-work-plan").find(".work-plan-title").empty().html("上周");
					$(".nextWeek-work-plan").find(".work-plan-title").empty().html("本周");
				} else if (thisweekth - 1 == presentweekth) {
					$(".thisWeek-work-plan").find(".work-plan-title").empty().html("下周");
					$(".nextWeek-work-plan").find(".work-plan-title").empty().html(obj.nextStartTime + '~'+ obj.nextEndTime);
				} else if (thisweekth + 2 == presentweekth) {
					$(".thisWeek-work-plan").find(".work-plan-title").empty().html(obj.startTime + '~' + obj.endTime);
					$(".nextWeek-work-plan").find(".work-plan-title").empty().html("上周");
				} else {
					$(".thisWeek-work-plan").find(".work-plan-title").empty().html(obj.startTime + '~' + obj.endTime);
					$(".nextWeek-work-plan").find(".work-plan-title").empty().html(obj.nextStartTime + '~'+ obj.nextEndTime);
				}
			}else {//不属于本年
				$(".thisWeek-work-plan").find(".work-plan-title").empty().html(obj.startTime + '~' + obj.endTime);
				$(".nextWeek-work-plan").find(".work-plan-title").empty().html(obj.nextStartTime + '~'+ obj.nextEndTime);
			}
			
			// 本周数据的渲染
			if (!obj.weekWorkPlanList.length) {
				$(".thisWeek-work-plan").find(".work-plan-title").html($(".thisWeek-work-plan").find(".work-plan-title").html()+ "暂无计划");
				$(".thisWeek-work-plan").find(".dropdown").remove();
			} else {
				var li = '';
				for (var i = 0; i < obj.weekWorkPlanList.length; i++) {
					var urgent = '';
					if (obj.weekWorkPlanList[i].level == "urgent") {
						urgent = "week_task_urgent";
					} else {
						urgent = "week_task_normal";
					}
					li += '<li workid="'+obj.weekWorkPlanList[i].id+'" class="week_plan_taskli '+urgent+' '+obj.weekWorkPlanList[i].workState.code+'" style="top: 0px;"><p class="week-plan-title"><span>标题：</span><span class="content-span">'
							+ obj.weekWorkPlanList[i].title
							+ '</span></p><p class="week-plan-date"><span>时间：</span><span class="content-span">'
							+ obj.weekWorkPlanList[i].workTime
							+ '</span></p><p class="week-plan-content"><span>内容：</span><span class="content-span">'
							+ obj.weekWorkPlanList[i].workContent
							+ '</span></p><div class="week-work-operation">';
					var editele = '<i class="icon icon-trash" data-trashid="'+obj.weekWorkPlanList[i].id+'"></i><i class="icon icon-edit" data-editid="'+obj.weekWorkPlanList[i].id+'"></i>';
					//本周之前的数据都不能修改
					if( parseInt($("#presentYearth").val())==parseInt($("#weekYearth").val()) ){//此时显示的数据是本年的数据
						if (parseInt(obj.weekWorkPlanList[i].weekth) >= parseInt($("#presentWeekth").val())) {//再判断周数
							li += editele;
						}
					}else if( parseInt($("#presentYearth").val())<parseInt($("#weekYearth").val()) ){//此时显示的数据是本年以后的数据
						li += editele;
					}
					li += '<i class="icon icon-search" data-searchid="'+obj.weekWorkPlanList[i].id+'"></i></div></li>';
				}
				$(".thisWeek-work-plan").find(".week-plan_taskul").append(li);
				//计划状态下拉框
				var select = '<div class="dropdown"><button class="btn btn-white btn-info" type="button" data-toggle="dropdown" style="margin-bottom:0;">全部状态 <span class="caret" style="margin-left:0.05rem;border-width:0.05rem;"></span></button><ul class="dropdown-menu" style="min-width:1.2rem;padding:0.05rem 0;"></ul></div>';
				if( parseInt($("#presentYearth").val())==parseInt($("#weekYearth").val()) ){
					if (parseInt(obj.weekWorkPlanList[0].weekth) <= parseInt($("#presentWeekth").val())) {//本周或之前周
						$(".work-plan-body .thisWeek-work-plan").find(".dropdown").remove();
						$(".work-plan-body .thisWeek-work-plan").find(".work-plan-title").before(select);
						$(".work-plan-body .thisWeek-work-plan .dropdown").find(".dropdown-menu").empty();
						if (parseInt(obj.weekWorkPlanList[0].weekth) == parseInt($("#presentWeekth").val())) {//本周
							var options = '<li class="week_statusall"><a javascript:void(0)>全部</a></li><li class="week_statusdoing"><a javascript:void(0)>进行中</a></li><li class="week_statusfinish"><a javascript:void(0)>完成</a></li><li class="week_statuscontinue"><a javascript:void(0)>下周继续</a></li><li class="week_statuspause"><a javascript:void(0)>暂停</a></li><li class="week_statusstop"><a javascript:void(0)>终止</a></li>';
							$(".work-plan-body .thisWeek-work-plan").find(".dropdown-menu").append(options);
						} else {//上周
							var options = '<li class="week_statusall"><a javascript:void(0)>全部</a></li><li class="week_statusfinish"><a javascript:void(0)>完成</a></li><li class="week_statuscontinue"><a javascript:void(0)>下周继续</a></li><li class="week_statuspause"><a javascript:void(0)>暂停</a></li><li class="week_statusstop"><a javascript:void(0)>终止</a></li><li class="week_statusoverdue"><a javascript:void(0)>逾期</a></li>';
							$(".work-plan-body .thisWeek-work-plan").find(".dropdown-menu").append(options);
						}
					} else {//之后周
						$(".work-plan-body .thisWeek-work-plan .dropdown").remove();
					}
				}else if( parseInt($("#presentYearth").val())>parseInt($("#weekYearth").val()) ){//此时显示的数据是本年之前的数据
					$(".work-plan-body .thisWeek-work-plan").find(".dropdown").remove();
					$(".work-plan-body .thisWeek-work-plan").find(".work-plan-title").before(select);
					$(".work-plan-body .thisWeek-work-plan .dropdown").find(".dropdown-menu").empty();
					var options = '<li class="week_statusall"><a javascript:void(0)>全部</a></li><li class="week_statusfinish"><a javascript:void(0)>完成</a></li><li class="week_statuscontinue"><a javascript:void(0)>下周继续</a></li><li class="week_statuspause"><a javascript:void(0)>暂停</a></li><li class="week_statusstop"><a javascript:void(0)>终止</a></li><li class="week_statusoverdue"><a javascript:void(0)>逾期</a></li>';
					$(".work-plan-body .thisWeek-work-plan").find(".dropdown-menu").append(options);
				}else {//本年之后的数据，只有一种状态
					$(".work-plan-body .thisWeek-work-plan .dropdown").remove();
				}
			}

			// 下周数据的渲染
			if (!obj.nextWeekWorkPlanList.length) {
				$(".nextWeek-work-plan").find(".work-plan-title").html($(".nextWeek-work-plan").find(".work-plan-title").html()+ "暂无计划");
				$(".nextWeek-work-plan").find(".dropdown").remove();
			} else {
				var li = '';
				for (var j = 0; j < obj.nextWeekWorkPlanList.length; j++) {
					var urgent = '';
					if (obj.nextWeekWorkPlanList[j].level == "urgent") {
						urgent = "week_task_urgent";
					} else {
						urgent = "week_task_normal";
					}
					li += '<li workid="'+obj.nextWeekWorkPlanList[j].id+'" class="week_plan_taskli '+urgent+' '+obj.nextWeekWorkPlanList[j].workState.code+'" style="top: 0px;"><p class="week-plan-title"><span>标题：</span><span class="content-span">'
							+ obj.nextWeekWorkPlanList[j].title
							+ '</span></p><p class="week-plan-date"><span>时间：</span><span class="content-span">'
							+ obj.nextWeekWorkPlanList[j].workTime
							+ '</span></p><p class="week-plan-content"><span>内容：</span><span class="content-span">'
							+ obj.nextWeekWorkPlanList[j].workContent
							+ '</span></p><div class="week-work-operation">';
					var editele = '<i class="icon icon-trash" data-trashid="'+obj.nextWeekWorkPlanList[j].id+'"></i><i class="icon icon-edit" data-editid="'+obj.nextWeekWorkPlanList[j].id+'"></i>';
					//本周之前的数据都不能修改
					if( parseInt($("#presentYearth").val())==parseInt($("#weekYearth").val()) ){//此时显示的数据是本年的数据
						if (parseInt(obj.nextWeekWorkPlanList[j].weekth) >= parseInt($("#presentWeekth").val())) {
							li += editele;
						}
					}else if( parseInt($("#presentYearth").val())<parseInt($("#weekYearth").val()) ){//此时显示的数据是本年以后的数据
						li += editele;
					}
					li += '<i class="icon icon-search" data-searchid="'+obj.nextWeekWorkPlanList[j].id+'"></i></div></li>';
				}
				$(".nextWeek-work-plan").find(".week-plan_taskul").empty().append(li);
				var select = '<div class="dropdown"><button class="btn btn-white btn-info" type="button" data-toggle="dropdown" style="margin-bottom:0;">全部状态 <span class="caret" style="margin-left:0.05rem;border-width:0.05rem;"></span></button><ul class="dropdown-menu" style="min-width:1.2rem;padding:0.05rem 0;"></ul></div>';
				if( parseInt($("#presentYearth").val())==parseInt($("#weekYearth").val()) ){//此时显示的数据是本年的数据
					if (parseInt(obj.nextWeekWorkPlanList[0].weekth) <= parseInt($("#presentWeekth").val())) {//本周或之前周
						$(".work-plan-body .nextWeek-work-plan").find(".dropdown").remove();
						$(".work-plan-body .nextWeek-work-plan").find(".work-plan-title").before(select);
						$(".work-plan-body .nextWeek-work-plan .dropdown").find(".dropdown-menu").empty();
						if (parseInt(obj.nextWeekWorkPlanList[0].weekth) == parseInt($("#presentWeekth").val())) {//本周
							var options = '<li class="week_statusall"><a javascript:void(0)>全部</a></li><li class="week_statusdoing"><a javascript:void(0)>进行中</a></li><li class="week_statusfinish"><a javascript:void(0)>完成</a></li><li class="week_statuscontinue"><a javascript:void(0)>下周继续</a></li><li class="week_statuspause"><a javascript:void(0)>暂停</a></li><li class="week_statusstop"><a javascript:void(0)>终止</a></li>';
							$(".work-plan-body .nextWeek-work-plan").find(".dropdown-menu").append(options);
						} else {//之前周
							var options = '<li class="week_statusall"><a javascript:void(0)>全部</a></li><li class="week_statusfinish"><a javascript:void(0)>完成</a></li><li class="week_statuscontinue"><a javascript:void(0)>下周继续</a></li><li class="week_statuspause"><a javascript:void(0)>暂停</a></li><li class="week_statusstop"><a javascript:void(0)>终止</a></li><li class="week_statusoverdue"><a javascript:void(0)>逾期</a></li>';
							$(".work-plan-body .nextWeek-work-plan").find(".dropdown-menu").append(options);
						}
					} else {//之后周，只有一种状态
						$(".work-plan-body .nextWeek-work-plan .dropdown").remove();
					}
				}else if( parseInt($("#presentYearth").val())>parseInt($("#weekYearth").val()) ){//此时显示的数据是本年之前的数据
					$(".work-plan-body .nextWeek-work-plan").find(".dropdown").remove();
					$(".work-plan-body .nextWeek-work-plan").find(".work-plan-title").before(select);
					$(".work-plan-body .nextWeek-work-plan .dropdown").find(".dropdown-menu").empty();
					var options = '<li class="week_statusall"><a javascript:void(0)>全部</a></li><li class="week_statusfinish"><a javascript:void(0)>完成</a></li><li class="week_statuscontinue"><a javascript:void(0)>下周继续</a></li><li class="week_statuspause"><a javascript:void(0)>暂停</a></li><li class="week_statusstop"><a javascript:void(0)>终止</a></li><li class="week_statusoverdue"><a javascript:void(0)>逾期</a></li>';
					$(".work-plan-body .nextWeek-work-plan").find(".dropdown-menu").append(options);
				}else {//本年之后的数据，只有一种状态
					$(".work-plan-body .nextWeek-work-plan .dropdown").remove();
				}
			}

		} else {
			alert("获取列表失败");
		}
	}
	
	//下拉框按钮的点击事件:使当前的时间（年份或月份）显示在下拉框的第一位
	$(".btn-group-weekcenter").delegate(".btn-group .dropdown-toggle","click",function(){
		if(!$(this).parent().hasClass('open')){
			var that=$(this);
			var h=parseInt($(this).next().find(".actived").data("index"))-parseInt($(this).next().children("li:first-child").data("index"));
			setTimeout(function(){
				var scrollHeight=that.next().find(".actived").get(0).clientHeight;
				that.next().scrollTop(h*scrollHeight);
			},10)

		}
	})
	//  prev/next 点击事件
	$(".btn-group-weekcenter").delegate(".prev_next_btn .btn", "click",function() {
		var weekTime,newtime;
		if($(this).hasClass("year_prev_btn")||$(this).hasClass("year_next_btn")){//点击年
			var weekoption=parseInt($(this).parent().next().find(".week-dropdown-menu .actived").data("index"));
			var year=parseInt($(this).parent().prev().find(".dropdown-toggle").text());
			$(this).hasClass("year_prev_btn")?year--:year++;//上一年减 下一年加
			$("#weekYearth").addClass("weekYearth").val(year);
			var weekdetail=getWeekNumDetail(year);
			for(w=0;w<weekdetail.length;w++){
				if(weekdetail[w].week==weekoption){
					newtime=weekdetail[w].startDate;
					break;
				}
			}
			if(!newtime){//选择的这一年没有之前年的周数（即选择的这一年周数比较少）
				newtime=weekdetail[weekdetail.length-1].startDate
			}
			weekTime=year+'-'+newtime;
		}else {
			if($(this).hasClass("week_prev_btn")){//上周
				weekTime = $("#lastWeek").val();
				var index=parseInt($(this).parent().prev().find(".week-dropdown-menu .actived").data("index"));
				if(index==1){
					var year=parseInt($("#weekYearth").val());
					year--;
					$("#weekYearth").val(year);
				}
			}else {//下周
				weekTime = $('#nextWeek').val();
				if($(this).parent().prev().find(".week-dropdown-menu li:last-child").hasClass("actived")){
					var year=parseInt($("#weekYearth").val());
					year++;
					$("#weekYearth").val(year);
				}
			}
		}
		$.ajax({
			url : "/weekWorkPlan/do_list",
			type : "POST",
			data : {
				'startTime' : weekTime,
				'userId' : $("#userId").val()
			},
			error : function(state) {
				new $.zui.Messager('获取上周数据的请求发送失败', {
					type : 'danger',
					time : 1500
				}).show();
			},
			success : function(data) {
				if (data.success) {
					loadData(data.data);
				} else {
					new $.zui.Messager('数据返回失败', {
						type : 'danger',
						time : 1500
					}).show();
				}
			}
		});
	})
	/* 年或周的下拉框点击事件 */
	$(".btn-group-weekcenter").delegate(".dropdown-menu li","click",function(){
		var year,time;
		if($(this).parent().hasClass("year-dropdown-menu")){//点击的年下拉框
			year=$(this).data("index");
			$("#weekYearth").val(year);
			var weekdetail=getWeekNumDetail(year);
			weekth=$(this).parent().parent().next().next().find(".week-dropdown-menu .actived").data("index");//获取到本来的周数
			for(var w=1;w<weekdetail.length;w++){//拿到新的年份所在周数的startDate
				if(weekdetail[w].week==weekth){
					time=weekdetail[w].startDate;
					break;
				}
			}
			if(!time){
				time=weekdetail[weekdetail.length-1].startDate
			}
		}else {//点击的周下拉框
			year=$(this).parent().parent().prev().prev().find(".year-dropdown-menu .actived").data("index");
			var slot=$(this).find(".dateSlot").text();
			time=slot.substring(1,6);
		}
		var weekTime=year+'-'+time;
		$.ajax({
			url : "/weekWorkPlan/do_list",
			type : "POST",
			data : {
				'startTime' : weekTime,
				'userId' : $("#userId").val()
			},
			error : function(state) {
				new $.zui.Messager('获取上周数据的请求发送失败', {
					type : 'danger',
					time : 1500
				}).show();
			},
			success : function(data) {
				if (data.success) {
					loadData(data.data);
				} else {
					new $.zui.Messager('数据返回失败', {
						type : 'danger',
						time : 1500
					}).show();
				}
			}
		});
	})
	//获取初始数据
	function init(plan, calendar) {
		var date = $('#thisWeekTime').val();
		var ajaxData = {
			'startTime' : $('#thisWeekTime').val()
		};
		if (calendar) {
			ajaxData.startTime = $("#workTime").val();
		}
		if (plan) {
			ajaxData.userId = $("#userId").val();
		}
		$.ajax({
			url : "/weekWorkPlan/do_list",
			cache : false,
			type : "POST",
			data : ajaxData,
			error : function(state) {
				new $.zui.Messager('请求发送失败', {
					type : 'danger',
					time : 1500
				}).show();
			},
			success : function(data) {
				if (data.success) {
					loadData(data.data);//填充当前周和下一周的工作任务
				}
			}
		});
	}
	if (GetRequest()) {
		if (GetRequest()['fromPlanView']) {
			init(true, false);
		}
		if (GetRequest()['fromCalendar']) {
			init(false, true);
		}
	} else {
		init(false, false);
	}
	//工作计划删除
	function weekWorkDelete(deleteid) {
		bootbox.confirm({
			title : "删除",
			message : '<div style="text-align:left;font-size:0.12rem">是否确认删除？</div>',
			size : 'small',
			buttons : {
				cancel : {
					label : '取消',
					className:'btn-white btn-info'
				},
				confirm : {
					label : '确定',
					className:'btn-white btn-info colorbtn'
				}
			},
			callback : function(result) {
				if (result) {
					$.ajax({
						url : "/weekWorkPlan/do_delete",
						type : "POST",
						data : {
							'id' : deleteid
						},
						error : function(state) {
							new $.zui.Messager(
									'删除成功',
									{
										type : 'danger',
										time : 1500
									}).show();
							$("#myModal-viewweekwork").modal('hide');
						},
						success : function(data) {
							if (data.success) {
								new $.zui.Messager(
										'删除成功',
										{
											type : 'success',
											time : 1500
										}).show();
								$("#myModal-viewweekwork").modal('hide');
								init();
							} else {
								new $.zui.Messager(
										data.msg,
										{
											type : 'warning',
											time : 1500
										}).show();
								$("#myModal-viewweekwork").modal('hide');
								init();
							}
						}
					});
				}
			}
		});
	}
	//工作计划修改点击事件
	function weekWorkModify(id) {
		$("#myModal-modifyweekwork").find('.notEmptyLabel').remove().end().find(".has-error").removeClass("has-error");
		$.ajax({
			url : "/weekWorkPlan/do_getWorkState",
			type : "get",
			async : false,
			data : {},
			error : function(state) {
				new $.zui.Messager('请求发送失败', {
					type : 'danger',
					time : 1500
				}).show();
			},
			success : function(data) {
				if (data.success) {
					var obj = data.data;
					var label_input = '';
					for (var i = 0; i < obj.length; i++) {
						if (obj[i].code != "workState_overdue") {
							label_input += '<label class="radio-inline"><input type="radio" name="workState.id" value="'+obj[i].id+'" class="'+obj[i].code+'"><span>'+ obj[i].name+ '</span></label>'
						}
					}
					$("#updateWorkForm .updateAllState").empty().append(label_input);
				} else {
					new $.zui.Messager('工作计划状态获取失败', {
						type : 'danger',
						time : 1500
					}).show();
				}
			}
		})
		$.ajax({
			url : "/weekWorkPlan/do_view",
			type : "get",
			async : false,
			data : {
				'id' : id
			},
			error : function(state) {
				new $.zui.Messager('请求发送失败', {
					type : 'danger',
					time : 1500
				}).show();
			},
			success : function(data) {
				if (data.success) {
					var obj = data.data;
					//状态渲染
					$("#myModal-modifyweekwork input[name='workState.id']").each(function() {
						if ($(this).attr("class") == obj.workState.code) {
							$(this).prop("checked",true);
						} else {
							$(this).prop("checked",false);
						}
					})
					//显示修改的按钮，要么是本周，要么是本周以后，不可能是本周之前的数据，所以只需要判断是否是本年（本年中本周后只显示进行中）或本年以后（只显示进行中）
					if( parseInt($("#presentYearth").val())==parseInt($("#weekYearth").val()) ){//此时显示的数据是本年的数据
						if (obj.weekth > parseInt($("#presentWeekth").val())) {//如果周数在本周之后，修改弹框内的状态一栏只有进行中
							$("#myModal-modifyweekwork .modifyplan-workingdoing").show();
							$("#myModal-modifyweekwork .modifyplan-allstate").hide();
						} else {
							$("#myModal-modifyweekwork .modifyplan-workingdoing").hide();
							$("#myModal-modifyweekwork .modifyplan-allstate").show();
						}
					}else if( parseInt($("#presentYearth").val())<parseInt($("#weekYearth").val()) ){//此时显示的数据是本年以后的数据
						$("#myModal-modifyweekwork .modifyplan-workingdoing").show();
						$("#myModal-modifyweekwork .modifyplan-allstate").hide();
					}
					$("#updateInputId").val(obj.id);
					$("#updateInputTitle").val(obj.title);
					if (obj.level == "紧急") {//0是普通 1是紧急
						$("#updateInputAddress option").eq(1).prop("selected",true)
						$("#updateInputAddress option").eq(0).prop("selected",false)
					} else {
						$("#updateInputAddress option").eq(0).prop("selected",true)
						$("#updateInputAddress option").eq(1).prop("selected",false)
					}
					$("#updateInputdateSelect").val(obj.workTime);
					$("#updateInputContent").text(obj.workContent);
					$("#myModal-modifyweekwork .leftDialog").next().hide();
					if (obj.workState.code == "workState_continue_next_week") {
						$("#myModal-modifyweekwork .leftDialog").removeClass("col-xs-12").addClass("col-xs-6");
						$("#myModal-modifyweekwork").find(".modal-dialog").css('width','12rem')
					} else {
						$("#myModal-modifyweekwork").find(".modal-dialog").css('width','7rem');
						$("#myModal-modifyweekwork .leftDialog").css({"borderRight" : "0px dashed #ccc"}).removeClass("col-xs-6").addClass("col-xs-12")
					}
					if (obj.workState.code == "workState_continue_next_week") {
						nextdateSelectInit(true,true,"#updateInputdateSelect");
						nextdateSelectInit(true,false,"#next_updateInputdateSelect");
						if (obj.nextWeekWorkPlan) {//下周继续的关联数据没有删除
							$("#next_updateInputId").val(obj.nextWeekWorkPlan.id);
							$("#next_updateInputTitle").val(obj.nextWeekWorkPlan.title);
							console.log(obj.nextWeekWorkPlan.level)
							if (obj.nextWeekWorkPlan.level == "urgent") {//0是普通 1是紧急
								$("#next_updateInputAddress option").eq(1).prop("selected",true)
							} else {
								$("#next_updateInputAddress option").eq(0).prop("selected",true)
							}
							$("#next_updateInputdateSelect").val(obj.nextWeekWorkPlan.workTime);
							
							$("#next_updateInputContent").val(obj.nextWeekWorkPlan.workContent);
						} else {//下周继续的关联数据被删除时，将左边的数据复制给右边
							$("#next_updateInputTitle").val(obj.title);
							if (obj.level == "urgent") {
								$("#next_updateInputAddress option").eq(1).prop("selected",true)
							} else {
								$("#next_updateInputAddress option").eq(0).prop("selected",true)
							}
							$("#next_updateInputdateSelect").val(getNextWeekFirstDay());
							$("#next_updateInputContent").val(obj.workContent);
						}
						$("#myModal-modifyweekwork .modal-dialog").css({"width" : "12rem"});
						$("#myModal-modifyweekwork .leftDialog").removeClass("col-xs-12").addClass("col-xs-6").css({"borderRight" : "1px dashed #54c3fe"}).next().data("flag", true).css({"display" : "block","marginLeft" : "0px"})
					}
					if(obj.workState.code == "workState_working"){//修改的弹框状态为进行中时
						var nextweekThisWeek=false;var workId=false;
						if(obj.lastWorkId){//下周继续的数据
							workId=true;
							var compare=compareDate(getNextWeekFirstDay(),obj.workTime);//判断下周继续的周数是下周还是本周（true:本周 false：下周）
							compare?nextweekThisWeek=true:nextweekThisWeek=false
							$("#updateInputdateSelect").data("weekth-data",nextweekThisWeek)
							$("#updateInputdateSelect").data("parent-data",obj.lastWorkId);
						}else {//正常新增的数据 可选日期为今天及其以后
							$("#updateInputdateSelect").data("parent-data",false);
						}
						nextdateSelectInit(workId,nextweekThisWeek,"#updateInputdateSelect");
					}
					$("#myModal-modifyweekwork").modal('show');
				}
			}
		});
	}
	function nextdateSelectInit(workid,nextweekThisWeek,obj){
		$(obj).datetimepicker('remove');
		var nextfirst,nextlast;
		if(workid){//下周继续
			if(nextweekThisWeek){//本周
				nextfirst=getFirstDay();
				nextlast=getLastDay();
			}else {//下周
				nextfirst=getNextWeekFirstDay();
				nextlast=getNextWeekLastDay();
			}
		}else {
			nextfirst=getFirstDay();
			nextlast="2116-12-31";
		}
		$(obj).datetimepicker('remove');
		$(obj).datetimepicker({//点击下周继续的日期选择开始日期及结束日期为下周周一到周日（如今天是周一5点之前，返回本周日期）
		    language:  "zh-CN",
		    weekStart: 1,
		    todayBtn:  0,
		    autoclose: 1,
		    todayHighlight: 1,
		    startView: 2,
		    minView: 2,
		    forceParse: 0,
		    format: "yyyy-mm-dd",
		    startDate:nextfirst,
		    endDate:nextlast
		});
	}
	
	//工作计划的整体查看
	function weekWorkView(viewId) {
		$.ajax({
			url : "/weekWorkPlan/do_view",
			type : "get",
			data : {
				'id' : viewId
			},
			error : function(state) {
				new $.zui.Messager('请求发送失败', {
					type : 'danger',
					time : 1500
				}).show();
			},
			success : function(data) {
				/* console.log(data); */
				var obj = data.data;
				if (data.success) {
					$("#myModal-viewweekwork .view-state").text(obj.workState.name);
					$("#myModal-viewweekwork .view-title").text(obj.title);
					$("#myModal-viewweekwork .view-urgent").text(obj.level);
					$("#myModal-viewweekwork .view-starttime").text(obj.workTime);
					$("#myModal-viewweekwork .view-content").text(obj.workContent);
					$("#myModal-viewweekwork .leftDialog").next().hide();
					if (obj.workState.code == "workState_continue_next_week") {
						$("#myModal-viewweekwork .leftDialog").removeClass("col-xs-12").addClass("col-xs-6");
						$("#myModal-viewweekwork").find(".modal-dialog").css('width','12rem')
					} else {
						$("#myModal-viewweekwork").find(".modal-dialog").css('width','7rem');
						$("#myModal-viewweekwork .leftDialog").css({"borderRight" : "0px dashed #ccc"}).removeClass("col-xs-6").addClass("col-xs-12")
					}

					if (obj.workState.code == "workState_continue_next_week") {
						if (obj.nextWeekWorkPlan) {
							$("#myModal-viewweekwork").find(".alreadyDelete").remove();
							$("#myModal-viewweekwork .view-nextstate").text(obj.nextWeekWorkPlan.workState.name);
							$("#myModal-viewweekwork .view-nexttitle").text(obj.nextWeekWorkPlan.title);
							var level;
							if (obj.nextWeekWorkPlan.level == "urgent") {
								level = "紧急"
							} else {
								level = "普通"
							}
							$("#myModal-viewweekwork .view-nexturgent").text(level);
							$("#myModal-viewweekwork .view-nextstarttime").text(obj.nextWeekWorkPlan.workTime);
							$("#myModal-viewweekwork .view-nextcontent").text(obj.nextWeekWorkPlan.workContent);
							$("#myModal-viewweekwork").find(".modal-dialog").css({"width" : "12rem"})
							$("#myModal-viewweekwork .leftDialog").removeClass("col-xs-12").addClass("col-xs-6").css({"borderRight" : "1px dashed #54c3fe"}).next().show()
						} else {
							$("#myModal-viewweekwork .leftDialog").removeClass("col-xs-12").addClass("col-xs-6").css({"borderRight" : "1px dashed #54c3fe"}).next().before('<div class="col-xs-6 alreadyDelete" style="text-align:center"><div class="plan-label">关联计划已被删除<div></div>');
						}
					}
					//显示弹框按钮，如果是本周之前，不可修改和删除
					if( parseInt($("#presentYearth").val())==parseInt($("#weekYearth").val()) ){//此时显示的数据是本年的数据
						if (obj.weekth < $("#presentWeekth").val()) {
							$(".modifyWeekWorkBtn").hide();
							$(".deleteWeekWorkBtn").hide();
						} else {
							$(".modifyWeekWorkBtn").show().data("id", obj.id);
							$(".deleteWeekWorkBtn").show().data("id", obj.id);
						}
					}else if( parseInt($("#presentYearth").val())>parseInt($("#weekYearth").val()) ){//此时显示的数据是本年以前的数据
						$(".modifyWeekWorkBtn").hide();
						$(".deleteWeekWorkBtn").hide();
					}
					$("#myModal-viewweekwork").modal('show');
				}
			}
		});
	}
	//修改工作计划按钮点击提交事件 
	$(".updateWeekWorkBtn").click(function() {
		var cla = $("#myModal-modifyweekwork .radio-inline").find("input:checked").attr("class");
		var postFormData;var judge;
		var flag = modifyweekWorkValidation(cla);
		if (flag) {
			if(cla != "workState_continue_next_week"){//非下周继续时检验标题
				judge=judgeIsIdentical($("#myModal-modifyweekwork #updateInputTitle"),$("#myModal-modifyweekwork .leftformdate"),$('#myModal-modifyweekwork #updateInputId'));
			}else {//下周继续时检验标题
				var judge1=judgeIsIdentical($("#myModal-modifyweekwork #updateInputTitle"),$("#myModal-modifyweekwork .leftformdate"),$('#myModal-modifyweekwork #updateInputId'));
				var judge2=judgeIsIdentical($("#myModal-modifyweekwork #next_updateInputTitle"),$("#myModal-modifyweekwork .rightformdate"),$('#myModal-modifyweekwork #next_updateInputId'));
				judge1&&judge2?judge=true:judge=false;
			}
			if(judge){
				if (cla != "workState_continue_next_week") {//没有选下周继续,去掉下周数据
					var weekPostData = $("#updateWorkForm").serialize().split('&');
					var weekNewData = [];
					for (var i = 0; i < weekPostData.length; i++) {
						if (!(weekPostData[i].split('=')[0] == "nextWeekWorkPlan.title"|| weekPostData[i].split('=')[0] == "nextWeekWorkPlan.level"|| weekPostData[i].split('=')[0] == "nextWeekWorkPlan.workTime" || weekPostData[i].split('=')[0] == "nextWeekWorkPlan.workContent")) {
							weekNewData.push(weekPostData[i])
						}
					}
					postFormData = weekNewData.join('&');
				} else {//选择了下周继续,传递全部
					postFormData = $("#updateWorkForm").serialize();
				}
				//验证以及新增时的字段恢复默认
				$.ajax({
					url : '/weekWorkPlan/do_update',
					data : postFormData,
					type : 'post',
					dataType : 'json',
					success : function(data) {
						/* console.log(data); */
						if (data.success) {
							new $.zui.Messager(
									'修改计划成功',
									{
										type : 'success',
										time : 1500
									}).show();
							$("#myModal-modifyweekwork").modal('hide');
							init();
						} else {
							new $.zui.Messager(
									'修改计划失败'
											+ data.msg,
									{
										type : 'error',
										time : 1500
									}).show();
							$("#myModal-modifyweekwork").modal('hide');
							init()
						}
						//表单恢复默认
						$("#updateWorkForm").resetForm();
						$("#updateWorkForm .row .leftDialog").next().data("flag",'');
					},
					error : function(status) {
						new $.zui.Messager(
							'提交修改计划的数据时发生错误',
							{
								type : 'error',
								time : 1500
							}).show();
					}
				})
			}else {
				$("#myModal-modifyweekwork").modal('show');
			}
		} else {
			$("#myModal-modifyweekwork").modal('show');
		}
	})
	//工作计划li点击查看
	$(".week-plan_taskul").delegate(".week_plan_taskli", "click",function() {
		weekWorkView($(this).attr("workid"));
	})
	//删除／查看／编辑事件
	$(".week-plan_taskul").delegate(".week-work-operation .icon","click", function(event) {
		if ($(this).hasClass("icon-trash")) {//删除事件
			var deleteid = $(this).data("trashid");
			weekWorkDelete(deleteid);
			event.stopPropagation();
		} else if ($(this).hasClass("icon-edit")) {//修改事件
			weekWorkModify($(this).data("editid"));
			event.stopPropagation();
		} else if ($(this).hasClass("icon-search")) {//查看事件
			var viewId = $(this).data("searchid");
			weekWorkView(viewId);
			event.stopPropagation();
		}
	})
	// 状态选择点击事件
	$(".work-plan-body").delegate(".dropdown-menu li","click",function() {
		var state = $(this).attr("class");
		$(this).parent().prev().html($(this).find("a").text()+ '<span class="caret" style="margin-left:0.05rem;border-width:0.05rem;"></span>');
		var $this = $(this);
		function hideshow(state) {
			$this.parent().parent().parent().find(".week-plan_taskul li").each(function() {
				if (!state) {
					$(this).show()
				} else {
					$(this).hasClass(state) ? $(this).show(): $(this).hide()
				}
			})
		}
		switch (state) {
		case "week_statusall":
			hideshow();
			break;
		case "week_statuspause":
			hideshow("workState_pause");
			break;
		case "week_statusfinish":
			hideshow("workState_finsh");
			break;
		case "week_statusstop":
			hideshow("workState_stop");
			break;
		case "week_statuscontinue":
			hideshow("workState_continue_next_week");
			break;
		case "week_statusdoing":
			hideshow("workState_working");
			break;
		case "week_statusoverdue":
			hideshow("workState_overdue");
			break;
		}
	})
	//划入
	$('.week_box .week-plan_taskul').on("mouseenter","li",function() {
		var str = $(this).attr("class");
		var pos = str.indexOf("workState_");
		if (!(str.indexOf("weekworkhover") + 1)) {
			var cla = "weekworkhover_"+ str.substring(pos);
			$(this).addClass(cla).find(".week-work-operation").css({"display" : "block"});
		}
	})
	//划出
	$('.week_box .week-plan_taskul').on("mouseleave","li",function() {
		var str = $(this).attr("class");
		var pos = str.indexOf("weekworkhover");
		var cla = str.substring(pos);
		$(this).removeClass(cla).find(".week-work-operation").css({"display" : "none"});
	})
	//新增工作计划---提交
	$("#myModal-addweekwork").delegate(".addWeekWorkBtn","click",function() {//新增工作计划按钮点击提交(表单不能为空——>同一时间标题不能相同)
		var cla = $("#myModal-addweekwork .radio-inline").find("input:checked").attr("class");
		var postFormData;var judge;
		var flag = addweekworkValidation(cla);
		if(flag){//表单验证
			if(cla != "workState_continue_next_week"){//非下周继续时检验标题
				judge=judgeIsIdentical($("#myModal-addweekwork .addLeftInputTitle"),$("#myModal-addweekwork .leftformdate"));
			}else {//下周继续时检验标题
				var judge1=judgeIsIdentical($("#myModal-addweekwork .addLeftInputTitle"),$("#myModal-addweekwork .leftformdate"));
				var judge2=judgeIsIdentical($("#myModal-addweekwork .addRightInputTitle"),$("#myModal-addweekwork .rightformdate"));
				judge1&&judge2?judge=true:judge=false;
			}
			if (judge) {//标题检验通过
				if (cla != "workState_continue_next_week") {//没有选下周继续,去掉下周数据
					var weekPostData = $("#addWorkForm")
							.serialize().split('&');
					var weekNewData = [];
					for (var i = 0; i < weekPostData.length; i++) {
						if (!(weekPostData[i].split('=')[0] == "nexttitle"|| weekPostData[i].split('=')[0] == "nextlevel"|| weekPostData[i].split('=')[0] == "nextworkTime" || weekPostData[i].split('=')[0] == "nextworkContent")) {
							weekNewData.push(weekPostData[i])
						}
					}
					postFormData = weekNewData.join('&');
				} else {//选择了下周继续,传递全部
					postFormData = $("#addWorkForm").serialize();
				}
				//验证以及新增时的字段恢复默认
				$.ajax({
					url : '/weekWorkPlan/do_add',
					data : postFormData,
					type : 'post',
					dataType : 'json',
					success : function(data) {
						if (data.success) {
							new $.zui.Messager(
									'新增计划成功',
									{
										type : 'success',
										time : 1500
									}).show();
							$("#myModal-addweekwork").modal('hide');
							init();
						} else {
							new $.zui.Messager(
									'新增计划失败'
											+ data.msg,
									{
										type : 'error',
										time : 1500
									}).show();
							$("#myModal-addweekwork").modal('hide');
							init()
						}
						//表单恢复默认
						$("#addWorkForm").resetForm()
					},
					error : function(status) {

					}
				})
			} else {//标题检验未通过
				$("#myModal-addweekwork").modal('show');
			}
		}else {//标题验证未通过
			$("#myModal-addweekwork").modal('show');
		}
	})
	$(".modifyWeekWorkBtn").click(function() {
		$("#myModal-viewweekwork").modal('hide');
		weekWorkModify($(this).data("id"));
	})
	$(".deleteWeekWorkBtn").click(function() {
		weekWorkDelete($(this).data("id"))
	})
	$(".week_box").delegate(".returnto-weekplanview","click",function() {
		var newlistpage = $("#mylistpage").val()
		$(".yk_rightcontent").load("/weekWorkPlan/weekPlanViewList",function(){
			mylistpage=newlistpage;
		});
	})
	//判断标题和时间是否符合要求
	function judgeIsIdentical(titleJQ,timeJQ,idJQ){
		var flag=false;
		var tdata = {
			title:titleJQ.val(),
			workTime:timeJQ.val()
		};
		if( idJQ!=undefined ){
			tdata.id = idJQ.val()
		};
		$.ajax({
			url: '/weekWorkPlan/do_validatorPlan',
			data : tdata,
			type : 'get',
			dataType : 'json',
			async:false,
			success : function(data) {
				if(data.success){
					if(data.data){
						flag=true;
						titleJQ.parent().find('.notEmptyLabel').remove();
					}else {
						var content = '<span class="notEmptyLabel error shows">该标题已存在</span>';
						if( titleJQ.parent().find('.notEmptyLabel').length<=0 ){
							titleJQ.parent().append(content);
						};
						titleJQ.parent().parent().addClass("has-error");
					}
				}else {
					new $.zui.Messager('判断标题时出错',{
						type : 'danger',
						time : 1500
					}).show();
				}
				
			},
			error:function(state){
				new $.zui.Messager('连接后台出错',{
					type : 'danger',
					time : 1500
				}).show();
			}
		})
		return flag;
	}
	function addweekworkValidation(cla) {
		var flag = true;
		if (!$("#inputtitle1").val()) {
			var content = '<span class="notEmptyLabel error shows">标题不能为空</span>';
			if( $("#inputtitle1").parent().find('.notEmptyLabel').length<=0 ){
				$("#inputtitle1").parent().append(content);
			};
			$("#inputtitle1").parent().parent().addClass("has-error");
			flag = false;
		}
		if (!$("#inputcontent1").val()) {
			var content = '<div class="notEmptyLabel error shows">工作内容不能为空</div>';
			if( $("#inputcontent1").parent().find('.notEmptyLabel').length<=0 ){
				$("#inputcontent1").parent().append(content);
			};
			$("#inputcontent1").parent().parent().addClass("has-error");
			flag = false;
		}
		if (cla == "workState_continue_next_week") {
			if (!$("#inputtitle2").val()) {
				var content = '<div class="notEmptyLabel error shows">标题不能为空</div>';
				if( $("#inputtitle2").parent().find('.notEmptyLabel').length<=0 ){
					$("#inputtitle2").parent().append(content);
				};
				$("#inputtitle2").parent().parent().addClass("has-error");
				flag = false;
			}
			if (!$("#inputcontent2").val()) {
				var content = '<div class="notEmptyLabel error shows">工作内容不能为空</div>';
				if( $("#inputcontent2").parent().find('.notEmptyLabel').length<=0 ){
					$("#inputcontent2").parent().append(content);
				};
				$("#inputcontent2").parent().parent().addClass("has-error");
				flag = false;
			}
		}
		return flag;
	}
	function modifyweekWorkValidation(cla) {
		var flag = true;
		if (!$("#updateInputTitle").val()) {
			var content = '<span class="notEmptyLabel error shows">标题不能为空</span>';
			if( $("#updateInputTitle").parent().find('.notEmptyLabel').length<=0 ){
				$("#updateInputTitle").parent().append(content);
			};
			$("#updateInputTitle").parent().parent().addClass("has-error");
			flag = false;
		}
		if (!$("#updateInputContent").val()) {
			var content = '<span class="notEmptyLabel error shows">工作内容不能为空</span>';
			if( $("#updateInputContent").parent().find('.notEmptyLabel').length<=0 ){
				$("#updateInputContent").parent().append(content);
			};	
			$("#updateInputContent").parent().parent().addClass("has-error");
			flag = false;
		}
		if (cla == "workState_continue_next_week") {
			if (!$("#next_updateInputTitle").val()) {
				var content = '<span class="notEmptyLabel error shows">标题不能为空</span>';
				if( $("#next_updateInputTitle").parent().find('.notEmptyLabel').length<=0 ){
					$("#next_updateInputTitle").parent().append(content);
				};
				$("#next_updateInputTitle").parent().parent().addClass("has-error");
				flag = false;
			}
			if (!$("#next_updateInputContent").val()) {
				var content = '<span class="notEmptyLabel error shows">工作内容不能为空</span>';
				if( $("#next_updateInputContent").parent().find('.notEmptyLabel').length<=0 ){
					$("#next_updateInputContent").parent().append(content);
				};
				$("#next_updateInputContent").parent().parent().addClass("has-error");
				flag = false;
			}
		}
		return flag;
	}
	
	
})