$(function(){
});

// 获取表格数据
function getList(page){
    page = page || 1;
    var pageSize = 10, data = {
        "name" : $("#name").val().trim(),
        "type" : $("#type").val(),
        "typeName" : $("#typeName").val().trim(),
        "firstTheme" : $("#firstTheme").val(),
        "secondTheme" : $("#secondTheme").val(),
        "mediaRank" : $("#mediaRank").val(),
        "mediaName" : $("#mediaName").val(),
        "mediaNumMin" : $("#mediaNumMin").val(),
        "mediaNumMax" : $("#mediaNumMax").val(),
        "showDateStart" : $("#showDateStart").val(),
        "showDateEnd" : $("#showDateEnd").val(),
        "showTimeStart" : $("#showTimeStart").val(),
        "showTimeEnd" : $("#showTimeEnd").val(),
        "jinxianMin" : $("#jinxianMin").val(),
        "jinxianMax" : $("#jinxianMax").val(),
        "pageNo" : page,
        "pageSize" : pageSize
    }, html = "";

    $("#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.name == undefined || item.name == null ? '' : item.name)+'</td>'+
                    '<td>'+ (item.mediaName == undefined || item.mediaName == null ? '' : item.mediaName)+'</td>'+
                    '<td>'+ (item.mediaNum == undefined || item.mediaNum == null ? '' : item.mediaNum ) +'</td>'+
                    '<td>'+ (item.firstTheme == undefined || item.firstTheme == null ? '' : item.firstTheme ) +'</td>'+
                    '<td>'+ (item.secondTheme == undefined || item.secondTheme == null ? '' : item.secondTheme ) +'</td>'+
                    '<td>'+ (item.showDate == undefined || item.showDate == null ? '' : item.showDate ) +'</td>'+
                    '<td>'+ (item.showTime == undefined || item.showTime == null ? '' : item.showTime ) +'</td>'+
                    '<td>'+ (item.type == undefined || item.type == null ? '' : (item.type == 0 ? '产品' : '栏目' ) ) +'</td>'+
                    '<td>'+ (item.typeName == undefined || item.typeName == null ? '' : item.typeName ) +'</td>'+
                    '<td>'+ (item.duration == undefined || item.duration == null ? '' : item.duration ) +'</td>'+
                    '<td>'+ (item.jinxian == undefined || item.jinxian == null ? '' : item.jinxian ) +'</td>'+
                    '<td class="edit">'+
                    (data_query == 1 ? '<a href="'+ _PUBLIC_ +'ad-theatre-tv/detail.do?id='+item.id+'&edit=0" target="_blank">查看</a>&nbsp;&nbsp;'
                        : '<a href="javascript:alert(\'您暂无权限，请联系管理员。\');">查看</a>&nbsp;&nbsp;') +
                    (data_update == 1 ? '<a href="'+ _PUBLIC_ +'ad-theatre-tv/detail.do?id='+item.id+'&edit=1" target="_blank">编辑</a>'
                        : '<a href="javascript:alert(\'您暂无权限，请联系管理员。\');">编辑</a><br />' ) +
                    '</td>'+
                    '<td class="edit">'+
                    (update_flag == 1 ? '<a href="javascript:platformModfiy(\'edit\',\'剧场信息\','+item.id+');">编辑</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";
                });
            } 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";
                });
            } else {
                alert(res.msg);
            }
        });
    });
}

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

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

