/**
 * 初始化硕博人才生活补贴申报详情对话框
 */
var LivingAllowanceInfoInfoDlg = {
    livingAllowanceInfoInfoData: {},
    locked: false,
    validateFields: {
        enterpriseId: {validators: {notEmpty: {message: '所属企业不能为空'}}},
        enterpriseName: {validators: {notEmpty: {message: '所属企业不能为空'}}},
        declareType: {validators: {notEmpty: {message: '申报类型不能为空'}}},
        type: {validators: {notEmpty: {message: '人才类别不能为空'}}},
        name: {validators: {notEmpty: {message: '姓名不能为空'}}},
        nation: {validators: {notEmpty: {message: '民族不能为空'}}},
        provinceCode: {validators: {notEmpty: {message: '户籍省份不能为空'}}},
        cityCode: {validators: {notEmpty: {message: '户籍市不能为空'}}},
        address: {validators: {notEmpty: {message: '现居地址不能为空'}}},
        highEducation: {validators: {notEmpty: {message: '最高学历不能为空'}}},
        graduateSchool: {validators: {notEmpty: {message: '毕业院校不能为空'}}},
        major: {validators: {notEmpty: {message: '专业不能为空'}}},
        phone: {
            validators: {
                notEmpty: {
                    message: '手机号码不能为空'
                },
                regexp: {
                    regexp: /0?(13|14|15|16|17|18|19)[0-9]{9}/,
                    message: "手机号码格式不正确"
                }
            }
        },
        bank: {
            validators: {
                notEmpty: {
                    message: '开户银行不能为空'
                },
                regexp: {
                    regexp: /^[\u4e00-\u9fa5]*银行$/,
                    message: "开户银行格式不正确"
                }
            }
        },
        bankAccount: {
            validators: {
                notEmpty: {
                    message: '银行账号不能为空'
                },
                regexp: {
                    regexp: /^\d+$/,
                    message: "银行账号格式不正确"
                }
            }
        },
        entryTime: {validators: {notEmpty: {message: '入职时间不能为空'}}},
        endTime: {validators: {notEmpty: {message: '工作合同结束时间不能为空'}}},
        type: {validators: {notEmpty: {message: '人才类别不能为空'}}},
        cardType: {validators: {notEmpty: {message: '证件类型不能为空'}}},
        idCard: {validators: {notEmpty: {message: '证件号码不能为空'}}},
        sex: {validators: {notEmpty: {message: '性别不能为空'}}},
        nationality: {validators: {notEmpty: {message: '国籍/地区不能为空'}}},
        birthday: {validators: {notEmpty: {message: '出生日期不能为空'}}},
        //firstSocialSecurityTime: {validators: {notEmpty: {message: '首次社保缴纳时间不能为空'}}},
        politics: {validators: {notEmpty: {message: '政治面貌不能为空'}}},
        post: {validators: {
                notEmpty: {message: '职务不能为空'},
                regexp: {
                    regexp: /^[\u4e00-\u9fa5]{0,}$/,
                    message: "职务必须为汉字"
                }

            }},
        email: {

            validators: {
                notEmpty: {
                    message: '电子邮箱不能为空'
                },
                emailAddress: {
                    message: "电子邮箱格式不正确"
                }
            }
        },
        bankNetwork: {
            validators: {
                notEmpty: {
                    message: '开户银行网点不能为空'
                },
                regexp: {
                    regexp: /^[\u4e00-\u9fa5]*银行[\u4e00-\u9fa5]*省?[\u4e00-\u9fa5]+市[\u4e00-\u9fa5]*$/,
                    message: "开户银行格式不正确"
                }
            }
        },
        bankNumber: {
            validators: {
                notEmpty: {
                    message: '银行行号不能为空'
                },
                regexp: {
                    regexp: /^\d{12}$/,
                    message: "银行行号格式不正确"
                }
            }
        },
        introductionMethod: {
            validators: {
                notEmpty: {
                    message: '引进方式不能为空'
                }
            }
        },
        startTime: {validators: {notEmpty: {message: '工作合同开始时间不能为空'}}},
        mainHonours: {validators: {notEmpty: {message: '主要业绩及取得的荣誉不能为空'}}},
        educationAndResume: {validators: {notEmpty: {message: '教育背景及工作简历不能为空'}}},
        // firstInJJTime: {validators: {notEmpty: {message: '首次来晋工作时间不能为空'}}},
        industryField: {validators: {notEmpty: {message: '行业领域不能为空'}}}
    },
    tax: null,
    socialSecurity: null,
    getBirthdayByIdCard() {
        var cardType = $("#cardType").val();
        if (cardType == 1) {
            var idCard = $("#idCard").val();
            $("#birthday").val(idCard.substring(6, 10) + "-" + idCard.substring(10, 12) + "-" + idCard.substring(12, 14));
        }
    }
};

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

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

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

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

