$(function(){

    $('select[name="showEnv"]').select2({
        placeholder: "请选择播出环境",
        allowClear: true,
        width: '230px'
    });

});


function isEmpty(obj){
	if (obj != null && obj != '') {
	    return false;
	} else {
	    return true;
	}
}

// 播出媒体
var mediaNameSelect = $('select[name="mediaName"]').select2({
	placeholder: "请输入播出媒体",
	allowClear: true,
	width:'230px',
	ajax:{
		url: _PUBLIC_ +'ad-media/select/list.do',
		dataType:'json',
		quietMillis:100,
		data:function(params){
			return {
				name : params.term,
				pageNo : params.page || 1,
				pageSize : 20
			}
		},
		processResults: function (data, params) {
			params.page = params.page || 1;
			return {
		        results: data.results,
		        pagination: {
		          more: (params.page * 20) < data.total
		        }
		    };
		},
		cache: true
	}
});

// 产品/栏目
var productNameSelect = $('select[name="productName"]').select2({
	placeholder: "请输入名称",
	allowClear: true,
	width:'230px',
	ajax:{
		url: _PUBLIC_ + ($("#type").val() == 0 ? 'ad-product/select/list.do' : 'ad-platform/select/list.do'), 
		dataType:'json',
		quietMillis:100,
		data:function(params){
			return {
				productName : params.term,
				platformName : params.term,
				pageNo : params.page || 1,
				pageSize : 20
			}
		},
		processResults: function (data, params) {
			params.page = params.page || 1;
			return {
		        results: data.results,
		        pagination: {
		          more: (params.page * 20) < data.total
		        }
		    };
		},
		cache: true
	}
});


//解绑品牌/内容select控件初始化
$('select[name="productName"]').live('change',function(){
	$('select[name="brandName"]').html('<option value=""></option>');
});

// 品牌/内容select控件初始化	 
var secondIndSelect = $('select[name="brandName"]').select2({
	placeholder: "请选择",
	allowClear: true,
	width:'230px',
	ajax:{
		url: _PUBLIC_ + ($("#type").val() == 0 ? 'ad-product/brand_name_by_product_name.do' : 'ad-platform/brand_name_by_platform_name.do'), 
		dataType:'json',
		quietMillis:100,
		data:function(params){
			return {
				productName : $("#productName").val(),
				platformName : $("#productName").val(),
				brandName :params.term,
				pageNo : params.page || 1,
				pageSize : 20
			}
		},
		processResults: function (data, params) {
			params.page = params.page || 1;
			return {
		        results: data.results,
		        pagination: {
		          more: (params.page * 20) < data.total
		        }
		    };
		},
		cache: true
	}
});


// 电视剧
var productNameSelect = $('select[name="tvName"]').select2({
	placeholder: "请输入播出节目",
	allowClear: true,
	width:'230px',
	ajax:{
		url: _PUBLIC_ +'ad-tv/select/list.do',
		dataType:'json',
		quietMillis:100,
		data:function(params){
			return {
				name : params.term,
				pageNo : params.page || 1,
				pageSize : 20
			}
		},
		processResults: function (data, params) {
			params.page = params.page || 1;
			return {
		        results: data.results,
		        pagination: {
		          more: (params.page * 20) < data.total
		        }
		    };
		},
		cache: true
	}
});