// 保存
function save(){
    // 得到数据
    var data = $('#dataForm').serializeJSON();
    data.id = $.getParam("id");
    data.firstTheme = $('#firstTheme').val();
    data.secondTheme = $('#secondTheme').val();
    // 数据是否完整
    if (data['name'].isEmpty()){
        top.alert("请填写剧名", 0, function(){
            $("input[name='name']").focus();
        });
        return false;
    }
    if (data['mediaNum'].isEmpty()){
        top.alert("请填写集数", 0, function(){
            $("input[name='mediaNum']").focus();
        });
        return false;
    }
    var intCheck = /(^[1-9]\d*$)/;
    if (!(intCheck.test(data['mediaNum']))){
        top.alert("集数请输入整数", 0, function(){
            $("input[name='mediaNum']").focus();
        });
        return false;
    }
    if (!data['jinxian'].isEmpty() && !(intCheck.test(data['jinxian']))){
        top.alert("进线预估请输入整数", 0, function(){
            $("input[name='jinxian']").focus();
        });
        return false;
    }
    if (data['mediaName'].isEmpty()){
        top.alert("请选择媒体");
        return false;
    }
    if (data['firstTheme'].isEmpty()){
        top.alert("请选择体裁");
        return false;
    }
    if (data['secondTheme'].isEmpty()){
        top.alert("请选择细分体裁");
        return false;
    }
    if (data['showDate'].isEmpty()){
        top.alert("请选择播出日期", 0, function(){
            $("input[name='showDate']").focus();
        });
        return false;
    }
    if (data['showTime'].isEmpty()){
        top.alert("请选择播出时间", 0, function(){
            $("input[name='showTime']").focus();
        });
        return false;
    }
    if (!data['duration'].isEmpty()){
	    var reg = /^(([1-9][0-9]*)+|0)(\.[0-9]{0,1})?$/;
        if (!reg.test(data['duration'])) {
            top.alert('请输入播出正确时长,最多1位小数');
            return false;
        }
        // 判断末尾是不是"."
        var indexNum = String(data['duration']).indexOf(".");
        var decimalLength = String(data['duration']).length;
        if ( (indexNum > -1 ? indexNum + 1 : -1)== decimalLength){
            top.alert("请输入播出正确时长", 0, function(){
                $("input[name='duration']").focus();
            });
            return false;
        }
        if (data['duration'] * 1 >= 100000){
            top.alert("时长最多五位数", 0, function(){
                $("input[name='duration']").focus();
            });
            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){
    title = title || "";
    id = id || "";
    $.openWindow(act.decode("add","新增","edit","修改","")+title, "detail.do?id="+id, 650, 500, true);
}

// 电视剧
var nameSelect = $('select[name="name"]').select2({
    placeholder: "请选择播出节目",
    allowClear: true,
    width:'166px',
    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
    }
});

// 媒体
var mediaNameSelect = $('select[name="mediaName"]').select2({
    placeholder: "请选择播出媒体",
    allowClear: true,
    width:'166px',
    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
    }
});

// 切换电视剧后，刷新体裁、细分体裁
$('select[name="name"]').live('change',function(){
    $('select[name="firstTheme"]').html('<option value=""></option>');
    $('select[name="secondTheme"]').html('<option value=""></option>');
    ajax({url: _PUBLIC_ + "ad-tv/detailByName.do",data:{"name":$('#name').val()},callBack:function(res){
        if (res.code == 1){
            $('select[name="firstTheme"]').html('<option value="' + res.data.firstTheme + '">' + res.data.firstTheme + '</option>');
            $('select[name="secondTheme"]').html('<option value="' + res.data.secondTheme + '">' + res.data.secondTheme + '</option>');
        }
    },load:false});
});

// 切换节目类型
function switchType(obj){
    // 类型：0产品 1栏目
    var type = $(obj).val();
    initSelectForTypeName(type);
}

/**
 * 初始化下拉框：产品/栏目
 * @param type 0-产品 1-栏目
 * @param typeName 名称
 */
function initSelectForTypeName(type, typeName) {
    var ajaxUrl = _PUBLIC_ + (type == 0 ? 'ad-product/select/list.do' : 'ad-platform/select/list.do');
    var content = (type == 0 ? '产品' : '栏目');
    // 修改下拉项
    $("#typeName").empty();
    // 获取产品列表
    ajax(ajaxUrl, {"pageNo" : 1, "pageSize" : 300}, function(res){
        if (isEmpty(typeName)){
            $("#typeName").append('<option value="">请选择' + content + '</option>');
        } else {
            $("#typeName").append('<option value="' + typeName + '">' + typeName + '</option>');
        }
        if (res.results.length > 0) {
            $.each(res.results, function (index, item) {
                if (item.text != typeName){
                    $("#typeName").append('<option value="' + item.text + '">' + item.text + '</option>');
                }
            });
        }
        $(".select").uiSelect();
    },false);
}

// 产品/栏目
var typeNameSelect = $('select[name="typeName"]').select2({
    placeholder: "请选择名称",
    allowClear: true,
    width:'166px'
});

// 体裁select控件初始化
var firstThemeSelect = $('select[name="firstTheme"]').select2({
    placeholder: "请选择体裁",
    allowClear: true,
    width:'166px',
    ajax:{
        url: _PUBLIC_ +'ad-select/top_category_by_type.do',
        dataType:'json',
        quietMillis:100,
        data:function(params){
            return {
                name : params.term,
                type : 1,
                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="firstTheme"]').live('change',function(){
    $('select[name="secondTheme"]').html('<option value=""></option>');
});

// 细分体裁select控件初始化
var secondThemeSelect = $('select[name="secondTheme"]').select2({
    placeholder: "请选择细分体裁",
    allowClear: true,
    width:'166px',
    ajax:{
        url: _PUBLIC_ +'ad-select/second_category_by_type.do',
        dataType:'json',
        quietMillis:100,
        data:function(params){
            return {
                name : params.term,
                type : 1,
                parentName : $('#firstTheme').val(),
                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
    }
});

