/**
 * 培训补贴管理初始化
 */
var TrainingSubsidy = {
    id: "TrainingSubsidyTable",	//表格id
    seItem: null,		//选中的条目
    table: null,
    layerIndex: -1
};

/**
 * 初始化表格的列
 */
TrainingSubsidy.initColumn = function () {
    return [
        {field: 'selectItem', radio: true},
        {title: '申报年度', field: 'year', visible: true, align: 'center', valign: 'middle',width:"80px",'class': 'uitd_showTip'},
        {title: '企业名称', field: 'enterpriseName', visible: true, align: 'center', valign: 'middle',width:"120px",'class': 'uitd_showTip'},
        {title: '姓名', field: 'name', visible: true, align: 'center', valign: 'middle',width: "80px",'class': 'uitd_showTip'},
        {title: '性别', field: 'sex', visible: true, align: 'center', valign: 'middle',width:"60px",'class': 'uitd_showTip',
            formatter : function (value,row,index){
                if(value==1){
                    return '男';
                }if(value==2){
                    return '女';
                }
            }
        },
        {title: '证件类型', field: 'cardTypeName', visible: true, align: 'center', valign: 'middle',width:"80px",'class': 'uitd_showTip'},
        {title: '证件号码', field: 'idCard', visible: true, align: 'center', valign: 'middle',width:"150px",'class': 'uitd_showTip'},
        {title: '国籍', field: 'nationalityName', visible: true, align: 'center', valign: 'middle',width:"80px",'class': 'uitd_showTip'},
        {title: '入职时间', field: 'entryTime', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '合同开始时间', field: 'startTime', visible: true, align: 'center', valign: 'middle',width:"110px",'class': 'uitd_showTip'},
        {title: '合同结束时间', field: 'endTime', visible: true, align: 'center', valign: 'middle',width:"110px",'class': 'uitd_showTip'},
        {title: '上一年度年薪', field: 'yearSalary', visible: true, align: 'center', valign: 'middle',width:"120px",'class': 'uitd_showTip'},
        {title: '上一年度缴纳个税总额', field: 'yearTax', visible: true, align: 'center', valign: 'middle',width:"150px",'class': 'uitd_showTip'},
        {title: '开户银行', field: 'bankName', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '开户银行网点', field: 'bankAddress', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '银行账号', field: 'bankNumber', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '联系电话', field: 'phone', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '联系地址', field: 'address', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '享受第几年度', field: 'enjoyYear', visible: true, align: 'center', valign: 'middle',width:"120px",'class': 'uitd_showTip'},
        {title: '兑现金额', field: 'enjoyMoney', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip',
            formatter : function (value,row,index){
                if(row.checkState == 5){
                    return value;
                }
                return "未知";
            }
        },
        {title: '审核状态', field: 'checkStateName', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip'},
        {title: '公示状态', field: 'publicState', visible: true, align: 'center', valign: 'middle',width:"100px",'class': 'uitd_showTip',
            formatter : function (value,row,index){
                if(value==1)return "<span class='label label-warning'>待公示</span>";
                if(value==2)return "<span class='label label-success'>公示中</span>";
                if(value==3)return "<span class='label label-info'>待兑现</span>";
                if(value==4)return "<span class='label label-primary'>已兑现</span>";
            }
        },
        {title: '操作', field: 'id', visible: true, align: 'center', valign: 'middle',width:"80px",
            formatter : function (value,row,index){
                return "<span class='label label-success' onclick=\"TrainingSubsidy.showLog('"+value+"')\" >" +
                    "<i class=\"fa fa-book\"></i>日志" +
                    "</span>";
            }
        }
    ];
};

/**
 * 检查是否选中
 */
TrainingSubsidy.check = function () {
    var selected = $('#' + this.id).bootstrapTable('getSelections');
    if(selected.length == 0){
        Feng.info("请先选中表格中的某一记录！");
        return false;
    }else{
        TrainingSubsidy.seItem = selected[0];
        return true;
    }
};

/**
 * 点击审核培训补贴
 */
TrainingSubsidy.openCheckTrainingSubsidy = function (type) {
    if (this.check()) {
        var index = layer.open({
            type: 2,
            title: '审核培训补贴',
            area: ['800px', '420px'], //宽高
            fix: false, //不固定
            maxmin: true,
            content: Feng.ctxPath + '/trainingSubsidy/trainingSubsidy_check/' + TrainingSubsidy.seItem.id,
            btn: ['<i class="fa fa-eye"></i>&nbsp;&nbsp;保存未提交', '<i class="fa fa-check layui-bg-green"></i>&nbsp;&nbsp;提交审核', '<i class="fa fa-eraser"></i>&nbsp;&nbsp;取消'],
            btnAlign: 'c',
            btn1: function (index, layero) {
                var obj = layero.find("iframe")[0].contentWindow;
                obj.TrainingSubsidyInfoDlg.showCheckModal(type);
            }, btn2: function (index, layero) {
                var obj = layero.find("iframe")[0].contentWindow;
                obj.TrainingSubsidyInfoDlg.submitToCheck(type);
                return false;
            },
            success: function (layero, index) {
                layer.tips('审核完成并确认无误后点击', '.layui-layer-btn1', {tips: [1, "#78BA32"], time: 0, closeBtn: 2});
            },
            end: function () {
                layer.closeAll('tips');
            }
        });
        TrainingSubsidy.layerIndex = index;
        layer.full(index);
    }
};

TrainingSubsidy.cancle = function (){
    if (this.check()) {
        var index = layer.open({
            type: 1,
            title: '撤回审核',
            area: ['800px', '420px'],
            fix: false,
            maxmin: true,
            content: '<form >\n' +
                '                    <div class="form-group" style="margin: 10px;">\n' +
                '                        <label for="checkMsg" class="control-label">撤销原因</label>\n' +
                '                        <textarea class="form-control" id="cancleMsg" rows="6" placeholder="只能撤销审核通过且未公示的数据"></textarea>\n' +
                '                    </div>\n' +
                '                </form>',
            btn: ['<i class="fa fa-save layui-bg-green"></i>&nbsp;&nbsp;提交', '<i class="fa fa-eraser"></i>&nbsp;&nbsp;关闭'],
            yes: function (index, layero) {
                var cancleMsg = $("#cancleMsg").val();
                if (Feng.isEmptyStr(cancleMsg)) {
                    Feng.error("撤销原因不能为空");
                    return;
                }
                var operation = function () {
                    var ajax = new $ax(Feng.ctxPath + "/trainingSubsidy/cancle", function (data) {
                        if (data.code == 200) {
                            Feng.success(data.msg);
                            TrainingSubsidy.table.refresh();
                            layer.close(index);
                        } else {
                            Feng.error(data.msg);
                        }
                    }, function (data) {
                        Feng.error("撤销复核失败!" + data.responseJSON.message + "!");
                    });
                    ajax.setData({"id": TrainingSubsidy.seItem.id, "checkMsg": cancleMsg})
                    ajax.start();
                };
                Feng.confirm("一旦提交无法修改，确定要撤回吗?", operation);
            }
        });
    }
}


/**
 * 收集数据
 */
TrainingSubsidy.formParams = function(){
    var queryData = {};
    queryData['year'] = $("#year").val();
    queryData['enterpriseName'] = $("#enterpriseName").val();
    queryData['name'] = $("#name").val();
    queryData['sex'] = $("#sex").val();
    queryData['cardType'] = $("#cardType").val();
    queryData['idCard'] = $("#idCard").val();
    queryData['nationality'] = $("#nationality").val();
    queryData['phone'] = $("#idCard").val();
    queryData['checkState'] = $("#checkState").val();
    queryData['publicState'] = $("#publicState").val();
    queryData['enjoyYear'] = $("#enjoyYear").val();
    return queryData;
}

/**
 * 重置数据
 */
TrainingSubsidy.reset = function(){
    $("#year").val("");
    $("#enterpriseName").val("");
    $("#name").val("");
    $("#sex").val("");
    $("#cardType").val("");
    $("#idCard").val("");
    $("#nationality").val("");
    $("#phone").val("");
    $("#checkState").val("");
    $("#publicState").val("");
}

/**
 * 查询培训补贴列表
 */
TrainingSubsidy.search = function () {
    TrainingSubsidy.table.refresh({query: TrainingSubsidy.formParams()});
};

/**
 * 显示审核日志
 */
TrainingSubsidy.showLog = function (id){
    layer.open({
        type: 1,
        title:"日志",
        fixed:false,
        content: '<table id="'+id+'"></table>',
        area: ['80%', '80%'],
        maxmin: true,
        success :function (layero, index) {
            Feng.getCheckLog(id,{"type":CONFIG.project_training,"mainId":id,"typeFileId":"","active":1})
        }
    });
}

/**
 * 获取需要处理的数据
 */
TrainingSubsidy.showData = function(type){
    $("#searchForm")[0].reset();
    $("#hczxForm")[0].reset();
    switch (type) {
        case 1:                 //公示
            $("#button").attr("onclick","TrainingSubsidy.public()").text("公示");
            $("#exportCommonModalLabel").text("待公示名单");
            $("#hczxForm").css("display","block");
            $(".time").each(function(){
                laydate.render({
                    elem: "#"+$(this).attr("id")
                    ,type: 'date'
                    ,format:'yyyy年MM月dd日'
                });
            });
            break;
        case 2:                 //公示通过
            $("#button").attr("onclick","TrainingSubsidy.publicPass()").text("提交");
            $("#exportCommonModalLabel").text("待公示通过名单");
            $("#hczxForm").css("display","none");
            break;
        case 3:                 //兑现
            $("#button").attr("onclick","TrainingSubsidy.cash()").text("提交");
            $("#exportCommonModalLabel").text("待兑现名单");
            $("#hczxForm").css("display","none");
            break;
    }
    $('#dataTable').bootstrapTable('destroy');
    $('#dataTable').bootstrapTable({
        url: Feng.ctxPath + "/trainingSubsidy/selectNeedCheckData?type="+type,
        method: 'POST',
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        search: false,					// 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
        showRefresh: false,				// 是否显示刷新按钮
        clickToSelect: true,			// 是否启用点击选中行
        singleSelect: false,				// 设置True 将禁止多选
        striped: true,  				// 是否显示行间隔色
        pagination: true,   			// 设置为 true 会在表格底部显示分页条
        paginationHAlign: "left",
        paginationDetailHAlign: "right",
        sidePagination: "client",   	// 设置在哪里进行分页，可选值为 'client' 或者 'server'
        pageNumber:1,                       //初始化加载第一页，默认第一页
        pageSize: 10,                       //每页的记录行数（*）
        pageList: [10, 25, 50, 100,500,1000,1500],        //可供选择的每页的行数（*）
        maintainSelected:true,              //全表全选需要开启
        showColumns: false,
        responseHandler : function(res){
            $("#exportCommonModal").modal("show");
            return res.obj.rows;
        },
        columns:
            [
                {field:"selectItem",checkbox:true},
                {title: '姓名', field: 'name', visible: true, align: 'center', valign: 'middle',width:"20%"},
                {title: '证件号码', field: 'idCard', visible: true, align: 'center', valign: 'middle',width:"30%"},
                {title: '企业名称', field: 'enterpriseName', visible: true, align: 'center', valign: 'middle',width:"50%"},
            ]

    });

}

/**
 * 公示
 */
TrainingSubsidy.public = function(){
    var selected = $('#dataTable').bootstrapTable('getSelections');
    if(!selected || selected.length<1){
        Feng.info("请至少选择一行数据!");
        return;
    }
    var ids = "";
    for(var i=0; i<selected.length; i++){
        ids = ids + selected[i].id + ",";
    }
    var isMessage = $("input[name='isSend']:checked").val();
    var typeName = $("#typeName").val();
    var address = $("#web").val();
    var publicStartTime = $("#publicStartTime").val();
    var publicEndTime = $("#publicEndTime").val();
    var dep = $("#dep").val();
    var phone = $("#fyphone").val();
    var email = $("#fyemail").val();
    if(isMessage == 1){
        if(typeName == null || typeName == ''){
            Feng.info("请填写公示类型");return ;
        }if(address == null || address == ''){
            Feng.info("请填写公示平台");return ;
        }if(publicStartTime == null || publicStartTime == ''){
            Feng.info("请填写公示开始时间");return ;
        }if(publicEndTime == null || publicEndTime == ''){
            Feng.info("请填写公示截止时间");return ;
        }if(dep == null || dep == ''){
            Feng.info("请填写反映单位");return ;
        }if(phone == null || phone == ''){
            Feng.info("请填写联系电话");return ;
        }if(email == null || email == ''){
            Feng.info("请填写联系邮箱");return ;
        }
    }
    var operation = function(){
        $("#exportCommonModal").modal("hide");
        window.location.href = encodeURI(encodeURI(Feng.ctxPath + "/trainingSubsidyExport/exportPublic?ids="+ids + "&typeName="+typeName+"&address="+address+
            "&publicStartTime="+publicStartTime+"&publicEndTime="+publicEndTime+"&dep="+dep+"&phone="+phone+"&email="+email+"&isMessage="+isMessage));
    }
    Feng.confirm("确定要公示吗?", operation);
}

/**
 * 公示通过
 */
TrainingSubsidy.publicPass = function(){
    var selected = $('#dataTable').bootstrapTable('getSelections');
    if(!selected || selected.length<1){
        Feng.info("请至少选择一行数据!");
        return;
    }
    var ids = "";
    for(var i=0; i<selected.length; i++){
        ids = ids + selected[i].id + ",";
    }
    var operation = function(){
        var ajax = new $ax(Feng.ctxPath + "/trainingSubsidy/publicPass", function (data) {
            if(data.code==200){
                Feng.success(data.msg);
                TrainingSubsidy.table.refresh();
                $("#exportCommonModal").modal("hide");
            }else{
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("公示通过失败!" + data.responseJSON.message + "!");
        });
        ajax.set("ids",ids);
        ajax.start();
    }
    Feng.confirm("一旦提交无法修改，确定公示通过吗?", operation);
}

/**
 * 兑现
 */
TrainingSubsidy.cash = function(){
    var selected = $('#dataTable').bootstrapTable('getSelections');
    if(!selected || selected.length<1){
        Feng.info("请至少选择一行数据!");
        return;
    }
    var ids = "";
    for(var i=0; i<selected.length; i++){
        ids = ids + selected[i].id + ",";
    }
    var operation = function(){
        var ajax = new $ax(Feng.ctxPath + "/trainingSubsidy/cash", function (data) {
            if(data.code==200){
                Feng.success(data.msg);
                TrainingSubsidy.table.refresh();
                $("#exportCommonModal").modal("hide");
            }else{
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("兑现失败!" + data.responseJSON.message + "!");
        });
        ajax.set("ids",ids);
        ajax.start();
    }
    Feng.confirm("一旦提交无法修改，确定兑现吗?", operation);
}


TrainingSubsidy.showExportModal = function(){
    $("#exportModal").modal("show");
}

TrainingSubsidy.exportBasicInfo =function(){
    var names = '';
    var values = '';
    $("#field_info li input").each(function(index){
        if($(this).is(":checked")){
            values = values + $(this).val() + ",";
            names = names + $(this).next().text() + ",";
        }
    });
    var queryData = TrainingSubsidy.formParams();
    queryData['names'] = names;
    queryData['values'] = values;
    $("#exportModal").modal('hide');
    var url = Feng.setUrlParam(Feng.ctxPath + "/trainingSubsidyExport/basicDataExport",queryData);
    window.hiddenIframe.location.href = url;
}

/**
* 是否发送短信
*/
TrainingSubsidy.toggleMessage = function(){
    var isMessage = $("input[name='isSend']:checked").val();
    if (isMessage==1) {
        $("#messageEdit").css("display","block");
    } else if ( isMessage == 2){
        $("#messageEdit").css("display","none");
    }
}

/**
 * 刷新检索
 */
TrainingSubsidy.prepareSearch = function () {
    var name = $("#preName").val();
    var idCard = $("#preIdCard").val();
    $('#dataTable').bootstrapTable("refresh",{"query":{"name":name,"idCard":idCard}});
}

/**
 * 重置
 */
TrainingSubsidy.prepareReset = function () {
    $("#preName").val("");
    $("#preIdCard").val("");
}

/**
 * 回调
 * @param data
 */
TrainingSubsidy.callBack = function(data){
    if(data.code == 200){
        Feng.success(data.msg);
    }else{
        Feng.info(data.msg);
    }
}

$(function () {
    var defaultColunms = TrainingSubsidy.initColumn();
    var table = new BSTable(TrainingSubsidy.id, "/trainingSubsidy/list", defaultColunms);
    table.setPaginationType("server");
    table.setOnDblClickRow(function () {
        TrainingSubsidy.openTrainingSubsidySelect();
    });
    TrainingSubsidy.table = table.init();
    var arr = [
        {"name":"cardType","code":"un_cardType"},
        {"name":"nationality","code":"un_nationality"}];
    Feng.findChildDictBatch(JSON.stringify(arr));
    $('#checkAll').click(function () {
        $("#dataTable").bootstrapTable('togglePagination').bootstrapTable('checkAll').bootstrapTable('togglePagination');
    })
    $('#uncheckAll').click(function () {
        $("#dataTable").bootstrapTable('togglePagination').bootstrapTable('uncheckAll').bootstrapTable('togglePagination')
    })
});
