/**
 * 初始化人才认定申报详情对话框
 */
var locked = false;
var IntegralInfoDlg = {
    integralInfoData: {}
};

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

/**
 * 初始化表格的列
 */
IntegralInfoDlg.initFileTypeColumn = function () {
    return [
        {field: 'selectItem', checkbox: false, visible: false},
        {title: '附件列表（带*号的附件必需上传）', field: 'name', visible: true, align: 'left', valign: 'middle', width: "100%", 'class': 'uitd_showTip',
            formatter: function (value, row, index) {
                if (row.id != 0) {
                    return '<span style="color:#000000;font-weight:bold;">申报"' + value + '"积分项目需要上传以下附件</span>';
                }
                return '<span style="color:#000000;font-weight:bold;">公共附件</span>';
            }
        },
        {title: '模板', field: 'templateUrl', visible: true, align: 'center', valign: 'middle', width: "8%"},
        {title: '操作', field: 'id', visible: true, align: 'center', valign: 'middle', width: "10%"}
    ]
};
IntegralInfoDlg.changeAndLoadFile = function () {
    var table = $(".fileTable");
    var items = $("select[name='item_id[]']");
    var item_id = [];
    for (var i = 0; i < items.length; i++) {
        let _id = items.eq(i).val();
        if (_id) {
            item_id.push(_id);
        }
    }
    if (item_id.length == 0) {
        //table.bootstrapTable("destroy");
        //return;
    }
    var ajax = new $ax("/common/api/findCommonFileType", function (data) {
        if (data == null || data.length == 0) {
            return;
        }
        table.bootstrapTable("destroy");
        table.bootstrapTable({
            columns: IntegralInfoDlg.initFileTypeColumn(),
            data: data.rows,
            showHeader: true,
            rowStyle: function (row, index) {
                return {classes: ""};
            },
            onPostBody: function (data) {

                for (var i in data) {
                    var fileTypes = data[i].fileTypes;
                    for (var k in fileTypes) {
                        var fileType = fileTypes[k];
                        /**-- 构造附件类型标题栏  --**/

                        let name = '<div class="word-wrap">';
                        if (fileType.must == 1) {
                            name = name + '<i class="fa fa-paste"></i><span style="font-weight:bold;color:red;font-size:14px;font-family:宋体"> * </span> ' + fileType.name;
                        }
                        if (fileType.must == 2) {
                            name = name + '<i class="fa fa-paste"></i>' + fileType.name;
                        }
                        name = name + '<br />' + fileType.description + '</div>'

                        var template = "";
                        if (fileType.templateUrl == null || fileType.templateUrl == '' || fileType.templateUrl == 'null') {
                            template = '无';
                        } else {
                            template = "<button type='button' onclick=\"IntegralInfoDlg.downloadFile('" + fileType.id + "',3)\" style='margin-right: 10px' class=\"btn btn-xs btn-primary\">" +
                                    "<i class=\"fa fa-download\"></i>下载" +
                                    "</button>";
                        }
                        var uploadBtn = IntegralInfoDlg.validUploadButton(1, fileType.id, '', data[i].id);

                        var tr = '<tr class="subTitleLine"><td class="uitd_showTip" style="text-align: left; vertical-align: middle; width: 82%; ">'
                                + name +
                                '</td>\n\
                                \n\
                                <td style="text-align: center; vertical-align: middle; width: 8%; ">' + template +
                                '</td>\n\
                                <td style="text-align: center; vertical-align: middle; width: 10%; ">' + uploadBtn +
                                '</td></tr>';

                        /**-- --**/
                        var typeId = fileType.id;
                        var files = fileType.files;
                        var html = '<ul class="imgs"><li style="width: 70%;font-weight: bold;padding-top: 5px;">附件原名</li><li style="width: 10%;font-weight: bold;padding-top: 5px;">预览</li><li style="width: 20%;font-weight: bold;padding-top: 5px;">操作</li>';
                        for (var key in files) {
                            var btn = "";
                            btn = IntegralInfoDlg.validUploadButton(2, typeId, files[key].id, files[key].relationId);
                            var sn = files[key].url.lastIndexOf(".");
                            var suffix = files[key].ext; //files[key].url.substring(sn + 1, files[key].url.length);
                            var imgStr = "";
                            if (suffix == "pdf" || suffix == "PDF") {
                                imgStr = "<button type='button'  onclick=\"Feng.showPdf('" + files[key].url + "','" + files[key].id + "','" + files[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 == 'doc' || suffix == 'DOCX' || suffix == 'DOC') {
                                imgStr = "<button type='button'  onclick=\"Feng.showExcel('" + files[key].url + "','" + files[key].id + "','" + files[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\" onclick=\"Feng.showImg(this)\" src=\"' + files[key].url + '\" style=\"width:25px;height:25px;\">';
                            }

                            html += '<li data-id="' + files[key].id + '">\n\
                                    <div><input type="hidden" name="uploadFiles[]" value="' + files[key].id + '"></div>\n' +
                                    '<div style="width: 70%;">' + files[key].orignName + '</div>\n' +
                                    '<div style="width: 10%;">' + imgStr + '</div>\n' +
                                    '<div style="width: 20%;">' + btn + '</div>\n\
                                    </li>';
                        }
                        html = html + '</ul>';
                        table.find("tr[data-index='" + i + "'] td").eq(0).attr("colspan", 3);
                        table.find("tr[data-index='" + i + "'] td").eq(1).remove();
                        table.find("tr[data-index='" + i + "'] td").eq(2).remove();
                        table.find("tr[data-index='" + i + "']").after(tr);
                        table.find("tr[data-index='" + i + "']").next(".subTitleLine").after('<tr class="detail-view"><td colspan="5">' + html + '</td></tr>');
                    }
                }
                $("td.uitd_showTip").bind("mouseover", function () {
                    var htm = $(this).html();
                    $(this).webuiPopover({title: '详情', content: htm, trigger: 'hover'}).webuiPopover('show');
                });
            },
        });
    }, function (data) {
        Feng.error("查询失败!" + data.responseJSON.message + "!");
    });
    var queryData = {};
    queryData["mainId"] = $("#id").val();
    queryData['project'] = CONFIG.project_integral_apply;
    queryData['type'] = $("#type").val();
    queryData["itemId"] = item_id;
    queryData['checkState'] = $("#checkState").val();
    ajax.set(queryData);
    ajax.start();
}

IntegralInfoDlg.onProjectTypeChange = function (obj) {
    var projectType = $(obj).val();
    var projectObj = $(obj).parents("table").find("select[name='projectId[]']")
    Feng.addAjaxSelect({
        "obj": projectObj,
        "displayCode": "id",
        "displayName": "name",
        "type": "GET",
        "url": "/common/api/getIntegralProjectsByType/projectType/" + projectType
    });
}
IntegralInfoDlg.onProjectChange = function (obj) {
    var projectId = $(obj).val();
    var itemObj = $(obj).parents("table").find("select[name='item_id[]']")
    Feng.addAjaxSelect({
        "obj": itemObj,
        "displayCode": "id",
        "displayName": "name",
        "bindData": "unit",
        "type": "GET",
        "url": "/common/api/getIntegralItemsByProject/projectId/" + projectId
    });
}
IntegralInfoDlg.onItemChange = function (obj) {
    var unit = $(obj).find("option:selected").data("unit");
    var parent = $(obj).parents("table");
    if (typeof unit != "undefined" && unit) {
        parent.find(".unit").html("（" + unit + "）");
    } else {
        parent.find(".unit").html("");
    }
    IntegralInfoDlg.changeAndLoadFile();
}

var currentTr = null;
//选择附件并显示附件名
IntegralInfoDlg.checkFile = function (content, fileTypeId, fileId, itemId) {
    var curTr = $(content).parents("tr");
    var index = curTr.index();
    if (curTr.hasClass("subTitleLine")) {
        index++;
    }
    currentTr = index;
    if (!IntegralInfoDlg.validateIsEdit())
        return;
    $("#upload_file").unbind("change");
    $("#upload_file").change(function () {
        if (!Feng.chkFileInvalid(this.files[0], 5, 10))
            return;
        IntegralInfoDlg.upload(fileTypeId, fileId, itemId);
    });
    $('#upload_file').val("");
    $('#upload_file').click();
}
//上传附件
IntegralInfoDlg.upload = function (fileTypeId, fileId, itemId) {
    var id = $("#id").val();
    if (!IntegralInfoDlg.validateIsEdit())
        return;
    if (fileId != null && fileId != 'null') {
        $("#fileId").val(fileId)
    } else {
        $("#fileId").val("");
    }
    $("#mainId").val(id);
    $("#fileTypeId").val(fileTypeId);
    var index = layer.load(0, {shade: false, time: 0});
    $("#index").val(index);
    $("#relationId").val(itemId);
    $("#pageToken").val($("input[name=__token__]").val());
    $("#uploadForm").submit();
}
//删除附件
IntegralInfoDlg.deleteFile = function (id, state) {
    if (!IntegralInfoDlg.validateIsEdit())
        return;
    var operation = function () {
        var ajax = new $ax(Feng.ctxPath + "/common/api/deleteFile", function (data) {
            if (data.code == 200) {
                Feng.success(data.msg);
                $("input[name='uploadFiles[]'][value='" + id + "']").parents("li").remove();
                //$("#fileTable").bootstrapTable("refresh", {});
            } else {
                Feng.error(data.msg);
            }
        }, function (data) {
            Feng.error("删除失败!" + data.responseJSON.message + "!");
        });
        ajax.set("id", id);
        ajax.set("type", 1);
        ajax.start();
    }
    Feng.confirm("删除后无法恢复，确认删除吗?", operation);
}


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

IntegralInfoDlg.downloadFile = function (id, type) {
    window.location.href = Feng.ctxPath + "/api/common/downloadFile?id=" + id + "&type=" + type;
}

//设置不可修改的字段
IntegralInfoDlg.setNoChangeField = function () {
    $("input,textarea").each(function () {
        $(this).attr("readonly", "readonly");
    });
    $("select,input[type=radio]").each(function () {
        $(this).attr("disabled", "disabled");
    });
}
$(function () {
    var id = $("#id").val();
    var checkState = $("#checkState").val();
    if (id != null && id != '') {
        //select初始化
        $("select").each(function () {
            $(this).val($(this).attr("value")).trigger("change");
        });
        Feng.getCheckLog("logTable", {"type": CONFIG.project_integral_apply, "mainId": id, "typeFileId": "", "active": 1})
    }
    $("#card_type").val($("#card_type").attr("value"));
    IntegralInfoDlg.setNoChangeField();
    IntegralInfoDlg.changeAndLoadFile();
});