// 获取表格数据
function getList(page){
	page = page || 1;
	var pageSize = 10, data = {
		"type" : $("#type").val(),
		"productName" : $("#productName").val(),
		"brandName" : $("#brandName").val(),
		"advMaster" : $("#advMaster").val(),
		"brandName" : $("#brandName").val(),
		"mediaName" : $("#mediaName").val(),
		"showEnv" : $("#showEnv").val(),
		"tvName" : $("#tvName").val(),
		"showTimeStart" : $("#showTimeStart").val(),
		"showTimeEnd" : $("#showTimeEnd").val(),
		"showDateStart" : $("#showDateStart").val(),
		"showDateEnd" : $("#showDateEnd").val(),
		"showDurationMin" : $("#showDurationMin").val(),
		"showDurationMax" : $("#showDurationMax").val(),
		"priceMin" : $("#priceMin").val(),
		"priceMax" : $("#priceMax").val(),
		"phone" : $("#phone").val(),
		"pageNo" : page,
	    "pageSize" : pageSize
	}, html = "";
		
    var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
    if(!isEmpty(data.showDurationMin)){
        if (!reg.test(data.showDurationMin)) {
            top.alert('请输入正确的播出最小时长');
            return false;
        }
    }
    if(!isEmpty(data.showDurationMax)){
        if (!reg.test(data.showDurationMax)) {
            top.alert('请输入正确的播出最大时长');
            return false;
        }
    }
    if(!isEmpty(data.priceMin)){
        if (!reg.test(data.priceMin)) {
            top.alert('请输入正确的刊例最小价格');
            return false;
        }
    }
    if(!isEmpty(data.priceMax)){
        if (!reg.test(data.priceMax) ) {
            top.alert('请输入正确的刊例最大价格');
            return false;
        }
    }
			
	$("#page, #list").empty();
	ajax("ajax_list.do", data, function(res){
		if (res.code == 1 && res.list.records.length > 0){
			$.each(res.list.records, function(index, item){
				html += '<tr>'+
					'<td><input type="checkbox" class="checkbox {click:itemCheck}" name="chk" value="'+item.id+'" /><label></label></td>'+
					'<td>'+ (item.productName == undefined || item.productName == null ? '' : item.productName ) +'</td>'+
					'<td>'+ (item.brandName == undefined || item.brandName == null ? '' : item.brandName ) +'</td>'+
					'<td>'+ (item.advMaster == undefined || item.advMaster == null ? '' : item.advMaster ) +'</td>'+
					'<td>'+ (item.mediaName == undefined || item.mediaName == null ? '' : item.mediaName) +'</td>'+
					'<td>'+ (item.showDate == undefined || item.showDate == null ? '' : item.showDate) +'</td>'+
					'<td>'+ (item.showTime == undefined || item.showTime == null ? '' : item.showTime) +'</td>'+
					'<td>'+ (item.showEnv == undefined || item.showEnv == null ? '' : item.showEnv) +'</td>'+
					'<td>'+ (item.tvName == undefined || item.tvName == null ? '' : item.tvName) +'</td>'+
					'<td>'+ (item.phone == undefined || item.phone == null ? '' : item.phone) +'</td>'+
					'<td>'+ (item.showDuration == undefined || item.showDuration == null ? '' : item.showDuration) +'</td>'+
					'<td>'+ (item.price == undefined || item.price == null ? '' : item.price) +'</td>'+
					'<td class="edit">'+
    					(update_flag == 1 && item.type == 0 ? '<a href="javascript:platformModfiy(\'edit\',\'专题广告信息\','+item.id+','+item.type+');">编辑</a>&nbsp;&nbsp;' : '') +
    					(update_flag == 1 && item.type == 1 ? '<a href="javascript:platformModfiy(\'edit\',\'专题栏目信息\','+item.id+','+item.type+');">编辑</a>&nbsp;&nbsp;' : '') +
	                    (delete_flag == 1 ? '<a href="javascript:delRecord('+item.id+');">删除</a>' : '' ) +
					'</td>'+
				'</tr>';
			});
			$("#list").html(html);
			$.checkbox();
			$("#count").text(res.list.total);
			var newpage = new createPage(res.list.total, page, pageSize, 3);
			$("#page").html(newpage.pageHtml);
		} else {
			$("#list").info("暂无数据。");
			$("#count").text(0);
		}
	});
}
pageGo = function(page){
	resetCheckAll();
	getList(page);
}

// 删除单个
function delRecord(id){
	confirm("确定删除该条记录吗？", function(){
        ajax("del.do", {"id" : id}, function(res){
            if (res.code == 1){
    			alert("删除成功。", 1, function(){
    				window.location.href = "index.do?type="+$("#type").val();
    			});
            } else {
            	alert(res.msg);
            }
        });
	});
}

