/**
 *
 * 父画面调用时，按钮需要校验时参考如下代码，在onOpen加入回调
 *      openDialog("attachmentFileDetailDialog", url, {
 *           title: '送货单附件',
 *           ...
 *           onOpen: function() {
 *               // dialog打开后，等待iframe加载完成
 *               const iframe = $(this).find('iframe')[0];
 *               iframe.onload = async function() {
 *                   // 按钮需要校验时参考如下代码：
 *                   iframe.contentWindow.uploadValidation = accountStatementExistValidation;
 *                   ...
 *               };
 *           }
 *       });
 * @author Chen Tianshi
 * @version 1.0
 */
let el = {
    businessAttachment: '#businessAttachment'
}
let uploadAttachmentFileDialog;
$(function () {
    // 初始化附件类型字典数据-businessFileTypeNecessaryData
    initDict("businessFileType");
    initOrderFileTb();
});

/**
 * 初始化表格
 */
function initOrderFileTb () {
    const column = [[
        {
            field: 'ck', checkbox: true
        }, {
            field: 'type', title: "附件类型", width: '10%', formatter: function (value) {
                return getNameByCode(businessFileTypeNecessaryData, value);
            }
        }, {
            field: 'fileName', title: "附件名称", width: '20%'
        }, {
            field: 'deleteFlag', title: "删除标记", formatter: function (value) {
                if (value === 1) {
                    return "<span style='color: red;'>是</span>"
                }
                return "否"
            }
        }, {
            field: 'remark', title: "备注", width: '20%'
        }, {
            field: 'updateUser', title: "最近修改人"
        }, {
            field: 'updateTime', title: "最近修改时间"
        }, {
            field: 'fileId', title: BJGL.BJGL__XZ, width: '10%', formatter: function (value, row) {
                return '<a href="#" onclick="previewFileForm(undefined,\'' + row.fileName + '\',\'' + row.fileId + '\')">预览</a>'+"&nbsp;&nbsp;<a href='" + g.ctx + "pc/sys/file/rest/download/" + value + "' title='" + row.fileName + "'>下载</a>"
            }
        }
    ]];
    const toolbar = [
        {
            text: BJGL.BJGL__SC, iconCls: 'icon-add', hidden: true, handler: uploadAttachmentFile
        }, "-", {
            text: BJGL.BJGL__SHANC, iconCls: 'icon-remove', handler: deleteAttachmentFile
        }, "-", {
            text: "设置备注", iconCls: 'icon-remove', handler: remarkAttachmentFile
        }
    ];

    const url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentList?businessId=' + businessId +"&=businessTypeCodes" + businessTypeCode;
    // 加载附件列表
    $(el.businessAttachment).datagrid({
        url: url,
        height: document.documentElement.clientHeight - 10,
        method: "GET",
        width: gridwidth,
        singleSelect: true,
        pagination: true,
        autoHeight: true,
        loadMsg: ALLCOMMON.LOADING,
        rownumbers: true,
        fitColumns: false,
        nowrap: true,
        remoteSort: false,
        striped: true,
        columns: column,
        toolbar: toolbar
    });
}

/**
 * 上传
 */
function uploadAttachmentFile() {
    // if (!validation(window.uploadValidation, [], businessId)) return;
    // const url = g.ctx + "pc/sys/businessAttachment/fileUploadWithType";
    // uploadAttachmentFileDialog = openDialog("uploadAttachmentFileDialog", url, {
    //     title: '附件上传',
    //     width: '400px',
    //     height: '250px',
    //     cache: false,
    //     modal: true,
    //     border: false,
    //     draggable: true,
    //     shadow: false,
    //     onClose: function () {
    //         uploadAttachmentFileDialog.dialog('destroy');
    //     },
    //     onOpen: function() {
    //         // dialog打开后，等待iframe加载完成
    //         const iframe = $(this).find('iframe')[0];
    //         iframe.onload = function() {
    //             // 将父页面的函数引用传递给iframe
    //             iframe.contentWindow.parentCallback = receiveFileUploadData;
    //         };
    //     },
    //     buttons: [{
    //         text: '继续', iconCls: 'icon-save', handler: function () {
    //             const iframe = uploadAttachmentFileDialog.find('iframe')[0];
    //             if (iframe.contentWindow.openFileUploader) {
    //                 iframe.contentWindow.openFileUploader();
    //             } else {
    //                 console.error('openFileUploader method not found');
    //             }
    //         }
    //     }, {
    //         text: '关闭', iconCls: 'icon-cancel', handler: function () {
    //             uploadAttachmentFileDialog.dialog('close');
    //         }
    //     }]
    // });

    openCommonFileDialog('commonFileDialog',{
        //业务类型编码
        title:'附件上传',
        //业务类型编码
        businessTypeCode:businessTypeCode,
        businessCode:businessCode,
        //业务唯一id
        businessId:businessId,
        callBack : function () {
            $(el.businessAttachment).datagrid('reload');
        },
    });
}

