//查询
function getList(page){
	page = page || 1;	
	var pageSize = 10, data = $("#programForm").serializeJSON(), html = "";
	data['pageSize'] = pageSize;
	data['pageNo'] = page;
	data['firstType'] = $("#keywords1").val();
	data['secondType'] = $("#keywords2").val();

  $("#list").empty();
  $("#count").text(0);
  ajax("get_program_list.do",data,function(res){
		  if(res.code == 1 && res.data.length > 0){
			  $.each(res.data, function(index, item){
      			html += '<tr>'+
      		        '<td><input type="checkbox" class="checkbox {click:itemCheck}" name="item" value="'+ item.id + '" /><label></label></td>' +
      		        '<td>'+item.programName.toNull()+'</td>'+
                      '<td>'+item.type.toString().decode("1","综艺", "2","栏目", "3","电视剧","4", "电影","") +'</td>'+
                      '<td>'+item.firstType.toNull() +'</td>'+
                      '<td>'+item.secondType.toNull() +'</td>'+
                      '<td>'+ (item.type == 1 || item.type == 2 ? item.showCycle.toString().decode("1","周播", "2","季播","") : "")+'</td>'+
                      '<td>'+ (item.type == 1 || item.type == 2 ? item.showCycle.toString().decode("1",item.showYear != '' ? item.showYear + "年":item.showYear.toNull(),"2",item.showYear != '' ?"第" + item.showYear +"季" :item.showYear.toNull(),""):"") +'</td>'+
                      '<td>'+ item.type.toString().decode("1",item.showPhase!=''? "第" +item.showPhase +"期" : item.showPhase.toNull(),"2",item.showPhase != '' ? "第" + item.showPhase + "期" : item.showPhase.toNull(),"3",item.episode != '' ? "第" + item.episode + "集" : item.episode.toNull(),"") +'</td>'+ 
                      '<td>'+(item.showTime ? new Date(item.showTime.time).Format("yyyy-MM-dd"):"")+'</td>'+ 
                      '<td>'+(item.startTime ? new Date(item.startTime.time).Format("hh:mm"):"")+'</td>'+                     
                      '<td>'+(item.endTime ? new Date(item.endTime.time).Format("hh:mm"):"")+ '</td>'+        
                  	'<td class="edit">'+
                  	' <a href="'+item.type.toString().decode("1","program_data_vareity.do?id="+item.id + "&mode=1", "2","program_data_vareity.do?id="+ item.id + "&mode=1", "3","program_data_tv.do?id=" + item.id + "&mode=1","4", "program_data_movie.do?id=" + item.id + "&mode=1","") +'">查看</a>&nbsp;&nbsp;'+
                  	(data_update_flag == 1 ? ' <a href="'+item.type.toString().decode("1","program_data_vareity.do?id="+item.id + "&mode=2", "2","program_data_vareity.do?id="+ item.id + "&mode=2", "3","program_data_tv.do?id=" + item.id + "&mode=2","4", "program_data_movie.do?id=" + item.id + "&mode=2","") +'">编辑</a>' : '') +
                  	'</td>' +
                  	'<td class="edit"> '+
                  	(update_flag == 1 ? '<a href="javascript:programModfiy(\'edit\',\'节目\','+item.id+')">编辑</a>&nbsp;&nbsp;' : '')+
                  	(delete_flag == 1 ? '<a href="javascript:delProgram('+item.id+')">删除</a>' : '') +
                  	'</td>' +
      			'</tr>';
      		});
			$("#list").html(html);
			$("#count").text(res.total);
			var newpage = new createPage(res.total, page, pageSize, 3);
			$("#page").html(newpage.pageHtml);
			$(".table").hoverTable(true);
			$.checkbox();
		  }else{
			  $("#list").info("暂无信息。");
		  }
  });
}

pageGo = function(page){
	resetCheckAll();
	getList(page);
}

// 删除
function delProgram(id){
	id = id == undefined ? getChkId().join(",") : id;
	confirm("您确定需要删除该节目记录吗？",function(){
		top.ajax("del_program.do",{"id":id},function(res){
			if(res.code == 1){
				alert("节目记录删除成功。", 1, function(){
					getList(1);
				});
			}else{
				alert(res.msg);
			}
		});
	});
}


// 获取选中的id
function getChkId(){
	var ids = '';
	$("input[name='item']:checked").each(function(){
		 if(ids != ''){
			 ids = ids + ',' + $(this).val();
		 }else{
			 ids = $(this).val();
		 }
	});
	return ids;
}


// 批量删除
function delBatch(){
	var checkedId = getChkId();
	
	if (checkedId.isEmpty()){
		alert("请至少选择一条记录");
		return false;
	}
	
	confirm("确定删除这些记录吗？", function(){
        ajax("del_batch_program.do", {"checkedId":checkedId}, function(res){
            if (res.code == 1){
    			alert("删除成功。", 1, function(){
    				getList(1);
    			});
            } else {
            	alert(res.msg);
            }
        });
	});
}


