/**
 * 初始化购房申请详情对话框
 */
var HouserRentingPurchaseApplyInfoDlg = {
    houserRentingPurchaseApplyInfoData : {},
    validateFields: {
        talentId: {validators: {notEmpty: {message: '申报对象不能为空'}}},
        email: {validators: {notEmpty: {message: '电子邮箱不能为空'}}},
        houseType: {validators: {notEmpty: {message: '拟申请购房人才社区不能为空'}}},
        cardType: {validators: {notEmpty: {message: '证件类型不能为空'}}},
        idCard: {validators: {notEmpty: {message: '证件号码不能为空'}}},
        marryStatus: {validators: {notEmpty: {message: '婚姻状态不能为空'}}},
    }
};

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

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

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

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

/**
 * 收集数据
 */
HouserRentingPurchaseApplyInfoDlg.collectData = function() {
    this
        .set('id')
        .set('type')
        .set('talentId')
        .set('phone')
        .set('email')
        .set('marryStatus')
        .set('spouseName')
        .set('spouseSex')
        .set('spouseCardType')
        .set('spouseIdCard')
        .set('spouseTalentArrange')
        .set('spouseNativePlace')
        .set('spouseEntryTime')
        .set('spousePost')
        .set('spouseEnterpriseName')
        .set('spouseEnterpriseAddress')
        .set('spouseAddress')
        .set('spousePhone')
        .set('spouseEmail')
        .set('houseType')
        .set('checkState')
        .set('applyAddress');
    this.houserRentingPurchaseApplyInfoData['pensionDetail'] = Feng.getCheckBoxValues("pensionDetail");
    this.houserRentingPurchaseApplyInfoData['unemploymentDetail'] = Feng.getCheckBoxValues("unemploymentDetail");
    this.houserRentingPurchaseApplyInfoData['medicaDetail'] = Feng.getCheckBoxValues("medicaDetail");
    this.houserRentingPurchaseApplyInfoData['taxDetail'] = Feng.getCheckBoxValues("taxDetail");
}

/**
 * 验证数据
 */
HouserRentingPurchaseApplyInfoDlg.validate = function () {
    $('#houseRentingPurchaseApplyInfoForm').data("bootstrapValidator").resetForm();
    $('#houseRentingPurchaseApplyInfoForm').bootstrapValidator('validate');
    return $("#houseRentingPurchaseApplyInfoForm").data('bootstrapValidator').isValid();
}



HouserRentingPurchaseApplyInfoDlg.nameChange = function(){
    var talentId = $("#talentId").val();
    if(Feng.isNotEmptyStr(talentId)){
        var ajax = new $ax(Feng.ctxPath + "/api/houserRentingPurchaseApply/initApplyDataByTalentId/"+talentId, function(data){
            if(data.code == 200){
                var talentInfo = data.obj;
                $("#name").val(talentInfo.name);
                $("#sex").val(talentInfo.sex);
                $("#cardType").val(talentInfo.cardType);
                $("#idCard").val(talentInfo.idCard);
                $("#nativePlace").val(talentInfo.provinceName+talentInfo.cityName+talentInfo.countyName);
                $("#talentArrange").val(talentInfo.talentArrange).trigger("change");
                $("#entryTime").val(talentInfo.entryTime);
                $("#post").val(talentInfo.post);
                $("#enterpriseAddress").val(talentInfo.enterpriseAddress);
                $("#phone").val(talentInfo.phone);
                $("#email").val(talentInfo.email);
                $("#houseType").val(talentInfo.houseType);
                $("#applyAddress").val(talentInfo.applyAddress);
            }else{
                Feng.info(data.msg);
            }
        },function(data){
            Feng.error("查询失败!" + data.responseJSON.message + "!");
        });
        ajax.start();
    }
}


/**
 * 添加未成年子女
 */