/**
 * 收集数据
 */
LivingAllowanceInfoInfoDlg.collectData = function () {
    this
            .set('id')
            .set('year')
            .set('enterpriseId')
            .set('enterpriseName')
            .set('type')
            .set('declareType')
            .set('cardType')
            .set('idCard')
            .set('name')
            .set('photo')
            .set('sex')
            .set('nation')
            .set('nationality')
            .set('provinceCode')
            .set('cityCode')
            .set('countyCode')
            .set('birthday')
            .set('address')
            .set('politics')
            .set('highEducation')
            .set('graduateSchool')
            .set('major')
            .set('post')
            .set('phone')
            .set('email')
            .set('bank')
            .set('bankNetwork')
            .set('bankAccount')
            .set('bankNumber')
            .set('entryTime')
            // .set('quitTime')
            .set('startTime')
            .set('endTime')
            .set('educationAndResume')
            .set('mainHonours')
            .set('firstInJJTime')
            // .set('isIntroduction')
            .set('industryFieldNew')
            .set('industryField')
            .set('title')
            .set('professionalQualifications')
            .set('studyAbroad')
            // .set('studyAbroadCountry')
            .set('studyAbroadTime')
            .set('backJJBusinessTime')
            .set('introductionMethod')
            .set('firstSocialSecurityTime')
            // .set('introductionMode')
            // .set('letterTime')
            // .set('applyCount')
            ;
    if ($("#provinceCode").val() != null && $("#provinceCode").val() != '') {
        this.livingAllowanceInfoInfoData["provinceName"] = $("#provinceCode").find("option:selected").text();
    }
    if ($("#cityCode").val() != null && $("#cityCode").val() != '') {
        this.livingAllowanceInfoInfoData["cityName"] = $("#cityCode").find("option:selected").text();
    }
    if ($("#countyCode").val() != null && $("#countyCode").val() != '') {
        this.livingAllowanceInfoInfoData["countyName"] = $("#countyCode").find("option:selected").text();
    }
    var personalTaxVal = LivingAllowanceInfoInfoDlg.tax.getValue();
    var socialSecurityVal = LivingAllowanceInfoInfoDlg.socialSecurity.getValue();
    // if(personalTaxVal == null || personalTaxVal.length <= 0){
    //     Feng.info("")
    // }
    var personalTax = personalTaxVal.map(function (item) {
        return item.value;
    }).sort().join(",");
    var socialSecurity = socialSecurityVal.map(function (item) {
        return item.value;
    }).sort().join(",");
    LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData["personalTax"] = personalTax;
    LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData["socialSecurity"] = socialSecurity;
}

/**
 * 数据校验
 * @returns {*|Window.jQuery}
 */
LivingAllowanceInfoInfoDlg.validate = function () {
    $('#talentInfoForm').data("bootstrapValidator").resetForm();
    $('#talentInfoForm').bootstrapValidator('validate');
    return $("#talentInfoForm").data('bootstrapValidator').isValid();
}