// 新增或修改弹窗
function programModfiy(act, title, id){
	title = title || "";
	id = id || "";
	$.openWindow(act.decode("add","新增","edit","修改","")+title, "program_info.do?id="+id, 800, 400, true);
}

function changeToVariety(obj){
	var val = $(obj).val();
	switch(parseInt(val)){
		case 3:
			$(".variety,.cycle-year,.cycle-month").addClass("contentTxt");
			$("input[name='showCycle']:eq(0),input[name='showCycle']:eq(1)").prop("checked",false);
			$(".tv").removeClass("contentTxt");
		break;
		case 4:
			$(".variety,.cycle-year,.cycle-month,.tv,.variety-date").addClass("contentTxt");
			$("input[name='showCycle']:eq(0),input[name='showCycle']:eq(1)").prop("checked",false);
		break;
		default:
			$(".variety,.cycle-year,.variety-date").removeClass("contentTxt");
			$(".tv,.cycle-month").addClass("contentTxt");
			$(".cycle-year").find("input").attr("name","showYear");
			$(".cycle-month").find("input").removeAttr("name");
			$("input[name='showCycle']:eq(0)").prop("checked",true);
		break;
	}
	$(".text").input();
	getOneCategory($(obj).val());
	$.radio();
}

// 周播和季播切换
function changeTobo(obj){
	var val = $(obj).val();
	if(val == 1){
		$(".cycle-year").removeClass("contentTxt");
		$(".cycle-month").addClass("contentTxt");
		$(".cycle-year").find("input").attr("name","showYear");
		$(".cycle-month").find("input").removeAttr("name");
		$(".cycle-month").find("input").val("");
	}else{
		$(".cycle-month").removeClass("contentTxt");
		$(".cycle-year").addClass("contentTxt");
		$(".cycle-month").find("input").attr("name","showYear");
		$(".cycle-year").find("input").removeAttr("name");
		$(".cycle-year").find("input").val("");
	}
	$(".text").input();
}

//// 获取一级分类(类型为单选框)
//function getOneCategory(typeName){
//	var html = '<option value="">一级分类</option>';
//	ajax(_PUBLIC_+"/static/json/program.json",{},function(res){
//		getOneCategory.data = res;
//		$.each(getOneCategory.data,function(index, item){
//			if(typeName == item.name){
//				$.each(item.childs,function(i, it){
//					html +='<option value="'+it.name+'"'+(it.name == firstType ? " selected":"")+'>'+it.name+'</option>';
//				});
//			}
//		},false);
//		$("#firstType").html(html);
//		$(".select").uiSelect();
//		getTwoCategory();
//	});
//}
// 获取一级，二级分类(单选框)
function getOneCategory(typeName){
	$("#keywords1").inputTips("ajax_program_category_list.do?type=" + typeName + "&level=1",2,"#firstType",200,null,true);
	$("#keywords2").inputTips("ajax_program_category_list.do?type=" + typeName + "&level=2",2,"#secondType",200,null,true);
}
//// 获取一级分类(类型为下拉框)
//function getOneCategorySelect(){
//	var html = '<option value="">一级分类</option>';
//	var type = $(this).find("option:selected").text();
//	ajax(_PUBLIC_+"/static/json/program.json",{},function(res){
//		getOneCategory.data = res;
//		$.each(getOneCategory.data,function(index, item){
//			if(type == item.name){
//				$.each(item.childs,function(i, it){
//					html +='<option value="'+it.name+'"'+(it.name == firstType ? " selected":"")+'>'+it.name+'</option>';
//				});
//			}
//		},false);
//		$("#firstType").html(html);
//		$(".select").uiSelect();
//		getTwoCategory();
//	});
//}
//获取一级分类和二级分类(类型为下拉框)
function getOneCategorySelect(){
	$("#keywords1").val("");
	$("#keywords2").val("")
	var type = $(this).find("option:selected").val();
	$("#keywords1").inputTips("ajax_program_category_list.do?type=" + type + "&level=1",2,"#firstType",200,null,true);
	$("#keywords2").inputTips("ajax_program_category_list.do?type=" + type + "&level=2",2,"#secondType",200,null,true);
}

function getSubData(){
	var data = "";
	$.each(getOneCategory.data,function(index, item){
		$.each(item.childs,function(i, it){
			if($("#firstType>option:selected").val() === it.name){
				data.length <= 0 ? data = it.childs : "";
			}
		});
	});
	return data;
}

// 获取二级分类
function getTwoCategory(){
	var html = '<option value="">二级分类</option>';
	$.each(getSubData(),function(x, t){
		html +='<option value="'+t.name+'"'+(t.name == secondType ? " selected":"")+'>'+t.name+'</option>';
	});
	$("#secondType").html(html);
	$(".select").uiSelect();
}