HouserRentingPurchaseApplyInfoDlg.addChild = function(){
    var options = $("#cardType").html();
    $("#childData").append(
        '<div class="col-sm-12">\n' +
        '<input type="hidden"  name="id"/>\n' +
        '<input type="hidden" name="pId"/>'+
        '<div class="rowGroup col-sm-3">\n' +
        '<input type="text" class="form-control" name="childName" placeholder="未成年子女姓名"/>\n' +
        '</div>\n' +
        '<div class="rowGroup col-sm-3">\n' +
        '<select class="form-control" name="childCardType" placeholder="未成年子女证件类型">\n' +
        options+
        '</select>\n' +
        '</div>\n' +
        '<div class="rowGroup col-sm-3">\n' +
        '<input type="text" class="form-control" name="childIdCard" placeholder="未成年子女证件号码"/>\n' +
        '</div>\n' +
        '<div class="add-btn"  onclick="HouserRentingPurchaseApplyInfoDlg.addChild()"></div>\n' +
        '<div class="reduce"  onclick="HouserRentingPurchaseApplyInfoDlg.reduceChild(this)"></div>'+
        '</div>');
}

/**
 * 删除子女信息
 */
HouserRentingPurchaseApplyInfoDlg.reduceChild = function(context){
    var id = $(context).parent().find("input[name='id']").val();
    if(Feng.isEmptyStr(id)){
        $(context).parent().remove();
        if($("#childData").children().length == 0){
            HouserRentingPurchaseApplyInfoDlg.addChild();
        }
    }else{
        if(!validateIsEdit())return;
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/api/houserRentingPurchaseApply/deleteChildren", function(data){
                if(data.code == 200){
                    $(context).parent().remove();
                    Feng.success(data.msg);
                    if($("#childData").children().length == 0){
                        HouserRentingPurchaseApplyInfoDlg.addChild();
                    }
                }else{
                    Feng.info(data.msg);
                }
            },function(data){
                Feng.error("添加失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id",id);
            ajax.start();
        }
        Feng.confirm("删除后无法恢复，确认删除吗?", operation);
    }
}

/**
 * 提交添加
 */