LivingAllowanceInfoInfoDlg.upsertValidate = function () {
    this.clearData();
    this.collectData();
    if (!LivingAllowanceInfoInfoDlg.validate()) {
        return;
    }
    // if (Feng.isEmptyStr(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.socialSecurity)) {
    //     Feng.info("社保缴交情况不能为空!");
    //     return;
    // }
    if (LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.introductionMethod == 1) {
        if (Feng.isEmptyStr(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.firstInJJTime)) {
            Feng.info("首次来晋时间不能为空!");
            return;
        }
        var dateArr = new Array(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.firstSocialSecurityTime,
                LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.entryTime,
                LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.startTime);
        dateArr.sort(function (a, b) {
            return a > b ? 1 : -1
        });
        if (new Date(dateArr[0]).getTime() < new Date("2021-11-16").getTime()) {
            Feng.info("不符合2021年11月16日起新引进的人才条件,无法申报");
            return;
        }
    }
    if (LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.introductionMethod == 2) {
        if (Feng.isEmptyStr(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.backJJBusinessTime)) {
            Feng.info("返晋创业时间不能为空!");
            return;
        }
        if (new Date("2021-11-16").getTime() > new Date(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.backJJBusinessTime).getTime()) {
            Feng.info("引进方式为其他的必须满足：返晋创业时间在2021-11-16至2022-11-15之间！");
            return;
        }
        if (new Date("2022-11-15").getTime() < new Date(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.backJJBusinessTime).getTime()) {
            Feng.info("引进方式为其他的必须满足：返晋创业时间在2021-11-16至2022-11-15之间！");
            return;
        }
    }
    if (Feng.isEmptyStr(LivingAllowanceInfoInfoDlg.livingAllowanceInfoInfoData.id) && Feng.isEmptyStr($("#photo").val())) {
        Feng.info("头像不能为空!");
        return;
    }
    var formData = new FormData();
    Object.keys(this.livingAllowanceInfoInfoData).forEach((key) => {
        formData.append(key, this.livingAllowanceInfoInfoData[key]);
    });
    formData.append('file', $('#photo')[0].files[0]);
    return formData;
}


/**
 * 提交添加
 */
LivingAllowanceInfoInfoDlg.addSubmit = function () {
    var formData = LivingAllowanceInfoInfoDlg.upsertValidate();
    if (formData == null) {
        return;
    }
    if (LivingAllowanceInfoInfoDlg.locked) {
        return;
    }
    LivingAllowanceInfoInfoDlg.locked = true;
    $.ajax({
        url: Feng.ctxPath + "/enterprise/living_allowance/apply",
        type: "POST",
        processData: false,
        contentType: false,
        data: formData,
        success: function (data) {
            LivingAllowanceInfoInfoDlg.setNoChangeField();
            LivingAllowanceInfoInfoDlg.locked = false;
            if (data.code == 200) {
                Feng.success(data.msg);
                window.parent.LivingAllowanceInfo.table.refresh();
                $("#id").val(data.obj.id);
                $("#fileLi").removeAttr("style");
                $("#checkState").val(data.obj.checkState);
            } else {
                Feng.info(data.msg);
            }
        }, error: function (data) {
            LivingAllowanceInfoInfoDlg.locked = false;
            Feng.error("保存失败!" + data.responseJSON.message + "!");
        }
    });
}

/**
 * 提交审核
 */
LivingAllowanceInfoInfoDlg.submitToCheck = function () {
    var id = $("#id").val();
    if (Feng.isEmptyStr(id)) {
        Feng.info("请先填写基础信息并上传附件");
        return;
    }
    if (!validateIsEdit())
        return;
    var formData = LivingAllowanceInfoInfoDlg.upsertValidate();
    if (formData == null) {
        return;
    }
    $.ajax({
        url: Feng.ctxPath + "/enterprise/living_allowance/apply",
        type: "POST",
        processData: false,
        contentType: false,
        data: formData,
        async: true,
        success: function (data) {
            if (data.code == 200) {
                LivingAllowanceInfoInfoDlg.submitFun();
            } else {
                Feng.info(data.msg);
            }
        }, error: function (data) {
            LivingAllowanceInfoInfoDlg.locked = false;
            Feng.error("提交失败!" + data.responseJSON.message + "!");
        }
    });

}

LivingAllowanceInfoInfoDlg.submitFun = function () {
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/enterprise/living_allowance/submitToCheck", function (data) {
            if (data.code == 200) {
                Feng.success(data.msg);
                // $("#checkState").val(data.obj);
                window.parent.LivingAllowanceInfo.table.refresh();
                LivingAllowanceInfoInfoDlg.close();
            } else if (data.code == 600) {
                layer.confirm(data.msg, {
                    btn: ['我已知晓'] //按钮
                }, function () {
                    window.parent.LivingAllowanceInfo.table.refresh();
                    LivingAllowanceInfoInfoDlg.close();
                });
            } else {
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("提交审核失败!" + data.responseJSON.message + "!");
        });
        ajax.set("id", $("#id").val());
        ajax.start();
    }
    Feng.confirm("请确认基础信息已核对无误，相应附件已上传，一旦提交，无法修改", operation);
}