// 保存节目
function programSave(){
	var data = $("#addProgramForm").serializeJSON();
	data['firstType'] = $("#keywords1").val();
	data['secondType'] = $("#keywords2").val();
	
	if(data.programName.isEmpty()){
		top.alert("请输入节目名称");
		$("input[name='programName']").focus();
		return false;
	}
	if(data.firstType.isEmpty()){
		top.alert("请选择一级分类");
		$("input[name='firstType']").focus();
		return false;
	}
	if(data.secondType.isEmpty()){
		top.alert("请选择二级分类");
		$("input[name='secondType']").focus();
		return false;
	}
	if(data.type == 1 || data.type == 2){
		if(data.showYear.isEmpty()){
			top.alert("请输入年份");
			$("input[name='showYear']").focus();
			return false;
		}
	}
	if(data.type == 1 || data.type == 2){
		if(data.showPhase.isEmpty()){
			top.alert("请输入第几期");
			$("input[name='showPhase']").focus();
			return false;
		}
	}	
	if(data.type == 3 && data.episode.isEmpty()){
		top.alert("请输入第几集");
		$("input[name='episode']").focus();
		return false;
	}	
	if(data.showTime.isEmpty()){
		top.alert("请输入首播日期");
		$("input[name='showTime']").focus();
		return false;
	}	
	if(data.startTime.isEmpty() && data.type != 4){
		top.alert("请输入开始时间");
		$("input[name='startTime']").focus();
		return false;
	}
	if(data.endTime.isEmpty() && data.type != 4){
		top.alert("请输入结束时间");
		$("input[name='endTime']").focus();
		return false;
	}
	if(data.type != 4 && compareTime(data.startTime,data.endTime) == 0){
		top.alert("结束时间不能小于等于开始时间！");
		$("input[name='endTime']").focus();
		return false;
	}

	top.ajax("./save_program.do",data,function(res){
		if(res.code == 1){
			top.alert("保存成功。", 1 , function(){
				top.getList(1);
				top.$.closeWindow();
			});
		}else{
			top.alert(res.msg);
		}
	});
}

// 时分比较
function compareTime(t1,t2){
	var a = t1.split(":");
	var b = t2.split(":");
	
	if(a[0] > b[0]){
		return 0;
	}else if(a[0] < b[0]){
		 return 1;
	}else{
		if(a[1] < b[1]){
			return 1;
		}else{
			return 0;
		}
	}
	
}

// 导入表格数据
function importExcel(obj){
	var url = "import_excel_for_program.do";
	$("#excelInfo").attr("action",url).submit();
// $("#programForm").attr({"action":"import_excel_for_program.do","method":"post","target":"hframe","enctype":"multipart/form-data"}).submit();
    $(obj).after($(obj).clone().val('')).remove();
}

// 导入结果
function excelCallback(code, msg) {
    if (code == 1) {
    	alert("导入成功。", 1, function(){
    		top.$.closeWindow();
    		getList(1);
		});    	
    } else {
    	alert(msg, 0, function(){
    		location.reload();
    	});	  	
    }
}

// 导出表格数据
function exportExcel(obj){
	var programName = $("#programName").val();
	var showPhase = $("#showPhase").val();
	var type = $("#type option:selected").val();
	var firstType = $("#keywords1").val();
	var secondType = $("#keywords2").val();
	var startDate = $("#start_time").val();
	var endDate = $("#end_time").val();
	
    $("#programForm").attr({"action":"export_excel_for_program.do?programName="+programName+"&showPhase="+showPhase +"&type="+type+"&firstType="+firstType+"&secondType="+secondType+"&startDate="+startDate+"&endDate="+endDate,"method":"get"}).submit();
    $(obj).after($(obj).clone().val('')).remove();
}

// 导入节目数据模板弹窗
function programDataTemplate(){
	$.openWindow("导入数据", "program_data_template.do", 450, 400, true);
}

// 选择模板导入节目数据
function importProgramData(o){
	$("input[type='radio']").prop("checked",false);
	$(o).prop("checked",true);
	$("#param").val($(o).val());
	$.radio();
	$("#programDataTemplate").click();
}
// 导入节目数据
function importExcelForProgramData(obj){
	if(!$("input[name='type']").is(':checked')){
		top.alert("请选择模板类型。");
		return false;
	}
	if($("#programDataTemplate").val().isEmpty()){
		top.alert("请选择上传的模板文件。");
		return false;
	}
	$("#excelInfo").attr("action","import_excel_for_program_data.do").submit();
}

//导入结果
function excelCallback2(code, msg) {
    if (code == 1) {
    	alert("导入成功。", 1, function(){
    		top.$.closeWindow();
    		getList(1);
		});    	
    } else {
    	top.$.closeWindow();
    	alert(msg, 0, function(){
    		location.reload();
    	});	  	
    }
}