$.jgrid.defaults.responsive = true;
$.jgrid.defaults.styleUI = 'Bootstrap';
$(function () {
    /*判断浏览器是否是ie8  解决ie8弹出框居中问题*/
    var ua = navigator.userAgent.toLowerCase();
    if (window.ActiveXObject) {
        if (ua.match(/msie ([\d.]+)/)[1] == '8.0') {
            $(window).resize(function () {
                $.each($(".moveModel > .modal-dialog"), function () {
                    $(this).css("left", ($(window).width() - $(this).width()) / 2);
                    $(this).css("top", "40px");
                })
            })
        }
    }
    /*表单校验 end*/
    $(".hideButton").click(function () {
        $("#tableForm").find(".form-control").tooltip("destroy").removeAttr("aria-invalid").removeAttr("title").removeAttr("style");
        $('#tableForm')[0].reset();
        $(".Pop").hide();
        $("#valiteType").val("");
        $("#jtcyid").removeAttr("disabled");
    });
    //下拉框  含搜索的
    $('.chosen-select').chosen({allow_single_deselect: true, no_results_text: "无匹配数据", width: "100%"});
    //resize the chosen on window resize
    $(window).on('resize.chosen', function () {
        $.each($('.chosen-select'), function (index, obj) {
            $(obj).next().css("width", 0);
            var w = $(obj).parent().width();
            $(obj).next().css("width", w);
        });
        $.each($('.chosen-single-select'), function (index, obj) {
            $(obj).next().css("width", 0);
            var e = $(obj).parent().width();
            $(obj).next().css("width", e);
        })
    }).trigger('resize.chosen');

    //绑定回车键
    $(document).keydown(function(event){
        if(event.keyCode==13){
            $("#search").trigger("click");
        }
    });

    var valiteType=$("#valiteType").val();
    if(valiteType == "update"){
        $("#jtcyid").attr("disabled", "disabled");
    }
    $("#SaveBtn").click(function () {
        var msg = valiteData(".tableA");
        if (msg && msg != 'undefined')
            tipInfo(msg);
        else
            valiteValue();
    });

    //时间控件
    $(".date-picker").datepicker({
        autoclose: true,
        todayHighlight: true,
        language: 'zh-CN'
    }).next().on(ace.click_event, function () {
        $(this).prev().focus();
    });
    //生成表格
    BdcJtcyTableConfigGrid();
    fillTable();

    $("#addData").click(function () {
        var url = configUrl + "/bdcJtcy/addJtcy?type=add";
        window.parent.parent.showModel(url, "新增申请人");
    });
    //删除
    $("#delData").click(function () {
        var ids = $('#limit-table-grid-table').jqGrid('getGridParam', 'selarrrow');
        delRule(ids, configUrl + "/bdcJtcy/delBdcJtcy", "limit-table-grid-table");
    });
    //修改
    $("#updateData").click(function () {
        var ids = $('#limit-table-grid-table').jqGrid('getGridParam', 'selarrrow');
        if (ids.length == 0) {
            tipInfo("请选择一条数据!");
            return;
        }
        if (ids.length > 1) {
            tipInfo("只能同时修改一条数据!");
            return;
        }
        var ids = $('#limit-table-grid-table').jqGrid('getGridParam', 'selarrrow');
        var data = $('#limit-table-grid-table').getRowData(ids);
        var url = configUrl + "/bdcJtcy/addJtcy?type=update&jtcyid="+ encodeURI(data.JTCYID)
            + "&qlrid=" + encodeURI(data.QLRID) + "&jtcymc=" + encodeURI(data.JTCYMC)+ "&sfzjzl=" + encodeURI(data.SFZJZL)
            + "&zjh=" + encodeURI(data.ZJH) + "&txdz=" + encodeURI(data.TXDZ)+ "&xb=" + encodeURI(data.XB)
            + "&lxdh=" + encodeURI(data.LXDH)+ "&xh=" + encodeURI(data.XH)+ "&yhzgx=" + encodeURI(data.YHZGX)
            + "&gxsj=" + encodeURI(data.GXSJ)+ "&hkszd=" + encodeURI(data.HKSZD);
        window.parent.parent.showModel(url, "修改信息");
    });

    $("#search").click(function () {
        var mc = $("#mc").val();
        $("#limit-table-grid-table").jqGrid('setGridParam', {
            datatype: 'json',
            page: 1,
            url: configUrl + "/bdcJtcy/getBdcJtcyPagesJson?mc=" + encodeURI(mc)
        }).trigger("reloadGrid"); //重新载入
    });
    //resize to fit page size
    $(window).on('resize.jqGrid', function () {
        var contentWidth;
        if ($("#limitTableContent").width() > 0) {
            contentWidth = $("#limitTableContent").width();
        }
        $("#limit-table-grid-table").jqGrid('setGridWidth', contentWidth);
    });
});

//获取列表数据
function fillTable() {
    $("#limit-table-grid-table").jqGrid('setGridParam', {
        datatype: 'json',
        page: 1,
        url: configUrl + "/bdcJtcy/getBdcJtcyPagesJson",
        postData: {}
    }).trigger("reloadGrid"); //重新载入
}
//删除判断是否没有选择数据
function delRule(ids, url, gridId) {
    if (ids.length == 0) {
        tipInfo("请选择一条数据!");
        return;
    }
    showConfirmDialog("删除", "是否删除？", "del", "'" + ids + "','" + url + "','" + gridId + "'", "", "");
}

//打开table页面
function toLimitTable() {
    $("#myModal").show();
}

//提示
function tipInfo(msg) {
    bootbox.dialog({
        message: "<h3><b>" + msg + "</b></h3>",
        title: "",
        buttons: {
            main: {
                label: "关闭",
                className: "btn-primary"
            }
        }
    });
}