// 删除多个
function delRecordBatch(){
	var arr = document.getElementsByName("chk");
	var ids = "";
	for (i=0; i<arr.length; i++){
		if (arr[i].checked){
			ids += ("," + arr[i].value);
		}
	}
	if (ids.isEmpty()){
		alert("请至少选择一条记录");
		return false;
	}
	confirm("确定删除这些记录吗？", function(){
        ajax("batch_del.do", {"ids" : ids.substring(1,ids.length)}, function(res){
            if (res.code == 1){
    			alert("删除成功。", 1, function(){
    				window.location.href = "index.do?type="+$("#type").val();
    			});
            } else {
            	alert(res.msg);
            }
        });
	});
}

// 导入表格数据
function importExcel(obj){
    $("#fileForm").submit();
}

// 导入结果
function excelCallback(code, msg) {
    if (code == 1) {
        // 导入成功
    	alert("导入成功。", 1, function(){
	        window.location.href = "index.do?type="+$("#type").val();
		});
    } else {
    	// 导入失败
    	alert(msg, 0, function(){
        	location.reload();
		});
    }
}

// 保存品牌型号信息
function save(){
	// 得到数据
    var data = $('#dataForm').serializeJSON(),type =$("#type").val();
    data.id = $.getParam("id");
    data.brandName = $("#brandName").val(); 
    console.log(data);
    // 数据是否完整
    if (data['productName'].isEmpty()){
    	top.alert(type == 0 ? "请选择产品名称" : "请选择栏目名称" , 0, function(){
            $("input[name='productName']").focus();
        });
        return false;
    }
    if (data['mediaName'].isEmpty()){
    	top.alert("请填写媒体名称");
        return false;
    }
    if (data['showEnv'].isEmpty()){
    	top.alert("请选择播出环境");
        return false;
    }else{
	    if(data['showEnv'] != 1){
		   data['tvName'] = data['tvNameInput']
	    }
    }
    if (data['tvName'].isEmpty()){
    	top.alert("请选择播出节目");
        return false;
    }
    if (data['showDate'].isEmpty()){
    	top.alert("请选择播出日期");
        return false;
    }
    if (data['showTime'].isEmpty()){
    	top.alert("请选择播出时间");
        return false;
    }
    if (data['showDuration'].isEmpty()){
    	top.alert("请输入播出时长");
        return false;
    }
    if (!data['showDuration'].isEmpty()){
	    var reg = /^(([1-9][0-9]*)+|0)(\.[0-9]{0,1})?$/;
        if (!reg.test(data['showDuration'])) {
            top.alert('请输入播出正确时长,最多1位小数');
            return false;
        }
        // 判断末尾是不是"."
        var indexNum = String(data['showDuration']).indexOf(".");
        var decimalLength = String(data['showDuration']).length;
        if ( (indexNum > -1 ? indexNum + 1 : -1)== decimalLength){
            top.alert("请输入播出正确时长", 0, function(){
                $("input[name='showDuration']").focus();
            });
            return false;
        }
        if (data['showDuration'] * 1 >= 100000){
            top.alert("时长最多五位数", 0, function(){
                $("input[name='showDuration']").focus();
            });
            return false;
        }
    }
    if(!data['price'].isEmpty()){
        var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
        if (!reg.test(data['price'])) {
            top.alert('请输入正确刊例价格');
            return false;
        }
    }
    // 提交数据
    top.ajax("save.do", data, function(res){
        if (res.code == 1){
            top.alert("保存成功。", 1, function(){
            	top.getList(1);
            	top.$.closeWindow();
            });
        } else {
            top.alert(res.msg);
        }
    });
}

// 弹窗
function platformModfiy(act, title, id , type){
	if(type == undefined || type == null){
		top.alert("参数为空！");
        return false;
	}
	title = title || "";
	id = id || "";
	$.openWindow(act.decode("add","新增","edit","修改","")+title, "detail.do?id="+id+"&type="+type, 800, 400, true);
}


// 播出环境变化切换播出节目
$('select[name="showEnv"]').live('change',function(){
	var tvName = $("#tvName").val()
	if($("#showEnv").val() == 1){
	    $(".tvNameSelect").css("display","");
        $(".tvNameInput").css("display","none");
	}else{
	    $(".tvNameSelect").css("display","none");
        $(".tvNameInput").css("display","");
	} 
});
