/**
 *
 * @author BOGON
 * @version 1.0
 */
var el = {
    form: '#form',
    tb_item: '#tb-item',
    body: '#body',
    bodyHeight: document.documentElement.clientHeight

};
//选填的资质编号
var codes =
    ['SRM_ZZ_002', 'SRM_ZZ_001', 'SRM_ZZ_006', 'SRM_ZZ_035', 'SRM_ZZ_036', 'SRM_ZZ_037', 'SRM_ZZ_038', 'SRM_ZZ_004', 'SRM_ZZ_017', 'SRM_ZZ_016', 'SRM_ZZ_039']
//日期选填的
var codes1 =
    ['SRM_ZZ_026', 'SRM_ZZ_023', 'SRM_ZZ_022', 'SRM_ZZ_021', 'SRM_ZZ_024', 'SRM_ZZ_019', 'SRM_ZZ_030', 'SRM_ZZ_009', 'SRM_ZZ_032', 'SRM_ZZ_033', 'SRM_ZZ_020', 'SRM_ZZ_024', 'SRM_ZZ_034']
var editIndex = undefined
$(function () {
    if (type !== 0) {
        $(el.body).find('input').attr('readonly', true);
    }
    loadGridItem();
});
var submitFlag = 0

function loadGridItem() {
    if (type != 2 && type != 1) {
        var toor = [
            {
                text: '选择资质', id: 'btn_add', iconCls: 'icon-add',
                handler: function () {
                    var supplier_id = $("#supplierId").val();
                    if (!supplier_id || supplier_id === "") {
                        topWin.layer.msg(tipsi18n.qxzgys);
                        return;
                    }
                    let url = g.ctx + 'pc/supplier/supplierQualification/page/selector?supplierId=' + supplier_id;
                    var supplierQualificationSelectorDialog = openDialog('supplierQualificationSelectorDialog', url, {
                        title: "供应商资质选择",
                        width: '90%',
                        height: '70%',
                        cache: false,
                        modal: true,
                        border: false,
                        draggable: true,
                        shadow: false,
                        onClose: function () {
                            supplierQualificationSelectorDialog.dialog('destroy');
                        },
                        buttons: [{
                            text: itablei8n.confirm, handler: function () {
                                topWin.frames['supplierQualificationSelectorDialog'].page.getChecked(function (rows) {
                                    $.each(rows, function (idx, itm) {
                                        const row = {
                                            qualificationCode: itm.qualificationCode,
                                            qualificationName: itm.qualificationName,
                                            fileId: itm.fileId,
                                            fileName: itm.fileName,
                                            availableEndDate: itm.availableEndDate,
                                            availableStartDate: itm.availableStartDate
                                        }
                                        $(el.tb_item).datagrid("appendRow", row)
                                    })
                                    supplierQualificationSelectorDialog.dialog('close');
                                });
                            }
                        }, {
                            text: itablei8n.close, handler: function () {
                                supplierQualificationSelectorDialog.dialog('close');
                            }
                        }]
                    });
                }
            },
            "-",
            {
                text: '新增资质', id: 'btn_add', iconCls: 'icon-add',
                handler: function () {
                    var supplier_id = $("#supplierId").val();
                    if (!supplier_id || supplier_id === "") {
                        topWin.layer.msg(tipsi18n.qxzgys);
                        return;
                    }
                    const url = g.ctx + 'pc/supplier/qualification/index?selected=1'
                    const qualificationItemDialog = openDialog('qualificationItemDialog', url, {
                        title: '资质选择',
                        width: '90%',
                        height: '90%',
                        cache: false,
                        modal: true,
                        border: false,
                        draggable: true,
                        shadow: false,
                        onClose: function () {
                            qualificationItemDialog.dialog('destroy');
                        },
                        buttons: [{
                            text: itablei8n.confirm, handler: function () {
                                topWin.frames['qualificationItemDialog'].getChecked(function (rows) {
                                    const tableRows = $("#tb-item").datagrid("getRows")
                                    const map = {}
                                    $.each(tableRows, function (idx, itm) {
                                        map[itm.qualificationCode] = 1
                                    })
                                    $.each(rows, function (idx, itm) {
                                        let tmpRow = {
                                            qualificationId: itm.id,
                                            qualificationName: itm.name,
                                            qualificationCode: itm.code
                                        }
                                        if (map[itm.code] == undefined) {
                                            $("#tb-item").datagrid("appendRow", tmpRow)
                                        }
                                    })
                                    qualificationItemDialog.dialog('close');
                                });
                            }
                        }, {
                            text: itablei8n.close, handler: function () {
                                qualificationItemDialog.dialog('close');
                            }
                        }]
                    });
                }
            },
            "-",
            {
                text: '删除', id: 'btn_del', iconCls: 'icon-delete',
                handler: function () {
                    var tbItem = $(el.tb_item).datagrid('getSelected');
                    if (!tbItem) {
                        topWin.layer.msg('请选择一条数据哦!', {icon: 0});
                        return;
                    }
                    // 指定行索引
                    var rowIndex = $(el.tb_item).datagrid('getRowIndex', tbItem);

                    let qualificationId = tbItem.qualificationId;
                    console.log(qualificationId)
                    if (qualificationId !== '') {
                        topWin.layer.msg('此条资质信息不允许删除哦!!', {icon: 0});
                        return;
                    }
                    $(el.tb_item).datagrid('deleteRow', rowIndex);

                }
            },
        ];
    } else {
        var toor = [];
    }
    if (isSupplier === 1) {
        toor = []
    }
    var searchHeight = $(el.form).outerHeight() - 10;
    var options = {
        method: "GET",
        autoSave: true,
        url: g.ctx + 'pc/supplier/supplierQualification/rest/changeItemList?changeId=' + id,
        height: el.bodyHeight - searchHeight - 50,
        columns: [[
            {field: 'ck', checkbox: true},
            {
                field: 'qualificationCode', title: supplieri18n.zzbm,
                width: '160', align: 'left'
            },
            {
                field: 'qualificationName', title: supplieri18n.zzmc,
                width: '160', align: 'left',
                formatter: function (value, row) {
                    if (row.qualificationFileId !== '') {
                        //增加预览
                        return "<a href='" + g.ctx + "pc/sys/file/rest/download/" + row.qualificationFileId + "'>" + value + "</a>"
                            + '&nbsp;&nbsp;&nbsp;<a href="#" onclick="previewFileForm(undefined,\'' + value + '\',\'' + row.qualificationFileId + '\')">预览</a>'
                    }
                    return value;
                }
            },
            {
                field: 'fileName', title: supplieri18n.yzswj,
                width: '190', align: 'left',
                formatter: function (value, row) {
                    if (value) {
                        //增加预览
                        return "<a href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + value + "</a>"
                            + '&nbsp;&nbsp;&nbsp;<a href="#" onclick="previewFileForm(undefined,\'' + value + '\',\'' + row.fileId + '\')">预览</a>'
                    }
                    return ''
                }
            },
            {
                field: 'availableStartDate', title: supplieri18n.ysxrq,
                width: '80', align: 'left',
            },
            {
                field: 'availableEndDate', title: supplieri18n.ysixrq,
                width: '80', align: 'left',
            },
            {
                field: 'newFileId', title: '新证书文件(<span style=\'color: red;\'>*</span>必传)',
                width: '200', align: 'left',
                formatter: function (value, row, rowIndex) {
                    var html = ''
                    if (type !== 3 && type !== 1) {
                        if (codes.indexOf(row.qualificationCode) === -1) {
                            html += "<span style='color: red;'>*</span>"
                        }
                        html += "<a onclick='uploadFile(" + rowIndex + ")' " +
                            "style='margin-right: 10px;'>上传</a>";
                    }
                    if (value) {
                        let txt
                        if (row.newFileName.length > 10) {
                            txt = row.newFileName.substring(0, 10) + "..."
                        } else {
                            txt = row.newFileName
                        }
                        html += "<a href='" + g.ctx + "pc/sys/file/rest/download/" + value + "' title='" + row.newFileName + "'>" + txt + "</a>"
                            + '&nbsp;&nbsp;&nbsp;<a href="#" onclick="previewFileForm(undefined,\'' + row.newFileName + '\',\'' + value + '\')">预览</a>';
                    }
                    return html;
                }
            }, {
                field: 'newAvailableStartDate', title: supplieri18n.xsxrq,
                width: '160', align: 'left',
                editor: {
                    editable: false,
                    type: 'datebox',
                    options: {
                        editable: false,
                        parser: function (value) {
                            if (value) {
                                return new Date(value);
                            } else {
                                return new Date();
                            }
                        }
                    }
                },formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD");
                    }
                    return ''
                }
            },
            {
                field: 'newAvailableEndDate', title: supplieri18n.xsixrq,
                width: '160', align: 'left',
                editor: {
                    editable: false,
                    type: 'datebox',
                    options: {
                        editable: false,
                        parser: function (value) {
                            if (value) {
                                return new Date(value);
                            } else {
                                return new Date();
                            }
                        }
                    }
                },formatter: function (value) {
                    if (value) {
                        return moment(value).format("YYYY-MM-DD");
                    }
                    return ''
                }
            },
            {
                field: 'version', title: '版本号',
                width: '90', align: 'left'
            }
        ]],
        toolbar: toor,
        singleSelect: true,
        pagination: false,
        autoHeight: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        fitColumns: false,
        nowrap: true,
        remoteSort: true,
        striped: true,
        onEdit: function (index) {
            editIndex = index
        }
    };
    $(el.tb_item).edatagrid(options)

}