//auth表格初始化
function BdcJtcyTableConfigGrid() {
    debugger;
    var grid_selector = "#limit-table-grid-table";
    var pager_selector = "#limit-table-grid-pager";
    //resize on sidebar collapse/expand
    var parent_column = $(grid_selector).closest('[class*="col-"]');
    $(document).on('settings.ace.jqGrid', function (ev, event_name, collapsed) {
        if (event_name === 'sidebar_collapsed' || event_name === 'main_container_fixed') {
            $(grid_selector).jqGrid('setGridWidth', parent_column.width());
        }
    });
    jQuery(grid_selector).jqGrid({
        datatype: "local",
        height: 'auto',
        jsonReader: {id: 'JTCYID'},
        colNames: ['家庭成员ID','权利人ID','家庭成员名称','身份证件种类','证件号', '通讯地址','性别',
            '联系电话','序号','与户主关系','更新时间','户口所在地'],
        colModel: [
            {name: 'JTCYID', index: 'JTCYID', width: '0%', sortable: false,hidden: true},
            {name: 'QLRID', index: 'QLRID', width: '0%', sortable: false,hidden: true},
            {name: 'JTCYMC', index: 'JTCYMC', width: '10%', sortable: false},
            {name: 'SFZJZL', index: 'SFZJZL', width: '10%', sortable: false},
            {name: 'ZJH', index: 'ZJH', width: '10%', sortable: false},
            {name: 'TXDZ', index: 'TXDZ', width: '10%', sortable: false},
            {name: 'XB', index: 'XB', width: '10%', sortable: false},
            {name: 'LXDH', index: 'LXDH', width: '10%', sortable: false},
            {name: 'XH', index: 'XH', width: '10%', sortable: false,hidden: true},
            {name: 'YHZGX', index: 'YHZGX', width: '10%', sortable: false},
            {name: 'GXSJ', index: 'GXSJ', width: '10%', sortable: false},
            {name: 'HKSZD', index: 'HKSZD', width: '10%', sortable: false}

        ],
        viewrecords: true,
        rowNum: 5,
        rowList: [5, 10, 15],
        pagerpos: "left",
        pager: pager_selector,
        altRows: false,
        multiboxonly: true,
        multiselect: true,
        loadComplete: function () {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
                enableTooltips(table);
                $(grid_selector).jqGrid('setGridWidth', $("#limitTableContent").width());
            }, 0);
        },
        ondblClickRow: function (rowid) {
        },
        caption: "",
        autowidth: true
    });

}

//replace icons with FontAwesome icons like above
function updatePagerIcons(table) {
    var replacement =
        {
            'ui-icon-seek-first': 'ace-icon fa fa-angle-double-left bigger-140',
            'ui-icon-seek-prev': 'ace-icon fa fa-angle-left bigger-140',
            'ui-icon-seek-next': 'ace-icon fa fa-angle-right bigger-140',
            'ui-icon-seek-end': 'ace-icon fa fa-angle-double-right bigger-140'
        };
    $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function () {
        var icon = $(this);
        var $class = $.trim(icon.attr('class').replace('ui-icon', ''));

        if ($class in replacement) icon.attr('class', 'ui-icon ' + replacement[$class]);
    })
}
function enableTooltips(table) {
    $('.navtable .ui-pg-button').tooltip({container: 'body'});
    $(table).find('.ui-pg-div').tooltip({container: 'body'});
}

function valiteValue() {
    $.ajax({
        url: configUrl + '/bdcJtcy/valite?valiteType=' + valiteType,
        type: 'get',
        data: {
            jtcyid: $("#jtcyid").val()
        },
        success: function (data) {
            if (data && data != 'undefiend') {
                if (data && data == "1"){
                    alert("请输入家庭成员ID!");
                }else if (data && data=="3"){
                    alert("表中数据已存在!");
                }else {
                    saveorupdate();
                }
            }
        },
        error: function (data) {
        }
    });
}

function saveorupdate() {
    $.ajax({
        url: configUrl + '/bdcJtcy/saveBdcJtcy?jtcyid=' + encodeURI($("#jtcyid").val()) + "&qlrid=" + encodeURI($("#qlrid").val())
        + "&jtcymc=" + encodeURI($("#jtcymc").val())+ "&sfzjzl=" + encodeURI($("#sfzjzl").val())+ "&zjh=" + encodeURI($("#zjh").val())
        + "&txdz=" + encodeURI($("#txdz").val())+ "&xb=" + encodeURI($("#xb").val())+ "&lxdh=" + encodeURI($("#lxdh").val())
        + "&xh=" + encodeURI($("#xh").val())+ "&yhzgx=" + encodeURI($("#yhzgx").val())
        + "&gxsj=" + encodeURI($("#gxsj").val())+ "&hkszd=" + encodeURI($("#hkszd").val()),
        type: 'post',
        dataType: 'json',
        success: function (data) {
            if (data && data.result =="1"||data.result=="2") {
                alert("保存成功");
                window.parent.resourceRefresh();//刷新父页面jqGrid;
            }else{
                alert(data.result);
            }
        },
        error: function (data) {
            alert("保存失败");
            $('#tableForm')[0].reset();
        }
    });
}

function del(ids, url, gridId) {
    $.getJSON(url + "?ids=" + encodeURIComponent(ids), {}, function (jsonData) {
        setTimeout($.unblockUI, 10);
        if (jsonData.result == "0"){
            alert("删除成功");
        } else {
            alert ("删除失败");
        }
        $('#' + gridId).trigger("reloadGrid");
    })
}