HouserRentingPurchaseApplyInfoDlg.addSubmit = function() {
    var id = $("#id").val();
    if(Feng.isNotEmptyStr(id)){
        HouserRentingPurchaseApplyInfoDlg.editSubmit(1);
        return;
    }
    this.clearData();
    this.collectData();
    if(!HouserRentingPurchaseApplyInfoDlg.validate()){
        return ;
    }
    //提交信息
    var child = new Array();
    var error = "";
    $("#childData .col-sm-12").each(function (index) {
        var id 	= $(this).find("input[name='id']").val();
        var pId = $(this).find("input[name='pId']").val();
        var childName = $(this).find("input[name='childName']").val();
        var childCardType = $(this).find("select[name='childCardType']").val();
        var childIdCard = $(this).find("input[name='childIdCard']").val();
        if (Feng.isNotEmptyStr(id) || Feng.isNotEmptyStr(pId) || Feng.isNotEmptyStr(childName) || Feng.isNotEmptyStr(childCardType) || Feng.isNotEmptyStr(childIdCard)){
            if(Feng.isEmptyStr(childName)){
                error =  error + "第"+ (index + 1) + "行未成年子女姓名为空;\n";
            }
            if(Feng.isEmptyStr(childCardType)){
                error =  error + "第"+ (index + 1) + "行未成年子女证件类型为空;\n";
            }
            if(Feng.isEmptyStr(childIdCard)){
                error =  error + "第"+ (index + 1) + "行未成年子女证件号码为空;\n";
            }
            child.push({"id":id,"pId":pId,"name":childName,"cardType":childCardType,"idCard":childIdCard});
        }
    });
    if (Feng.isNotEmptyStr(error)){
        Feng.info(error);
        return;
    }
    this.houserRentingPurchaseApplyInfoData['childList'] = child;
    var ajax = new $ax(Feng.ctxPath + "/api/houserRentingPurchaseApply/add", function(data){
        if(data.code == 200){
            var obj = data.obj;
            var childList = obj.childList;
            Feng.success(data.msg);
            $("#id").val(obj.id);
            $("#type").val(obj.type);
            $("#fileLi").removeAttr("style");
            $("#checkState").val(obj.checkState);
            HouserRentingPurchaseApplyInfoDlg.initChildData(childList);
        }else{
            Feng.info(data.msg);
        }
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.setcontentType("application/json;charset=utf-8");
    ajax.setData(JSON.stringify(this.houserRentingPurchaseApplyInfoData));
    ajax.start();
}

/**
 * 提交修改
 */
HouserRentingPurchaseApplyInfoDlg.editSubmit = function(type) {
    this.clearData();
    this.collectData();
    if(!validateIsEdit())return;
    if(!HouserRentingPurchaseApplyInfoDlg.validate()){
        return ;
    }
    //提交信息
    var child = new Array();
    var error = "";
    $("#childData .col-sm-12").each(function (index) {
        var id 	= $(this).find("input[name='id']").val();
        var pId = $(this).find("input[name='pId']").val();
        var childName = $(this).find("input[name='childName']").val();
        var childCardType = $(this).find("select[name='childCardType']").val();
        var childIdCard = $(this).find("input[name='childIdCard']").val();
        if (Feng.isNotEmptyStr(id) || Feng.isNotEmptyStr(pId) || Feng.isNotEmptyStr(childName) || Feng.isNotEmptyStr(childCardType) || Feng.isNotEmptyStr(childIdCard)){
            if(Feng.isEmptyStr(childName)){
                error =  error + "第"+ (index + 1) + "行未成年子女姓名为空;\n";
            }
            if(Feng.isEmptyStr(childCardType)){
                error =  error + "第"+ (index + 1) + "行未成年子女证件类型为空;\n";
            }
            if(Feng.isEmptyStr(childIdCard)){
                error =  error + "第"+ (index + 1) + "行未成年子女证件号码为空;\n";
            }
            child.push({"id":id,"pId":pId,"name":childName,"cardType":childCardType,"idCard":childIdCard});
        }
    });
    if (Feng.isNotEmptyStr(error)){
        Feng.info(error);
        return;
    }
    this.houserRentingPurchaseApplyInfoData['childList'] = child;
    var ajax = new $ax(Feng.ctxPath + "/api/houserRentingPurchaseApply/update", function(data){
        if(data.code == 200){
            if(type == 1){
                var childList = data.obj.childList;
                Feng.success(data.msg);
                HouserRentingPurchaseApplyInfoDlg.initChildData(childList);
            }else{
                HouserRentingPurchaseApplyInfoDlg.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.houserRentingPurchaseApplyInfoData));
    ajax.start();
}

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


/**
 * 校验是否显示按钮
 * @param type      类型  1-上传按钮，2-修改删除按钮
 * @param row
 * @returns {string}
 */
function validUploadButton(type,row,fileId){
    var files = $("#files").val();
    var checkState = $("#checkState").val();
    if(Feng.isEmptyStr(checkState)||checkState==1 || (checkState == 10 )){
        return type == 1?
            "<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>"
            :
            "<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_renting_purchase_apply+"')\" class=\"btn btn-xs btn-danger\">" +
            "<i class=\"fa fa-times\"></i>删除" +
            "</button>";
    }else{
        return type == 1?"":"" ;
    }
}

function validateIsEdit(){
    var id = $("#id").val();
    var checkState = $("#checkState").val();
    if(Feng.isEmptyStr(id)){
        Feng.info("请先填写基础信息并上传附件");
        return false;
    }
    if(checkState != 1 && checkState != 10){
        if(checkState==-1){
            Feng.error("您的申报审核不通过，无法修改");
            return false;
        }else if(checkState>=30){
            Feng.error("您的申报已审核通过，无法修改");
            return false;
        }else{
            Feng.error("您的申报正在审核中，请耐心等待");
            return false;
        }
    }
    return true;
}

/**
 * 初始化子女信息
 * @param list
 */
HouserRentingPurchaseApplyInfoDlg.initChildData = function(list){
    var options = $("#cardType").html();
    var html = "";
    for(var key in list) {
        html = html +
            '<div class="col-sm-12">\n' +
            '<input type="hidden"  name="id" value="'+list[key].id+'"/>\n' +
            '<input type="hidden" name="pId" value="'+list[key].pId+'"/>' +
            '<div class="rowGroup col-sm-3">\n' +
            '<input type="text" class="form-control" name="childName" value="'+list[key].name+'" placeholder="未成年子女姓名"/>\n' +
            '</div>\n' +
            '<div class="rowGroup col-sm-3">\n' +
            '<select class="form-control" name="childCardType" value="'+list[key].cardType+'" placeholder="未成年子女证件类型">\n' +
            options +
            '</select>\n' +
            '</div>\n' +
            '<div class="rowGroup col-sm-3">\n' +
            '<input type="text" class="form-control" name="childIdCard" value="'+list[key].idCard+'" placeholder="未成年子女证件号码"/>\n' +
            '</div>\n' +
            '<div class="add-btn"  onclick="HouserRentingPurchaseApplyInfoDlg.addChild()"></div>\n' +
            '<div class="reduce"  onclick="HouserRentingPurchaseApplyInfoDlg.reduceChild(this)"></div>'+
            '</div>';
    }
    if(Feng.isEmptyStr(html)){
        html = html +
            '<div class="col-sm-12">\n' +
            '<input type="hidden"  name="id" />\n' +
            '<input type="hidden" name="pId" />' +
            '<div class="rowGroup col-sm-3">\n' +
            '<input type="text" class="form-control" name="childName"  placeholder="未成年子女姓名"/>\n' +
            '</div>\n' +
            '<div class="rowGroup col-sm-3">\n' +
            '<select class="form-control" name="childCardType" placeholder="未成年子女证件类型">\n' +
            options +
            '</select>\n' +
            '</div>\n' +
            '<div class="rowGroup col-sm-3">\n' +
            '<input type="text" class="form-control" name="childIdCard"  placeholder="未成年子女证件号码"/>\n' +
            '</div>\n' +
            '<div class="add-btn"  onclick="HouserRentingPurchaseApplyInfoDlg.addChild()"></div>\n' +
            '</div>';
    }
    $("#childData").empty().append(html);
    $("#childData select").each(function () {
        $(this).val($(this).attr("value"))
    })
    if(list == null){
        HouserRentingPurchaseApplyInfoDlg.addChild();
    }
}


HouserRentingPurchaseApplyInfoDlg.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);
        }
    })
}

