/**
 * 初始化医疗补助详情对话框
 */
var MedicalSubsidyInfoDlg = {
    medicalSubsidyInfoData : {},
    validateFields: {
        talentId: {validators: {notEmpty: {message: '申报人不能为空'}}},
        address: {validators: {notEmpty: {message: '现居地址不能为空'}}},
        phone: {
            validators: {
                notEmpty: {
                    message: '联系电话不能为空'
                },
                regexp: {
                    regexp: /0?(13|14|15|16|17|18|19)[0-9]{9}/,
                    message: "手机号码格式不正确"
                }
            }
        },
    }
};

/**
 * 清除数据
 */
MedicalSubsidyInfoDlg.clearData = function() {
    this.medicalSubsidyInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
MedicalSubsidyInfoDlg.set = function(key, val) {
    this.medicalSubsidyInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
MedicalSubsidyInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
MedicalSubsidyInfoDlg.close = function() {
    parent.layer.close(window.parent.MedicalSubsidy.layerIndex);
}

/**
 * 收集数据
 */
MedicalSubsidyInfoDlg.collectData = function() {
    this
    .set('id')
    .set('year')
    .set('talentId')
    .set('address')
    .set('phone')
    .set('checkState');
    this.medicalSubsidyInfoData['pensionDetail'] = Feng.getCheckBoxValues("pensionDetail");
    this.medicalSubsidyInfoData['unemploymentDetail'] = Feng.getCheckBoxValues("unemploymentDetail");
    this.medicalSubsidyInfoData['medicaDetail'] = Feng.getCheckBoxValues("medicaDetail");
    this.medicalSubsidyInfoData['taxDetail'] = Feng.getCheckBoxValues("taxDetail");
}

/**
 * 根据所选人才对象初始化相应数据
 */
MedicalSubsidyInfoDlg.objChange = function(){
    var talentId = $("#talentId").val();
    if(Feng.isEmptyStr(talentId)){
        $("#sex,#cardType,#idcard,#talentArrange,#certificateNo,#nativePlace,#phone,#bankAddress,#bankNumber").val("");
    }else{
        var ajax = new $ax(Feng.ctxPath + "/api/talentInfo/detail/"+talentId, function(data){
            $("#sex").val(data.sex);
            $("#cardType").val(data.cardType);
            $("#idCard").val(data.idCard);
            $("#talentArrange").val(data.talentArrange);
            $("#certificateNo").val(data.certificateNO);
            $("#nativePlace").val(data.provinceName+data.cityName+data.countyName);
            $("#phone").val(data.phone);
            $("#bankAddress").val(data.bankNetwork);
            $("#bankNumber").val(data.bankAccount);
        },function(data){
            Feng.error("查询失败!" + data.responseJSON.message + "!");
        });
        ajax.start();
    }
}

/**
 * 校验字段
 */
MedicalSubsidyInfoDlg.validate = function(){
    $('#medicSubsidyForm').data("bootstrapValidator").resetForm();
    $('#medicSubsidyForm').bootstrapValidator('validate');
    return $("#medicSubsidyForm").data('bootstrapValidator').isValid();
}


/**
 * 校验是否可以操作
 */
function validateIsEdit () {
    var checkState = $("#checkState").val();
    if(Feng.isNotEmptyStr(checkState) && checkState != 1 && checkState != 4) {
        Feng.error("您的申报正在审核中或已审核完成，无法操作");
        return false;
    }
    return true;
}


/**
 * 提交添加
 */
MedicalSubsidyInfoDlg.addSubmit = function() {
    if(Feng.isNotEmptyStr($("#id").val())){
        MedicalSubsidyInfoDlg.editSubmit(1);
        return;
    }
    this.clearData();
    this.collectData();
    if(!MedicalSubsidyInfoDlg.validate()){
        return ;
    }
    if(!validateIsEdit())return;
    //提交信息
    var hospitalArr = new Array();
    var error = MedicalSubsidyInfoDlg.getHospitalArray(hospitalArr);
    if (Feng.isNotEmptyStr(error)){
        Feng.info(error);
        return ;
    }
    this.medicalSubsidyInfoData["feesList"] = hospitalArr;
    var ajax = new $ax(Feng.ctxPath + "/api/medicalSubsidy/add", function(data){
        if(data.code == 200){
            Feng.success(data.msg);
            window.parent.MedicalSubsidy.table.refresh();
            $("#id").val(data.obj.id);
            $("#checkState").val(data.obj.checkState);
            MedicalSubsidyInfoDlg.initHospital(data.obj.feesList);
            MedicalSubsidyInfoDlg.validId();
        }else{
            Feng.info(data.msg);
        }
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.setcontentType("application/json;charset=utf-8");
    ajax.setData(JSON.stringify(this.medicalSubsidyInfoData));
    ajax.start();
}

/**
 * 提交修改
 */
MedicalSubsidyInfoDlg.editSubmit = function(type) {
    this.clearData();
    this.collectData();
    if(!MedicalSubsidyInfoDlg.validate()){
        return ;
    }
    if(!validateIsEdit())return;
    //提交信息
    var hospitalArr = new Array();
    var error = MedicalSubsidyInfoDlg.getHospitalArray(hospitalArr);
    if (Feng.isNotEmptyStr(error)){
        Feng.info(error);
        return ;
    }
    this.medicalSubsidyInfoData["feesList"] = hospitalArr;
    var ajax = new $ax(Feng.ctxPath + "/api/medicalSubsidy/update", function(data){
        if(data.code == 200){
            if(type == 1){
                Feng.success(data.msg);
                MedicalSubsidyInfoDlg.initHospital(data.obj.feesList);
                window.parent.MedicalSubsidy.table.refresh();
            }else{
                MedicalSubsidyInfoDlg.submitToCheck();
            }
        }else{
            Feng.info(data.msg);
        }
    },function(data){
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.setcontentType("application/json;charset=utf-8");
    ajax.setData(JSON.stringify(this.medicalSubsidyInfoData));
    ajax.start();
}

MedicalSubsidyInfoDlg.getHospitalArray = function(hospitalArr){
    var error = "";
    $("#hospitalDiv .panel-body").each(function (index) {
        var id = $(this).find("input[name='id']").val();
        var mainId = $(this).find("input[name='mainId']").val();
        var hospital = $(this).find("input[name='hospital']").val();
        var startTime = $(this).find("input[name='startTime']").val();
        var endTime = $(this).find("input[name='endTime']").val();
        var settlementTime = $(this).find("input[name='settlementTime']").val();
        var total = $(this).find("input[name='total']").val();
        var plan = $(this).find("input[name='plan']").val();
        var insurance = $(this).find("input[name='insurance']").val();
        var ownFees = $(this).find("input[name='ownFees']").val();
        if(Feng.isNotEmptyStr(id) || Feng.isNotEmptyStr(mainId) || Feng.isNotEmptyStr(hospital) || Feng.isNotEmptyStr(settlementTime)||Feng.isNotEmptyStr(ownFees)){
            if(Feng.isEmptyStr(hospital)){
                error =  error + "第"+ (index + 1) + ")个救治医院为空;\n";
            }
            if(Feng.isEmptyStr(startTime)){
                error =  error + "第"+ (index + 1) + "个住院开始时间为空;\n";
            }else if(!/^\d{4}-\d{2}-\d{2}$/.test(startTime)){
                error =  error + "第"+ (index + 1) + "个住院开始时间格式不正确;\n";
            }
            if(Feng.isEmptyStr(endTime)){
                error =  error + "第"+ (index + 1) + "个住院截止时间为空;\n";
            }else if(!/^\d{4}-\d{2}-\d{2}$/.test(endTime)){
                error =  error + "第"+ (index + 1) + "个住院截止时间格式不正确;\n";
            }
            if(Feng.isEmptyStr(settlementTime)){
                error =  error + "第"+ (index + 1) + "个医保报销结算时间为空;\n";
            }else if(!/^\d{4}-\d{2}-\d{2}$/.test(settlementTime)){
                error =  error + "第"+ (index + 1) + "个医保报销结算时间格式不正确;\n";
            }
            if(Feng.isEmptyStr(total)){
                error =  error + "第"+ (index + 1) + "个总费用为空;\n";
            }else if(!/^([1-9][0-9]*)+(\.[0-9]{1,10})?$/.test(total)){
                error =  error + "第"+ (index + 1) + "个总费用格式不正确;\n";
            }
            if(Feng.isEmptyStr(plan)){
                error =  error + "第"+ (index + 1) + "个统筹基金为空;\n";
            }else if(!/^([1-9][0-9]*)+(\.[0-9]{1,10})?$/.test(plan)){
                error =  error + "第"+ (index + 1) + "个统筹基金格式不正确;\n";
            }
            if(Feng.isEmptyStr(insurance)){
                error =  error + "第"+ (index + 1) + "个商保基金为空;\n";
            }else if(!/^([1-9][0-9]*)+(\.[0-9]{1,10})?$/.test(insurance)){
                error =  error + "第"+ (index + 1) + "个商保基金格式不正确;\n";
            }
            if(Feng.isEmptyStr(ownFees)){
                error =  error + "第"+ (index + 1) + "个个人自费为空;\n";
            }else if(!/^([1-9][0-9]*)+(\.[0-9]{1,10})?$/.test(ownFees)){
                error =  error + "第"+ (index + 1) + "个个人自费格式不正确;\n";
            }
            hospitalArr.push({"id":id,"mainId":Feng.isEmptyStr(mainId)?$("#id").val():mainId,"hospital":hospital,"startTime":startTime,"endTime":endTime,"settlementTime":settlementTime,"total":total,"plan":plan,"insurance":insurance,"ownFees":ownFees});
        }
    });
    return error;
}


MedicalSubsidyInfoDlg.initHospital = function(list){
    $("#hospitalDiv").find(".panel-default").remove();
    var html = "";
    for(var key in list){
        html = html +   '<div class="panel panel-default ">\n' +
            '    <div class="panel-heading">\n' +
            '        <span class="caret" onclick="$(this).parent().next().toggle()"></span>\n' +
            '        <span class="hospitalName">'+list[key].hospital+'</span>\n' +
            '        <button type="button" class="btn btn-xs btn-danger" style="float: right" onclick="MedicalSubsidyInfoDlg.removeHospital(this)"><i class="fa fa-remove"></i>删除</button>\n' +
            '    </div>\n' +
            '    <div class="panel-body">\n' +
            '        <div class="col-sm-12">\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <input type="hidden" name="id" value="'+list[key].id+'"/>\n' +
            '                <input type="hidden" name="mainId" value="'+list[key].mainId+'"/>\n' +
            '                <label class="control-label spacing">救治医院</label>\n' +
            '                <input type="text" class="form-control" name="hospital" value="'+list[key].hospital+'" onchange="MedicalSubsidyInfoDlg.addTitle(this)" onkeypress="MedicalSubsidyInfoDlg.addTitle(this)"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">住院开始时间</label>\n' +
            '                <input type="text" class="form-control date"  name="startTime" value="'+list[key].startTime+'"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">住院截止时间</label>\n' +
            '                <input type="text" class="form-control date" name="endTime" value="'+list[key].endTime+'"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">医保报销结算时间</label>\n' +
            '                <input type="text" class="form-control date" name="settlementTime" value="'+list[key].settlementTime+'"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">总费用</label>\n' +
            '                <input type="text" class="form-control" name="total"  value="'+list[key].total+'"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">统筹基金</label>\n' +
            '                <input type="text" class="form-control" name="plan" value="'+list[key].plan+'"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">商保基本</label>\n' +
            '                <input type="text" class="form-control" name="insurance" value="'+list[key].insurance+'"/>\n' +
            '            </div>\n' +
            '            <div class="rowGroup col-sm-3">\n' +
            '                <label class="control-label spacing">个人自费</label>\n' +
            '                <input type="text" class="form-control" name="ownFees" value="'+list[key].ownFees+'"/>\n' +
            '            </div>\n' +
            '        </div>\n' +
            '    </div>\n' +
            '</div>'
    }
    $("#hospitalDiv").append(html);
}


/**
 * 提交审核
 */
MedicalSubsidyInfoDlg.submitToCheck = function () {
    var id = $("#id").val();
    if(id==null || id==""){
        Feng.info("请先填写基础信息并上传附件");
        return ;
    }
    if(!validateIsEdit())return;
    var operation = function() {
        var ajax = new $ax(Feng.ctxPath + "/api/medicalSubsidy/submitToCheck", function (data) {
            if(data.code==200){
                Feng.success(data.msg);
                // $("#checkState").val(data.obj);
                window.parent.MedicalSubsidy.table.refresh();
                MedicalSubsidyInfoDlg.close();
            }else{
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("提交审核失败!" + data.responseJSON.message + "!");
        });
        ajax.set("id", id);
        ajax.start();
    }
    Feng.confirm("请确认基础信息已核对无误，相应附件已上传，一旦提交，无法修改", operation);
}

/**
 * 校验是否显示按钮
 * @param type      类型  1-上传按钮，2-修改删除按钮
 * @param row
 * @returns {string}
 */
function validUploadButton(type,row,fileId){
    var checkState = $("#checkState").val();
    if(Feng.isEmptyStr(checkState)|| checkState ==1 ||checkState== 4){
        if(type == 1){          //上传
            return "<button type='button' onclick=\"checkFile(this,'"+row.id+"','"+null+"')\" style='margin-right: 10px' class=\"btn btn-xs btn-info\">" +
                "<i class=\"fa fa-upload\"></i>上传" +
                "</button>" ;
        }else{
            return "<button type=\'button\' onclick=\"checkFile(this,'"+row.id+"','"+fileId+"')\" style=\'margin-right: 10px\' class=\"btn btn-xs btn-info\">" +
                "<i class=\"fa fa-paste\"></i>修改" +
                "</button>" +
                "<button type='button' onclick=\"deleteFile('"+fileId+"','"+CONFIG.project_medical+"')\" class=\"btn btn-xs btn-danger\">" +
                "<i class=\"fa fa-times\"></i>删除" +
                "</button>";
        }
    }else{
        return type == 1?"":"";
    }
}


//校验是否保存基础信息
MedicalSubsidyInfoDlg.validId = function (){
    $("#fileLi").css("pointer-events",Feng.isEmptyStr($("#id").val())?"none":"auto");
}

MedicalSubsidyInfoDlg.checkSbAndTax = function(){
    var pensionDetail = $("#pensionDetail").attr("value");
    var unemploymentDetail = $("#unemploymentDetail").attr("value");
    var medicaDetail = $("#medicaDetail").attr("value");
    var taxDetail = $("#taxDetail").attr("value");
    $("#pensionDetail input").each(function () {
        if(pensionDetail.indexOf($(this).val())!= -1){
            $(this).attr("checked", true);
        }
    })
    $("#unemploymentDetail input").each(function () {
        if(unemploymentDetail.indexOf($(this).val())!= -1){
            $(this).attr("checked", true);
        }
    })
    $("#medicaDetail input").each(function () {
        if(medicaDetail.indexOf($(this).val())!= -1){
            $(this).attr("checked", true);
        }
    })
    $("#taxDetail input").each(function () {
        if(taxDetail.indexOf($(this).val())!= -1){
            $(this).attr("checked", true);
        }
    })
}

/**
 * 同步医院标题
 * @param context
 */
MedicalSubsidyInfoDlg.addTitle = function(context){
    $(context).parent().parent().parent().parent().find(".hospitalName").text($(context).val());
}

MedicalSubsidyInfoDlg.addHospital = function(){
    $("#hospitalDiv").append(
        '<div class="panel panel-default ">\n' +
        '    <div class="panel-heading">\n' +
        '        <span class="caret" onclick="$(this).parent().next().toggle()"></span>\n' +
        '        <span class="hospitalName"></span>\n' +
        '        <button type="button" class="btn btn-xs btn-danger" style="float: right" onclick="MedicalSubsidyInfoDlg.removeHospital(this)"><i class="fa fa-remove"></i>删除</button>\n' +
        '    </div>\n' +
        '    <div class="panel-body">\n' +
        '        <div class="col-sm-12">\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <input type="hidden" name="id"/>\n' +
        '                <input type="hidden" name="mainId" />\n' +
        '                <label class="control-label spacing">救治医院</label>\n' +
        '                <input type="text" class="form-control" name="hospital" onchange="MedicalSubsidyInfoDlg.addTitle(this)" onkeypress="MedicalSubsidyInfoDlg.addTitle(this)"/>\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">住院开始时间</label>\n' +
        '                <input type="text" class="form-control date" name="startTime" />\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">住院截止时间</label>\n' +
        '                <input type="text" class="form-control date" name="endTime"/>\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">医保报销结算时间</label>\n' +
        '                <input type="text" class="form-control date" name="settlementTime"/>\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">总费用</label>\n' +
        '                <input type="text" class="form-control" name="total"/>\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">统筹基金</label>\n' +
        '                <input type="text" class="form-control" name="plan"/>\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">商保基本</label>\n' +
        '                <input type="text" class="form-control" name="insurance"/>\n' +
        '            </div>\n' +
        '            <div class="rowGroup col-sm-3">\n' +
        '                <label class="control-label spacing">个人自费</label>\n' +
        '                <input type="text" class="form-control" name="ownFees"/>\n' +
        '            </div>\n' +
        '        </div>\n' +
        '    </div>\n' +
        '</div>');
    Feng.initDate();
}

/**
 * 删除住院信息
 * @param context
 */
MedicalSubsidyInfoDlg.removeHospital = function(context){
    var id = $(context).parent().parent().find("input[name='id']").val();
    if(Feng.isEmptyStr(id)){
        $(context).parent().parent().remove();
    }else{
        var operation = function() {
            var ajax1 = new $ax(Feng.ctxPath + "/api/medicalSubsidy/removeHospital", function (data) {
                if (data.code == 200) {
                    Feng.success(data.msg);
                    $(context).parent().parent().remove();
                } else {
                    Feng.info(data.msg);
                }
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax1.set("id", id);
            ajax1.start();
        }
        Feng.confirm("一旦删除无法恢复，确认删除吗?", operation);
    }
}

$(function() {
    Feng.initValidatorTip("medicSubsidyForm",MedicalSubsidyInfoDlg.validateFields);
    var arr = [{"name":"talentArrange","code":"un_talentLevel"},
        {"name":"cardType","code":"un_cardType"}];
    Feng.findChildDictBatch(JSON.stringify(arr))
    Feng.initDate();
    if(Feng.isNotEmptyStr($("#id").val())){
        $("select").each(function () {
            $(this).val($(this).attr("value")).trigger("change");
        });
        Feng.getCheckLog("logTable",{"type":CONFIG.project_medical,"mainId":$("#id").val(),"typeFileId":"","active":1})
        MedicalSubsidyInfoDlg.checkSbAndTax();
    }
    MedicalSubsidyInfoDlg.validId();
});
