var locked = false;
var EpChangeEdit = {
    epChangeEditData: {},
    validateFields: {
        newName: {validators: {notEmpty: {message: '单位名称不能为空'}, regexp: {regexp: /^[\u4e00-\u9fa5]{1,100}$/, message: "单位名称只允许中文"}}},
        newAddress: {validators: {notEmpty: {message: '单位地址不能为空'}}},
        newStreet: {validators: {notEmpty: {message: '所属街道不能为空'}}},
        newAgentName: {validators: {notEmpty: {message: '人才联络员不能为空'}}},
        newEphone: {
            validators: {
                notEmpty: {
                    message: '单位电话不能为空'
                },
                regexp: {
                    regexp: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
                    message: "单位电话格式不正确"
                }
            }
        },
        newAgentPhone: {
            validators: {
                notEmpty: {
                    message: '人才联络员电话不能为空'
                },
                regexp: {
                    regexp: /((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/,
                    message: "人才联络员电话格式不正确"
                }
            }
        },
        newAgentEmail: {
            validators: {
                notEmpty: {
                    message: '电子邮箱不能为空'
                },
                emailAddress: {
                    message: "电子邮箱格式不正确"
                }
            }
        }
    }
};

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

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

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

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

/**
 * 收集数据
 */
EpChangeEdit.collectData = function () {
    this
            .set('id')
            .set('type')
            .set('newName')
            .set('newIdCard')
            .set('newEnterpriseTag')
            .set('newEnterpriseType')
            .set('newLegal')
            .set('newStreet')
            .set('newAddress')
            .set('newEphone')
            .set('newAgentName')
            .set('newAgentPhone')
            .set('newAgentEmail')
            .set('newIndustryFieldNew')
            .set('newIndustryFieldOld')
            .set('newBankCard')
            .set('newBank')
            .set('newBankNetwork')
            .set('enterprise_id');
}

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


EpChangeEdit.initFileTable = function () {
    $("#fileTable").bootstrapTable({
        url: Feng.ctxPath + "/common/api/listCurrencyFileType",
        method: 'POST',
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        search: false, // 是否显示表格搜索，此搜索是客户端搜索，不会进服务端
        showRefresh: false, // 是否显示刷新按钮
        clickToSelect: true, // 是否启用点击选中行
        singleSelect: true, // 设置True 将禁止多选
        striped: true, // 是否显示行间隔色
        escape: true,
        pagination: false, // 设置为 true 会在表格底部显示分页条
        paginationHAlign: "left",
        paginationDetailHAlign: "right",
        sidePagination: "server", // 设置在哪里进行分页，可选值为 'client' 或者 'server'
        showColumns: false,
        detailView: true, //是否显示父子表
        pageList: [10, 30, 50],
        queryParams: function (params) {
            return $.extend({"type": "governmentChange"}, params)
        },
        rowStyle: function (row, index) {
            return {classes: "info"};
        },
        columns: EpChangeEdit.initFileTypeColumn(),
        onPostBody: function () {
            $("td.uitd_showTip").bind("mouseover", function () {
                var htm = $(this).html();
                $(this).webuiPopover({title: '详情', content: htm, trigger: 'hover'}).webuiPopover('show');
            });
        },
        onLoadSuccess: function (data) {
            $("#fileTable").bootstrapTable('expandAllRows');
        },
        onExpandRow: function (index, row, $detail) {
            var ajax = new $ax(Feng.ctxPath + "/common/api/listTalentCommonFile", function (data) {
                if (data == null || data.length == 0) {
                    return;
                }
                var checkState = $("#checkState").length > 0 ? $("#checkState").val() : 1;
                var files = "";
                if (checkState != 1) {
                    files = $("#files").val().split(",");
                }
                var html = '<ul class="imgs"><li style="width: 80%;font-weight: bold;padding-top: 5px;">附件原名</li><li style="width: 10%;font-weight: bold;padding-top: 5px;">预览</li><li style="width: 10%;font-weight: bold;padding-top: 5px;">操作</li>';
                for (var key in data) {
                    var sn = data[key].url.lastIndexOf(".");
                    var suffix = data[key].ext;//data[key].url.substring(sn+1,data[key].url.length);
                    var imgStr = "";
                    if (suffix == "pdf" || suffix == "PDF") {
                        imgStr = "<button type='button'  onclick=\"Feng.showPdf('" + data[key].url + "','" + data[key].id + "','" + data[key].orignName + "')\" class=\"btn btn-xs btn-danger\"><i class=\"fa fa-file-pdf-o\" aria-hidden=\"true\"></i></button>";
                    } else if (suffix == "xlsx" || suffix == "XLSX" || suffix == 'xls' || suffix == 'XLS' || suffix == "DOCX" || suffix == "docx" || suffix == 'DOC' || suffix == 'doc') {
                        imgStr = "<button type='button'  onclick=\"Feng.showExcel('" + data[key].url + "','" + data[key].id + "','" + data[key].orignName + "')\" class=\"btn btn-xs btn-danger\"><i class=\"fa fa-file-excel-o\" aria-hidden=\"true\"></i></button>";
                    } else {
                        imgStr = '<img class=\"imgUrl\"  src=\"' + data[key].url + '\" style=\"width:25px;height:25px;\">';
                    }
                    var btn = "<button type=\'button\' onclick=\"EpChangeEdit.checkFile('" + row.id + "','" + data[key].id + "')\" style=\'margin-right: 10px\' class=\"btn btn-xs btn-info\"><i class=\"fa fa-paste\"></i>修改</button>" +
                            "<button type='button' onclick=\"EpChangeEdit.deleteFile('" + data[key].id + "')\" class=\"btn btn-xs btn-danger\"><i class=\"fa fa-times\"></i>删除</button>";
                    html = html + '<li style="display: none">' + data[key].id + '</li>\n' +
                            '<li style="width: 80%;padding-top: 5px;">' + data[key].orignName + '</li>\n' +
                            '<li style="width: 10%;">' + imgStr + '</li>\n' +
                            '<li style="width: 10%;padding-top: 2px;">' + (checkState == 1 ? btn : (files.indexOf(data[key].typeId.toString()) > -1 ? btn : "")) + '</li>';
                }
                html = html + '</ul>';
                $detail.html(html);
                $(".imgs").viewer({
                    // toolbar:false,
                    fullscreen: false
                });
            }, function (data) {
                Feng.error("查询失败!" + data.responseJSON.message + "!");
            });
            var queryData = {};
            queryData["mainId"] = $("#id").val();
            queryData["typeId"] = row.id;
            ajax.set(queryData);
            ajax.start();
        }
    });
}


EpChangeEdit.initFileTypeColumn = function () {
    return [
        {field: 'selectItem', checkbox: false, visible: false},
        {title: '名称', field: 'name', visible: true, align: 'center', valign: 'middle', width: "30%", 'class': 'uitd_showTip',
            formatter: function (value, row, index) {
                if (row.must == 1) {
                    return '<i class="fa fa-paste"></i><span style="font-weight:bold;color:red;font-size:14px;font-family:宋体"> * </span> ' + value;
                }
                if (row.must == 2) {
                    return '<i class="fa fa-paste"></i>' + value;
                }
            }
        },
        {title: '备注', field: 'description', visible: true, align: 'center', valign: 'middle', width: "52%", 'class': 'uitd_showTip',
            formatter: function (value, row, index) {
                return '<span style="color: red">' + value + '</span>';
            }
        },
        {title: '操作', field: 'id', visible: true, align: 'center', valign: 'middle', width: "10%",
            formatter: function (value, row, index) {
                var checkState = $("#checkState").length > 0 ? $("#checkState").val() : 1;
                if (checkState == 1) {
                    return "<button type='button' onclick=\"EpChangeEdit.checkFile('" + value + "','" + null + "')\" style='margin-right: 10px' class=\"btn btn-xs btn-info\">" +
                            "<i class=\"fa fa-upload\"></i>上传" +
                            "</button>";
                } else {
                    var files = $("#files").val().split(",");
                    if (files.indexOf(value.toString()) != -1) {
                        return "<button type='button' onclick=\"EpChangeEdit.checkFile('" + value + "','" + null + "')\" style='margin-right: 10px' class=\"btn btn-xs btn-info\">" +
                                "<i class=\"fa fa-upload\"></i>上传" +
                                "</button>";
                    } else {
                        return "";
                    }
                }
            }
        }
    ]
}

//选择附件并显示附件名
EpChangeEdit.checkFile = function (fileTypeId, fileId) {
    var checkState = $("#checkState").val();
    if (checkState == 2) {
        Feng.error("正在审核中，无法修改");
        return;
    }
    if (checkState == 4) {
        Feng.error("审核通过，无法修改");
        return;
    }
    $("#upload_file ").unbind("change");
    $("#upload_file ").change(function () {
        EpChangeEdit.upload(fileTypeId, fileId);
    });
    $('#upload_file').val("");
    $('#upload_file').click()
}
//上传附件
EpChangeEdit.upload = function (fileTypeId, fileId) {
    if (fileId != null && fileId != 'null') {
        $("#fileId").val(fileId)
    } else {
        $("#fileId").val("");
    }

    $("#mainId").val($("#id").val());
    $("#typeId").val(fileTypeId);
    var index = layer.load(0, {shade: false, time: 0});
    $("#index").val(index);
    $("#uploadForm").submit();
}
//删除附件
EpChangeEdit.deleteFile = function (id) {
    var checkState = $("#checkState").val();
    if (checkState == 2) {
        Feng.error("正在审核中，无法修改");
        return;
    }
    if (checkState == 4) {
        Feng.error("审核通过，无法删除");
        return;
    }
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/api/talentCommonFile/deleteTalentCommonFile", function (data) {
            if (data.code = 200) {
                Feng.success(data.msg);
                $("#fileTable").bootstrapTable("refresh", {});
            } else {
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("id", id);
        ajax.start();
    }
    Feng.confirm("删除后无法恢复，确认删除吗?", operation);
}


EpChangeEdit.addSubmit = function () {
    this.clearData();
    this.collectData();
    if (!this.validate()) {
        return;
    }
    var checkState = $("#checkState").val();
    if (checkState == 2 || checkState == 5) {
        Feng.info("正在审核中，无法修改")
        return;
    }
    if (checkState == 4) {
        Feng.info("已审核通过，无法修改")
        return;
    }
    // $(".layui-layer-btn0",parent.document).css("pointer-events","none");
    if (locked)
        return;
    locked = true;
    var ajax = new $ax(Feng.ctxPath + "/enterprise/api/upsert", function (data) {
        if (data.code == "200") {
            Feng.success(data.msg);
            $("#fileLi").removeAttr("style");
            $("#id").val(data.obj.id);
            $("#checkState").val(data.obj.checkState);
            window.parent.EnterpriseCenter.table.refresh();
        } else {
            Feng.info(data.msg);
        }
        //$(".layui-layer-btn0",parent.document).css("pointer-events","block");
        locked = false;
    }, function (data) {
        Feng.error("添加失败!" + data.responseJSON.msg + "!");
        locked = false;
    });
    ajax.set(this.epChangeEditData);
    ajax.start();
};


/**
 * 提交审核
 */
EpChangeEdit.submitToCheck = function () {
    var id = $("#id").val();
    if (id == null || id == "") {
        Feng.info("请先填写基础信息并上传附件");
        return;
    }
    var checkState = $("#checkState").val();
    if (checkState == 2 || checkState == 5) {
        Feng.error("正在审核中，无法修改");
        return;
    }
    if (checkState == 4) {
        Feng.error("审核通过，无法修改");
        return;
    }
    //$(".layui-layer-btn1",parent.document).css("pointer-events","none");
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/enterprise/api/submitToCheck", function (data) {
            //$(".layui-layer-btn1",parent.document).css("pointer-events","block");
            if (data.code == 200) {
                Feng.success(data.msg);
                window.parent.EnterpriseCenter.table.refresh();
                EpChangeEdit.close();
            } else {
                Feng.error(data.msg);
            }

        }, function (data) {
            //$(".layui-layer-btn1",parent.document).css("pointer-events","block");
            Feng.error("提交审核失败!" + data.responseJSON.message + "!");

        });
        ajax.set("id", id);
        ajax.start();
    }
    Feng.confirm("请确认基础信息已核对无误，相应附件已上传，一旦提交，无法修改", operation);
}