$(function() {
    Feng.initValidatorTip("houseRentingPurchaseApplyInfoForm", HouserRentingPurchaseApplyInfoDlg.validateFields);
    //批量加载字典表数据
    var arr = [
        {"name":"cardType","code":"un_cardType"},
        {"name":"talentArrange","code":"un_talentLevel"},
        {"name":"houseType","code":"un_renting_houseType"},
        {"name":"marryStatus","code":"un_marryStatus"},
        {"name":"spouseCardType","code":"un_cardType"},
        {"name":"spouseTalentArrange","code":"un_talentLevel"}];
    Feng.findChildDictBatch(JSON.stringify(arr));
    $("select[name='childCardType']").empty().append($("#cardType").html());
    //加载时间控件
    $(".date").each(function(){laydate.render({
        elem: this,type: 'date',trigger: 'click'
        });
    });
    var id = $("#id").val();
    if(Feng.isNotEmptyStr(id)){
        $("select").each(function () {$(this).val($(this).attr("value")).trigger("change");});
        $("#fileLi").removeAttr("style");
        HouserRentingPurchaseApplyInfoDlg.checkSbAndTax();
        Feng.getCheckLog("logTable",{"type":CONFIG.project_renting_purchase_apply,"mainId":id,"typeFileId":"","active":1})
    }else{
        $("#fileLi").attr("style","pointer-events: none");
    }
});
