let el = {
    fileType: '#fileType'
}
$(function () {
    // 初始化附件类型下拉框
    $(el.fileType).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=businessFileType',
        panelHeight: 'auto',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '-- 请选择 --',
        editable: false
    });
});

/**
 * 弹出文件选择窗口
 */
function openFileUploader() {
    if (!$("#form").form('validate')) {
        layer.msg('附件类型必填');
        return;
    }
    $("#fileUpload .filebox-label").click();
}

/**
 * 文件上传后触发
 */
function handleFileUpload() {
    const fileType = $(el.fileType).val();
    const files = $("#fileInput").filebox('files');
    if (files.length !== 0) {
        let formData = new FormData();
        for (let i = 0; i < files.length; i++) {
            formData.append("files", files[i]); // 关键：逐个添加
        }
        fileUploadAjaxWithCall(formData, function (rows) {
            const data = []
            $.each(rows, function (index, item) {
                data.push({
                    fileId: item.id,
                    fileName: item.fileName,
                    dateline: item.dateline,
                    type: fileType
                })
            });
            sendDataToParent(data);
        }, true);
    }
}

/**
 * 将文件数据回传父页面
 * @param data 文件对象包括：文件队列、文件类型
 * @returns {boolean}
 */
function sendDataToParent(data) {
    //使用父页面传递的回调函数
    try {
        if (typeof window.parentCallback === 'function') {
            window.parentCallback(data);
            return true;
        }
    } catch (error) {
        console.log('callback方式失败:', error);
    }

    $.messager.alert('错误', '无法与父页面通信', 'error');
    return false;
}

function save(call) {
    var fieldArray = $('.fieldTable tbody tr');
    let businessData = [];
    $.each(fieldArray, function (index, target) {
        var  fileIds = $(this).find('.files').attr('data-fileIds');
        if (fileIds){
            //fileIds转数组
            var fileIdArray = fileIds.split(',');
            if (fileIdArray.length > 0) {
                for (let i = 0; i < fileIdArray.length; i++) {
                    var field = {};
                    field.businessId = businessId;
                    field.businessCode = businessCode;
                    field.businessTypeCode = businessTypeCode;
                    field.type = $(this).find('.code').val();
                    field.fileId = fileIdArray[i];
                    businessData.push(field);
                }
            }
        }
    });
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/sys/businessAttachment/rest/save',
        method: 'post',
        data: JSON.stringify(businessData),
        contentType: 'application/json',
        success: function (data) {
            top.layer.close(loading);
            call();
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            top.layer.close(loading);
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}