function supplierSelect() {
    var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?single=1", {
        title: "供应商选择",
        width: '650px',
        height: '80%',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            supplierDialogElement.dialog('destroy');
        },
        buttons: [{
            text: '选择', iconCls: 'icon-save', handler: function () {
                topWin.frames['supplierDialog'].chooseRow(function (data) {
                    $("#supplierId").val(data.id)
                    $("#supplierName").textbox('setValue', data.supplierName)
                    supplierDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                supplierDialogElement.dialog('close');
            }
        }]
    })
}

function submitForm(callback) {
    if (verification()) {
        if (submitFlag == 1) {
            return;
        }
        var formData = $(el.form).serializeJson();
        $("#tb-item").edatagrid("saveRow");
        var item = $("#tb-item").datagrid("getRows");
        formData.item = item;
        for (var i = 0; i < item.length; i++) {
            if (codes.indexOf(item[i].qualificationCode) == -1 && (item[i].newFileId == undefined || item[i].newFileId == "")) {
                topWin.layer.msg("请上传新" + item[i].qualificationName + "文件", {icon: 0})
                return
            }
            if (item[i].newFileId !== undefined && item[i].newFileId !== "") {
                if (codes1.indexOf(item[i].qualificationCode) === -1) {
                    if (item[i].newAvailableStartDate == undefined || item[i].newAvailableStartDate == "") {
                        topWin.layer.msg("请选择新" + item[i].qualificationName + "文件的新生效日期", {icon: 0})
                        return
                    }
                    if (item[i].newAvailableEndDate == undefined || item[i].newAvailableEndDate == "") {
                        topWin.layer.msg("请选择新" + item[i].qualificationName + "文件的新效日期", {icon: 0})
                        return
                    }
                }
            }
        }

        submitFlag = 1
        $.ajax({
            url: g.ctx + 'pc/supplier/supplierQualification/rest/changeSaveOrUpdate',
            method: "post",
            contentType: 'application/json',
            data: JSON.stringify(formData),
            complete: function () {
                submitFlag = 0
            },
            success: function (data) {
                topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    callback()
                });
            },
            error: function (data) {
                topWin.layer.msg(data.responseJSON.message, {icon: 2});
            }
        });
    }
}