EpChangeEdit.callBack = function (data) {
    layer.close(data.obj);
    Feng.info(data.msg);
    if (data.code == 200) {
        $("#fileTable").bootstrapTable("refresh", {});
    }
};


EpChangeEdit.downloadFile = function (id) {
    window.location.href = Feng.ctxPath + '/enterprisechangeRecord/downloadFile?id=' + id;
};

EpChangeEdit.industryChange = function () {
    var industryNew = $("#newIndustryFieldNew").val();
    var arr = [{"name": "newIndustryFieldOld", "code": industryNew + "_field"}];
    Feng.findChildDictBatch(JSON.stringify(arr));
}

$(function () {
    Feng.initValidator("ecr_form", EpChangeEdit.validateFields);
    var industryNew = $("#newIndustryFieldNew").attr("value");
    var arr = [
        {"name": "newStreet", "code": "street"},
        {"name": "newEnterpriseTag", "code": "enterprise_tag"},
        {"name": "newEnterpriseType", "code": "enterprise_type"},
        {"name": "newIndustryFieldNew", "code": "industry_field"},
        {"name": "newIndustryFieldOld", "code": industryNew + "_field"}];
    Feng.findChildDictBatch(JSON.stringify(arr));
    $("select").each(function () {
        $(this).val($(this).attr("value"));
    })
    if ($("#type").val() == 1) {
        $("#newEnterpriseTag,#newIndustryFieldNew,#newIndustryFieldOld,#newEnterpriseType").parent().parent().attr("style", "display:block");
        $("#newEnterpriseTag").val($("#newEnterpriseTag").attr("value"));
        $("#newIndustryFieldNew").val($("#newIndustryFieldNew").attr("value"));
        $("#newIndustryFieldOld").val($("#newIndustryFieldOld").attr("value"));
    } else {
        $("#newEnterpriseTag,#newIndustryFieldNew,#newIndustryFieldOld,#newEnterpriseType").parent().parent().attr("style", "display:none");
        $("#newEnterpriseTag").val("");
        $("#newIndustryFieldNew").val("");
    }
    var id = $("#id").val();
    if (id != null && id != '') {
        $("#fileLi").removeAttr("style");
    } else {
        $("#fileLi").attr("style", "pointer-events: none");
    }
    var checkState = $("#checkState").length > 0 ? $("#checkState").val() : 1;
    if (checkState != 1) {
        $("#baseForm :input").prop("disabled", true);
        var fields = $("#fields").val().split(",");
        for (var i in fields) {
            $("#" + fields[i]).removeAttr("disabled");
        }
    }
});