/**
 * 设置不可修改的字段
 */
LivingAllowanceInfoInfoDlg.setNoChangeField = function () {
    var checkState = $("#checkState").val();
    var fields = $("#fields").val();
    if (checkState == 10) {
        // $("input,textarea").each(function () {
        //     $(this).attr("readonly", "readonly");
        // });
        $("select,input,textarea").not(":file,:hidden").each(function () {
            $(this).attr("disabled", "disabled");
        });
        if (Feng.isNotEmptyStr(fields)) {
            var arr = fields.split(",");
            for (var key in arr) {
                var name = $("#" + arr[key]).prop("tagName");
                if (name == 'select' || name == 'SELECT') {
                    $("#" + arr[key]).removeAttr("disabled");
                }
                if (name == "input" || name == 'textarea' || name == "INPUT" || name == 'TEXTAREA') {
                    $("#" + arr[key]).removeAttr("disabled");
                }
            }
            LivingAllowanceInfoInfoDlg.tax.update({disabled: fields.indexOf("personalTax") == -1});
            LivingAllowanceInfoInfoDlg.socialSecurity.update({disabled: fields.indexOf("socialSecurity") == -1});
        }
    }
}


/**
 * 数据加载
 * */
/**
 * 加载市
 */
LivingAllowanceInfoInfoDlg.afterSelectProvince = function () {
    var province = $("#provinceCode").val();
    $("#cityCode").empty();
    $("#countyCode").empty();
    if (province == null || province == '') {
        return;
    }
    Feng.addAjaxSelect({
        "id": "cityCode",
        "displayCode": "code",
        "displayName": "name",
        "type": "GET",
        "url": Feng.ctxPath + "/common/tool/findCityByProvinceSelect/code/" + province
    });
}

LivingAllowanceInfoInfoDlg.introductionMethodChange = function () {
    var introductionMethod = $("#introductionMethod").val();
    if (Feng.isEmptyStr(introductionMethod)) {
        $("#backJJBusinessTime,#firstInJJTime").val("");
        $("#backJJBusinessTimeDiv,#firstInJJTimeDiv").css("display", "none");
        return;
    }
    if (introductionMethod == 1) {
        $("#backJJBusinessTime").val("");
        $("#backJJBusinessTimeDiv").css("display", "none");
        $("#firstInJJTimeDiv").css("display", "block");
        return;
    }
    $("#firstInJJTime").val("");
    $("#firstInJJTimeDiv").css("display", "none");
    $("#backJJBusinessTimeDiv").css("display", "block");
}

/**
 * 加载县
 */
LivingAllowanceInfoInfoDlg.afterSelectCity = function () {
    var city = $("#cityCode").val();
    $("#countyCode").empty();
    if (city == null || city == '') {
        return;
    }
    Feng.addAjaxSelect({
        "id": "countyCode",
        "displayCode": "code",
        "displayName": "name",
        "type": "GET",
        "url": Feng.ctxPath + "/common/tool/findCountyByCitySelect/code/" + city
    });
}

//校验是否保存基础信息
LivingAllowanceInfoInfoDlg.validId = function () {
    var id = $("#id").val();
    if (id != null && id != '') {
        $("#fileLi").removeAttr("style");
    } else {
        $("#fileLi").attr("style", "pointer-events: none");
    }
}

LivingAllowanceInfoInfoDlg.initTaxAndSocialSecurity = function () {
    var year = $("#year").val().substr(0, 4);
    var nowYear = new Date().getFullYear();
    var nowMonth = new Date().getMonth() + 1;
    let maxMonth = 12;
    if (year == nowYear) {
        maxMonth = nowMonth;
    }
    var startYear = year-1;
    var data = new Array();
    for (var j = 1;j<= 12; j++){
        var month = startYear + "-" + (j < 10 ? "0" + j : j);
        data.push({name: month, value: month, selected: false, disabled: false});
    }
    for (var i = 1; i <= maxMonth; i++) {
        var month = year + "-" + (i < 10 ? "0" + i : i);
        data.push({name: month, value: month, selected: false, disabled: false});
    }
    LivingAllowanceInfoInfoDlg.tax = xmSelect.render({
        el: '#personalTax',
        data: data
    })
    LivingAllowanceInfoInfoDlg.socialSecurity = xmSelect.render({
        el: '#socialSecurity',
        data: data
    })
}


