/**
 * 初始化认定条件管理详情对话框
 */
var IdentifyConditionInfoDlg = {
    identifyConditionInfoData: {},
    validateFields: {
        talentLevel: {
            validators: {
                notEmpty: {
                    message: '人才层次不能为空'
                }
            }
        },
        type: {
            validators: {
                notEmpty: {
                    message: '人才类别不能为空'
                }
            }
        },
        name: {
            validators: {
                notEmpty: {
                    message: '名称不能为空'
                }
            }
        },
        active: {
            validators: {
                notEmpty: {
                    message: '启用状态不能为空'
                }
            }
        }
    }
};

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

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

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

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

/**
 * 收集数据
 */
IdentifyConditionInfoDlg.collectData = function () {
    this
            .set('id')
            .set('type')
            .set('talentLevel')
            .set('talentLevelCat')
            .set('name')
            .set('active')
            .set('description')
            .set('isSalary');
    var companys = $("#companyIds").val();
    var bindFileTypes = $("#bindFileTypes").val();
    var company_ids = "", bind_fts_ids = "";
    for (var key in companys) {
        if (Feng.isNotEmptyStr(companys[key])) {
            company_ids = company_ids + companys[key] + ",";
        }
    }
    if (Feng.isNotEmptyStr(company_ids)) {
        company_ids = company_ids.substring(0, company_ids.length - 1);
    }
    for (var key in bindFileTypes) {
        if (Feng.isNotEmptyStr(bindFileTypes[key])) {
            bind_fts_ids = bind_fts_ids + bindFileTypes[key] + ",";
        }
    }
    if (Feng.isNotEmptyStr(bind_fts_ids)) {
        bind_fts_ids = bind_fts_ids.substring(0, bind_fts_ids.length - 1);
    }
    this.identifyConditionInfoData['companyIds'] = company_ids;
    this.identifyConditionInfoData['bindFileTypes'] = bind_fts_ids;

    var chks = $("#relationTable input[type=checkbox]:checked");
    var relation = {};
    for (var i = 0; i < chks.length; i++) {
        var companyId = $(chks[i]).data("company-id");
        if (typeof relation[companyId] == "undefined") {
            relation[companyId] = $(chks[i]).val();
        } else {
            relation[companyId] += "," + $(chks[i]).val();
        }
    }
    this.identifyConditionInfoData['relation'] = relation;
}

IdentifyConditionInfoDlg.otherValid = function () {
    if (this.identifyConditionInfoData.companyIds == '') {
        Feng.error("请选择审核单位");
        return false;
    }
    if (this.identifyConditionInfoData.bindFileTypes == '') {
        Feng.error("请选择审核附件");
        return false;
    }

    var companyIds = this.identifyConditionInfoData.companyIds.split(",");
    var total = companyIds.length;
    var _goal = 0;
    for (var i = 0; i < total; i++) {
        var companyId = companyIds[i];
        _goal += $("input[type=checkbox][data-company-id='" + companyId + "']:checked").length > 0 ? 1 : 0;
    }
    if (_goal != total) {
        Feng.error("存在审核单位没有成功关联附件");
        return false;
    }

    var fileTypes = this.identifyConditionInfoData.bindFileTypes.split(",");
    total = fileTypes.length;
    _goal = 0;
    for (var i = 0; i < total; i++) {
        var typeId = fileTypes[i];
        _goal += $("input[type=checkbox][value='" + typeId + "']:checked").length > 0 ? 1 : 0;
    }
    if (_goal != total) {
        Feng.error("选择了审核单位及审核附件后，每个附件必须与其中一个审核单位关联");
        return false;
    }
    return true;
}

/**
 * 提交添加
 */