/**
 * 上传完文件的回调
 * @param data 上传文件服务器后的文件数据
 */
function receiveFileUploadData(data) {
    data.forEach(item => {
        item["businessId"] = businessId;
        item["businessCode"] = businessCode;
        item["businessTypeCode"] = businessTypeCode;
    })
    $.ajax({
        url: g.ctx + 'pc/sys/businessAttachment/rest/save',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function () {
            topWin.layer.msg('保存成功', {icon: 1});
            $(el.businessAttachment).datagrid('reload');
        },
        error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

    uploadAttachmentFileDialog.dialog('close');
}

/**
 * 删除
 */
function deleteAttachmentFile() {
    const rows = $(el.businessAttachment).datagrid("getChecked");
    if (rows.length > 0) {
        // if (!validation(window.deleteValidation, rows, businessId)) return;
        // if (!validation(window.deleteInvoiceValidation, rows, businessId)) return;
        const id = rows[0].id;

        var loading = topWin.layer.msg('数据操作中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/sys/businessAttachment/rest/deleteCheck',
            type: 'POST',
            data: {
                id: id
            },
            success: function (result) {
                topWin.layer.close(loading);
                topWin.layer.prompt({
                    formType: 2, value: '', title: '请输入删除备注',
                }, function (value, index) {
                    $.ajax({
                        type: 'post',
                        url: g.ctx + 'pc/sys/businessAttachment/rest/delete',
                        data: {
                            id: id,
                            remark: value
                        },
                        async: false,
                        success: function () {
                            $(el.businessAttachment).datagrid('reload');
                            topWin.layer.close(index);
                        }, error: function (data) {
                            topWin.layer.close(index);
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                });
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    } else {
        layer.msg('请选择一条数据');
    }
}

/**
 * 备注
 */
function remarkAttachmentFile() {
    const rows = $(el.businessAttachment).datagrid("getChecked");
    if (rows.length > 0) {
        if (!validation(window.remarkValidation, rows, businessId)) return;
        const id = rows[0].id;
        topWin.layer.prompt({
            formType: 2, value: '', title: '请输入备注',
        }, function (value, index) {
            $.ajax({
                type: 'post',
                url: g.ctx + 'pc/sys/businessAttachment/rest/remark',
                data: {
                    id: id,
                    remark: value
                },
                async: false,
                success: function () {
                    $(el.businessAttachment).datagrid('reload');
                    topWin.layer.close(index);
                }, error: function (data) {
                    topWin.layer.close(index);
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        });
    } else {
        layer.msg('请选择一条数据');
    }
}

/**
 * 根据code获取对应的name
 * @param {Array} list - 文件类型列表
 * @param {string} code - 要查找的code
 * @returns {string|null} 对应的name，找不到返回null
 */
function getNameByCode(list, code) {
    const item = list.find(item => item.code === code);
    return item ? item.name : null;
}

/**
 * 按钮校验
 * @param parentValidationFunction 父画面的校验回调
 * @param rows 选中的行数据
 * @param businessId 业务ID
 * @returns {boolean} 结果
 */
function validation(parentValidationFunction, rows, businessId) {
    if (typeof parentValidationFunction === 'function') {
        /**
         * result: {
         *     isError: false/true
         *     message: 校验信息
         * }
         */
        const result = parentValidationFunction(rows, businessId);
        if (result.isError) {
            topWin.layer.alert(result.message, {icon: 2});
            return false;
        }
    }
    return true;
}