function validUploadButton(type, row, fileId) {
    var files = $("#files").val();
    var checkState = $("#checkState").val();
    if ((Feng.isEmptyStr(checkState) || checkState == 1 || (checkState == 10 && files.indexOf(row.id) != -1)) && $("#hand").val() != "select") {
        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_master_living_allowance + "')\" class=\"btn btn-xs btn-danger\">" +
                "<i class=\"fa fa-times\"></i>删除" +
                "</button>";
    } else {
        return "";
    }
}

/**
 * 校验是否可以操作
 */
function validateIsEdit() {
    var checkState = $("#checkState").val();
    if (checkState != 1 && checkState != 5 && checkState != 10) {
        if (checkState == -1) {
            Feng.error("您的申报审核不通过，无法再修改");
            return false;
        } else if (checkState >= 35) {
            Feng.error("您的申报已审核通过，无法再修改");
            return false;
        } else {
            Feng.error("您的申报正在审核中，请耐心等待");
            return false;
        }
    }
    return true;
}

$(function () {
    Feng.initValidatorTip("talentInfoForm", LivingAllowanceInfoInfoDlg.validateFields);
    var id = $("#id").val();
    var industry_field_type = $("#industry_field_type").val();
    if ($("#industryFieldNew").attr("value") == "") {
        industry_field_type = "un_industryField";//兼容查看旧申报时候，没有产业信息，就显示旧的行业领域信息
    }
    //批量加载字典表数据
    var arr = [
        {"name": "nation", "code": "nation"},
        {"name": "nationality", "code": "nationality"},
        {"name": "politics", "code": "politics"},
        {"name": "declareType", "code": "un_master_education"},
        {"name": "highEducation", "code": "highest_degree"},
        {"name": "introductionMode", "code": "un_introduction_mode"},
        {"name": "industryFieldNew", "code": "industry_field"},
        {"name": "industryField", "code": industry_field_type},
        {"name": "address", "code": "street"}];
    Feng.findChildDictBatch(JSON.stringify(arr))
    //加载省份
    Feng.addAjaxSelect({
        "id": "provinceCode",
        "displayCode": "code",
        "displayName": "name",
        "type": "GET",
        "url": Feng.ctxPath + "/common/tool/getProvinceSelect"
    });
    LivingAllowanceInfoInfoDlg.initTaxAndSocialSecurity();
    LivingAllowanceInfoInfoDlg.setNoChangeField();
    //批量加载时间控件
    $(".date").each(function () {
        laydate.render({
            elem: this
            , type: 'date'
            , trigger: 'click'
        });
    });
    if (id != null && id != '') {
        //select初始化
        $("select").each(function () {
            $(this).val($(this).attr("value")).trigger("change");
        });
        if (Feng.isNotEmptyStr($("#personalTax").attr("value"))) {
            LivingAllowanceInfoInfoDlg.tax.setValue($("#personalTax").attr("value").split(","));
        }
        if (Feng.isNotEmptyStr($("#socialSecurity").attr("value"))) {
            LivingAllowanceInfoInfoDlg.socialSecurity.setValue($("#socialSecurity").attr("value").split(","));
        }
        Feng.getCheckLog("logTable", {
            "type": CONFIG.project_master_living_allowance,
            "mainId": id,
            "typeFileId": "",
            "active": 1
        })
    }
    $("#address").val($("#address").attr("value"));
    $("#industryFieldNew").val($("#industryFieldNew").attr("value"))
    $("#industryField").val($("#industryField").attr("value"));
    ;
    $("#provinceCode").val($("#provinceCode").attr("value"));
    LivingAllowanceInfoInfoDlg.afterSelectProvince();
    $("#cityCode").val($("#cityCode").attr("value"));
    LivingAllowanceInfoInfoDlg.afterSelectCity();
    $("#countyCode").val($("#countyCode").attr("value"));
    LivingAllowanceInfoInfoDlg.validId();
    $("#photo").change(function (e) {
        var tag = e.target;
        var file = tag.files[0];
        var imgSrc;
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function () {
            imgSrc = this.result;
            $("#photoImg").attr("src", imgSrc);
        };
    });
});