IdentifyConditionInfoDlg.addSubmit = function () {
    this.clearData();
    this.collectData();
    if (!this.validate() || !IdentifyConditionInfoDlg.otherValid()) {
        return;
    }

    var ajax = new $ax("/admin/talent_condition/add", function (data) {
        if (data.code == "200") {
            Feng.success(data.msg);
            window.parent.IdentifyCondition.table.refresh();
            IdentifyConditionInfoDlg.close();
        } else {
            Feng.error(data.msg);
        }
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.identifyConditionInfoData);
    ajax.start();
}

/**
 * 提交修改
 */
IdentifyConditionInfoDlg.editSubmit = function () {
    this.clearData();
    this.collectData();
    if (!this.validate() || !IdentifyConditionInfoDlg.otherValid()) {
        return;
    }
    var ajax = new $ax(Feng.ctxPath + "/admin/talent_condition/edit", function (data) {
        if (data.code == "200") {
            Feng.success(data.msg);
            window.parent.IdentifyCondition.table.refresh();
            IdentifyConditionInfoDlg.close();
        } else {
            Feng.error(data.msg);
        }
    }, function (data) {
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.identifyConditionInfoData);
    ajax.start();
}
IdentifyConditionInfoDlg.onTypeChange = function () {
    var type = $("#type").val();
    Feng.addAjaxSelect({
        "id": "bindFileTypes",
        "displayCode": "id",
        "displayName": "name",
        "type": "GET",
        "url": Feng.ctxPath + "/common/api/getConditionFileTypesByType/type/" + type
    });
    $("#bindFileTypes").trigger("chosen:updated");
}
IdentifyConditionInfoDlg.onLayerChange = function () {
    var lv = $("#talentLevel").val();
    Feng.addAjaxSelect({
        "id": "talentLevelCat",
        "displayCode": "code",
        "displayName": "name",
        "type": "GET",
        "url": Feng.ctxPath + "/common/api/getLayerCatsByLayer/level/" + lv
    });
}

IdentifyConditionInfoDlg.onCompanyOrTypeChange = function () {
    var companyIds = $("#companyIds").val();
    var bindFileTypes = $("#bindFileTypes").val();
    IdentifyConditionInfoDlg.buildRelationTable(companyIds, bindFileTypes);
}

IdentifyConditionInfoDlg.fstLoad = true;
IdentifyConditionInfoDlg.buildRelationTable = function (companyIds, bindFileTypes) {
    var companyWithFileType = $("#companyWithFileType").val();
    var setting = [];
    if (companyWithFileType) {
        var companyTmps = companyWithFileType.split(";")
        for (var i in companyTmps) {
            var _companyTmp = companyTmps[i].split(":");
            var _companyId = _companyTmp[0];
            var _fileTypes = _companyTmp[1].split(",");
            setting[_companyId] = _fileTypes;
        }
    }
    var trs = $("#relationTable tbody").find("tr");
    trs.each(function (index, tr) {
        if (!companyIds || companyIds.indexOf($(tr).data("id").toString()) == -1)
            $(tr).remove();
    })
    for (let i in companyIds) {
        let companyId = companyIds[i];
        if (companyId == "")
            continue;
        var cfg = setting[companyId];
        if ($("#relationTable tbody").find("tr[data-id='" + companyId + "']").length > 0) {
            var chks = $("#relationTable tbody").find("tr[data-id='" + companyId + "']").find("input[type=checkbox]");
            chks.each(function (index, chk) {
                if (!bindFileTypes || bindFileTypes.indexOf($(chk).val().toString()) == -1)
                    $(chk).parents("li").remove();
            })
            for (let n in bindFileTypes) {
                let fileType = bindFileTypes[n];
                if ($("#relationTable tbody").find("tr[data-id='" + companyId + "']").find("input[value='" + fileType + "']").length == 0) {
                    let typename = $("#bindFileTypes option[value='" + fileType + "']").text();
                    let disabled = $("input[type=checkbox][value='" + fileType + "']:checked").length > 0 ? "disabled" : "";
                    let li = '<li><label for="relation[' + companyId + ']">' + typename + '</label><input type="checkbox" data-company-id="' + companyId + '" value="' + fileType + '" ' + disabled + ' onchange="IdentifyConditionInfoDlg.onCheckChange(this);"></li>';
                    $("#relationTable tbody").find("tr[data-id='" + companyId + "'] ul").append(li);
                }
            }
        } else {
            let newTr = "";
            let companyName = $("#companyIds option[value='" + companyId + "']").text();
            newTr = '<tr data-id="' + companyId + '"><td style="width:10%;" class="word-wrap">' + companyName + '</td><td style="width:90%"><ul>';
            for (let n in bindFileTypes) {
                let fileType = bindFileTypes[n];
                let typename = $("#bindFileTypes option[value='" + fileType + "']").text();

                var checked = "";
                if (typeof cfg != "undefined" && cfg.indexOf(fileType) > -1 && $("input[type=checkbox][value='" + fileType + "']:checked").length == 0)
                    checked = "checked";
                if (IdentifyConditionInfoDlg.fstLoad && checked == "checked") {
                    $("input[type=checkbox][value='" + fileType + "']").prop("disabled", true);
                }
                let disabled = $("input[type=checkbox][value='" + fileType + "']:checked").length > 0 ? "disabled" : "";
                newTr += '<li class="word-wrap"><label for="relation[' + companyId + ']">' + typename + '</label><input type="checkbox" data-company-id="' + companyId + '" value="' + fileType + '" ' + checked + " " + disabled + ' onchange="IdentifyConditionInfoDlg.onCheckChange(this);"></li>';
            }
            newTr += '</ul></td></tr>'
            $("#relationTable tbody").append(newTr);
        }
    }
    IdentifyConditionInfoDlg.fstLoad = false;
}
IdentifyConditionInfoDlg.onCheckChange = function (chk) {
    var typeId = $(chk).val();
    if ($(chk).is(":checked")) {
        $("input[type=checkbox][value='" + typeId + "']").prop("disabled", true);
        $(chk).removeAttr("disabled");
    } else {
        $("input[type=checkbox][value='" + typeId + "']").removeAttr("disabled");
    }
}

/**
 * 验证数据是否为空
 */
IdentifyConditionInfoDlg.validate = function () {
    $('#identifyConditionInfoForm').data("bootstrapValidator").resetForm();
    $('#identifyConditionInfoForm').bootstrapValidator('validate');
    return $("#identifyConditionInfoForm").data('bootstrapValidator').isValid();
}

$(function () {
    Feng.initValidator("identifyConditionInfoForm", IdentifyConditionInfoDlg.validateFields);
    var arr = [{
            "name": "talentLevel",
            "code": "talent_arrange"
        }];
    Feng.findChildDictBatch(JSON.stringify(arr));
    Feng.addAjaxSelect({
        "id": "companyIds",
        "displayCode": "id",
        "displayName": "name",
        "type": "GET",
        "url": Feng.ctxPath + "/common/api/getCompanyKvs"
    });
    $('#companyIds').chosen({
        search_contains: true,
        disable_search: false,
        width: "100%",
        enable_split_word_search: true
    });
    $('#bindFileTypes').chosen({
        search_contains: true,
        disable_search: false,
        width: "100%",
        enable_split_word_search: true
    });
    //下拉框数据回显
    $("select").each(function () {
        $(this).val($(this).attr("selectVal"));
    });
    var lv = $("#talentLevel").val();
    if (lv > 0) {
        IdentifyConditionInfoDlg.onLayerChange();
        $("#talentLevelCat").val($("#talentLevelCat").attr("selectVal"));
    }
    var companyIds = $("#companyIds").attr("selectVal");
    if (Feng.isNotEmptyStr(companyIds)) {
        $("#companyIds").val(companyIds.split(",")).trigger("chosen:updated");
    }
    var type = $("#type").val();
    if (type > 0) {
        IdentifyConditionInfoDlg.onTypeChange();
    }
    var bindFileTypes = $("#bindFileTypes").attr("selectVal");
    if (Feng.isNotEmptyStr(bindFileTypes)) {
        $("#bindFileTypes").val(bindFileTypes.split(",")).trigger("chosen:updated");
    }
    IdentifyConditionInfoDlg.onCompanyOrTypeChange();
});
