/**
 *
 * @author BOGON
 * @version 1.0
 */

var page = {
    initOrderFileTb: function () {
        var toolbar = toolbar = [/*{
            text: BJGL.BJGL__SC, iconCls: 'icon-add', hidden: true, handler: function () {
                $("#fileUpload").find('.filebox-label').click();
            }
        }, "-",*/ {
            text: BJGL.BJGL__SHANC, iconCls: 'icon-remove', handler: function () {
                var rows = $("#file_table").datagrid("getChecked");
                const ids = rows.map(obj => obj.id).join(',');
                topWin.layer.prompt({
                    formType: 2, value: '', title: '请输入备注',
                }, function (value, index, elem) {
                    $.ajax({
                        type: 'post', url: g.ctx + 'pc/order/purchaseOrder/rest/removeAttachment', data: {
                            ids: ids, remark: value
                        }, async: false, success: function (va) {
                            $("#file_table").datagrid('reload');
                            topWin.layer.close(index);
                        }, error: function (data) {
                            topWin.layer.close(index);
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                });
            }
        }];
        if (!isSupplier) {
            toolbar.push({
                text: "设置备注", iconCls: 'icon-remove', handler: function () {
                    var rows = $("#file_table").datagrid("getChecked");
                    const ids = rows.map(obj => obj.id).join(',');
                    topWin.layer.prompt({
                        formType: 2, value: '', title: '请输入备注',
                    }, function (value, index, elem) {
                        $.ajax({
                            type: 'post', url: g.ctx + 'pc/order/purchaseOrder/rest/submitRemark', data: {
                                ids: ids, remark: value
                            }, async: false, success: function (va) {
                                $("#file_table").datagrid('reload');
                                topWin.layer.close(index);
                            }, error: function (data) {
                                topWin.layer.close(index);
                                topWin.layer.alert(data.responseJSON.message, {icon: 2});
                            }
                        });
                    });
                }
            })
        }
        if (batchFlag && !isSupplier) {
            toolbar.push({
                // text: "一键下载", iconCls: 'icon-download', handler: function () {
                //     let rows = $("#file_table").datagrid("getRows");
                //     debugger;
                //     $.each(rows, function (idx, itm) {
                //         if (itm.deleteFlag != 1) {
                //             window.open(g.ctx + 'pc/sys/file/rest/download/' + itm.fileId);
                //         }
                //     })
                // }

                text: "一键下载", iconCls: 'icon-download', handler: function () {
                let rows = $("#file_table").datagrid("getRows");

                // 过滤掉删除标记的
                let fileIds = rows
                    .filter(r => r.deleteFlag != 1 && r.fileId)
                    .map(r => r.fileId);

                if (!fileIds.length) {
                    topWin.layer.alert("没有可下载的附件", {icon: 0});
                    return;
                }

                // 方式1：直接跳转下载（最简单）
                // 后端提供：/pc/sys/file/rest/downloadBatch?ids=1,2,3
                window.location.href = g.ctx + "pc/sys/file/rest/downloadBatch?ids=" + fileIds.join(",");
            }
        })
        }
        var url = g.ctx + 'pc/order/purchaseOrder/rest/attachmentList?ids=' + ids;
        // 加载附件列表
        $("#file_table").datagrid({
            url: url,
            height: document.documentElement.clientHeight - 50,
            method: "GET",
            width: gridwidth,
            singleSelect: true,
            pagination: false,
            autoHeight: true,
            loadMsg: ALLCOMMON.LOADING,
            rownumbers: true,
            fitColumns: false,
            nowrap: true,
            remoteSort: true,
            striped: true,
            columns: [[{
                field: 'ck', checkbox: true
            }, {
                field: 'fileName', title: BJGL.BJGL__FJM, width: '40%'
            }, {
                field: 'deleteFlag', title: "删除标记", width: '10%', formatter: function (value) {
                    if (value === 1) {
                        return "是"
                    }
                    return "否"
                }
            }, {
                field: 'createTime', title: "上传时间", width: '17%'
            } ,
                {
                    field: 'createUserName', title: "上传人姓名", width: '10%'
                } ,
                {
                    field: 'deleteTime', title: "删除时间", width: '17%'
                } ,
                {
                    field: 'deleteUserName', title: "删除人姓名", width: '10%'
                },
                {
                field: 'remark', title: "备注", width: '20%'
            }, {
                field: 'fileId', title: BJGL.BJGL__XZ, width: '15%', formatter: function (value, row, index) {
                    return '<a href="#" onclick="previewFileForm(undefined,\'' + row.fileName + '\',\'' + row.fileId + '\')">预览</a>'
                }
            }]],
            toolbar: toolbar
        });
    }, uploadOrderFile: function () {
        var addFiles = [];
        var files = $("#fileInput").filebox('files'), formData = new FormData()
        for (var r = 0; r < files.length; r++) {
            addFiles.push(files[r]);
        }
        for (var n = 0; n < addFiles.length; n++) {
            formData.append('files', addFiles[n]);
        }
        if (addFiles.length > 0) {
            fileUploadAjaxWithCall(formData, function (rows) {
                const postData = []
                $.each(ids.split(","),function (iid,iit){
                    $.each(rows, function (idx, itm) {
                        postData.push({
                            fileId: itm.id, masterId: iit
                        })
                    })
                })

                $.ajax({
                    url: g.ctx + 'pc/order/purchaseOrder/rest/saveAttachment',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(postData),
                    success: function () {
                        topWin.layer.msg('保存成功', {icon: 1});
                        $("#file_table").datagrid('reload');
                    },
                    error: function (data) {
                        topWin.layer.alert(data.responseJSON.message, {icon: 2});
                    }
                });
            }, true)
            $("#fileInput").filebox('clear')
        }
    }
}
$(function () {
    $('#attachmentType').combobox('setValue', '0');
    page.initOrderFileTb()
})

function confirm(call) {
    var attachmentType =  $('#attachmentType').val();
    if(!isSupplier && batchFlag == 1){
        if(!attachmentType){
            topWin.layer.alert('请选择附件类型', {icon: 0});
            return false;
        }
    }
    var param = {
        attachmentType : attachmentType
    }
    call(param);
}