function changeBusinessPass(callback) {
    var remark = getRemark();
    if (!remark) {
        topWin.layer.msg("请输入审批意见")
        return;
    }
    $("#tb-item").edatagrid("saveRow");
    var item = $("#tb-item").datagrid("getRows");
    for (var i = 0; i < item.length; i++) {
        if (codes.indexOf(item[i].qualificationCode) == -1 && (item[i].newFileId == undefined || item[i].newFileId == "")) {
            topWin.layer.msg("请上传新" + item[i].qualificationName + "文件", {icon: 0})
            return
        }
        if (item[i].newFileId !== undefined && item[i].newFileId !== "") {
            if (codes1.indexOf(item[i].qualificationCode) === -1) {
                if (item[i].newAvailableStartDate == undefined || item[i].newAvailableStartDate == "") {
                    topWin.layer.msg("请选择新" + item[i].qualificationName + "文件的新生效日期", {icon: 0})
                    return
                }
                if (item[i].newAvailableEndDate == undefined || item[i].newAvailableEndDate == "") {
                    topWin.layer.msg("请选择新" + item[i].qualificationName + "文件的新效日期", {icon: 0})
                    return
                }
            }
        }
    }
    submitFlag = 1
    $.ajax({
        url: g.ctx + "pc/supplier/supplierQualification/rest/changeBusinessPass",
        type: "POST",
        data: {
            id: id,
            rows: JSON.stringify(item),
            remark: remark
        },
        complete: function () {
            submitFlag = 0
        },
        success: function (data) {
            topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                topWin.layer.close(idx);
                callback()
            });
        },
        error: function (data) {
            topWin.layer.msg(data.responseJSON.message, {icon: 2});
        }
    });
}

function verification() {
    if (!$("#supplierId").val()) {
        topWin.layer.msg(tipsi18n.xzgys);
        return false;
    }
    var rows = $(el.tb_item).datagrid("getRows");
    if (rows.length <= 0) {
        topWin.layer.msg(tipsi18n.xzybgdzz);
        return false;
    }
    return true;
}


function uploadFile(rowIndex) {
    $("#tb-item").edatagrid("saveRow")
    tableSingleFileUpload("tb-item", "fileInput", "png", rowIndex, 'newFileId', 'newFileName')
}

function getRemark() {
    return $("#remark").val()
}

function getSqeRemark() {
    return $("#sqeRemark").val()
}