function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
    try {
        var info = gen[key](arg);
        var value = info.value;
    } catch (error) {
        reject(error);
        return;
    }
    if (info.done) {
        resolve(value);
    } else {
        Promise.resolve(value).then(_next, _throw);
    }
}
function _async_to_generator(fn) {
    return function() {
        var self = this, args = arguments;
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(self, args);
            function _next(value) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
            }
            function _throw(err) {
                asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
            }
            _next(undefined);
        });
    };
}
function _define_property(obj, key, value) {
    if (key in obj) {
        Object.defineProperty(obj, key, {
            value: value,
            enumerable: true,
            configurable: true,
            writable: true
        });
    } else {
        obj[key] = value;
    }
    return obj;
}
function _instanceof(left, right) {
    if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
        return !!right[Symbol.hasInstance](left);
    } else {
        return left instanceof right;
    }
}
function _object_spread(target) {
    for(var i = 1; i < arguments.length; i++){
        var source = arguments[i] != null ? arguments[i] : {};
        var ownKeys = Object.keys(source);
        if (typeof Object.getOwnPropertySymbols === "function") {
            ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function(sym) {
                return Object.getOwnPropertyDescriptor(source, sym).enumerable;
            }));
        }
        ownKeys.forEach(function(key) {
            _define_property(target, key, source[key]);
        });
    }
    return target;
}
function ownKeys(object, enumerableOnly) {
    var keys = Object.keys(object);
    if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);
        if (enumerableOnly) {
            symbols = symbols.filter(function(sym) {
                return Object.getOwnPropertyDescriptor(object, sym).enumerable;
            });
        }
        keys.push.apply(keys, symbols);
    }
    return keys;
}
function _object_spread_props(target, source) {
    source = source != null ? source : {};
    if (Object.getOwnPropertyDescriptors) {
        Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
    } else {
        ownKeys(Object(source)).forEach(function(key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
        });
    }
    return target;
}
function _ts_generator(thisArg, body) {
    var f, y, t, _ = {
        label: 0,
        sent: function() {
            if (t[0] & 1) throw t[1];
            return t[1];
        },
        trys: [],
        ops: []
    }, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype), d = Object.defineProperty;
    return d(g, "next", {
        value: verb(0)
    }), d(g, "throw", {
        value: verb(1)
    }), d(g, "return", {
        value: verb(2)
    }), typeof Symbol === "function" && d(g, Symbol.iterator, {
        value: function() {
            return this;
        }
    }), g;
    function verb(n) {
        return function(v) {
            return step([
                n,
                v
            ]);
        };
    }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while(g && (g = 0, op[0] && (_ = 0)), _)try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [
                op[0] & 2,
                t.value
            ];
            switch(op[0]){
                case 0:
                case 1:
                    t = op;
                    break;
                case 4:
                    _.label++;
                    return {
                        value: op[1],
                        done: false
                    };
                case 5:
                    _.label++;
                    y = op[1];
                    op = [
                        0
                    ];
                    continue;
                case 7:
                    op = _.ops.pop();
                    _.trys.pop();
                    continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
                        _ = 0;
                        continue;
                    }
                    if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
                        _.label = op[1];
                        break;
                    }
                    if (op[0] === 6 && _.label < t[1]) {
                        _.label = t[1];
                        t = op;
                        break;
                    }
                    if (t && _.label < t[2]) {
                        _.label = t[2];
                        _.ops.push(op);
                        break;
                    }
                    if (t[2]) _.ops.pop();
                    _.trys.pop();
                    continue;
            }
            op = body.call(thisArg, _);
        } catch (e) {
            op = [
                6,
                e
            ];
            y = 0;
        } finally{
            f = t = 0;
        }
        if (op[0] & 5) throw op[1];
        return {
            value: op[0] ? op[1] : void 0,
            done: true
        };
    }
}
import { message } from "antd";
import { useContext } from "react";
import { useRefFunction } from "../../Hooks/useRefFunction";
import { I18nContext } from "../../I18n";
import { upLoadFileToServer } from "../AttachmentButton";
import { SupportedFileFormats } from "../AttachmentButton/AttachmentButtonPopover";
import { isMobileDevice, isVivoOrOppoDevice, isWeChat } from "../AttachmentButton/utils";
/**
 * 文件上传管理器
 *
 * @description 封装文件上传相关的逻辑，包括上传、删除、重试等操作
 */ export var useFileUploadManager = function useFileUploadManager(param) {
    var attachment = param.attachment, fileMap = param.fileMap, onFileMapChange = param.onFileMapChange;
    var locale = useContext(I18nContext).locale;
    // 判断是否所有文件上传完成
    var fileUploadDone = (fileMap === null || fileMap === void 0 ? void 0 : fileMap.size) ? Array.from((fileMap === null || fileMap === void 0 ? void 0 : fileMap.values()) || []).every(function(file) {
        return file.status === 'done';
    }) : true;
    // 默认支持的文件格式
    var supportedFormat = (attachment === null || attachment === void 0 ? void 0 : attachment.supportedFormat) || SupportedFileFormats.image;
    /**
   * 更新附件文件列表
   */ var updateAttachmentFiles = useRefFunction(function(newFileMap) {
        onFileMapChange === null || onFileMapChange === void 0 ? void 0 : onFileMapChange(new Map(newFileMap));
    });
    /**
   * 移动设备默认的文件类型 accept 值
   */ var MOBILE_DEFAULT_ACCEPT = 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,.csv,text/plain,application/x-zip-compressed';
    /**
   * 根据支持的格式获取 accept 属性值
   * 优先级：微信 > 手机品牌（oppo/vivo）> 移动设备 > 相册模式 > 默认
   */ var getAcceptValue = useRefFunction(function(forGallery) {
        // 相册模式
        if (forGallery) {
            return 'image/*';
        }
        var isMobile = isMobileDevice();
        var isVivoOrOppo = isVivoOrOppoDevice();
        var isWeChatEnv = isWeChat();
        var extensions = (supportedFormat === null || supportedFormat === void 0 ? void 0 : supportedFormat.extensions) || [];
        // 1. 微信环境最优先：设置为空字符串以打开文件浏览器
        if (isWeChatEnv) {
            return '*';
        }
        // 2. 手机品牌其次（oppo/vivo）：设置为空字符串以打开文件浏览器
        if (isVivoOrOppo) {
            return '*';
        }
        // 3. 移动设备其次：设置为空字符串以打开文件浏览器
        if (isMobile) {
            return '*';
        }
        // 4. 默认情况：使用具体扩展名列表
        return extensions.length > 0 ? extensions.map(function(ext) {
            return ".".concat(ext);
        }).join(',') : MOBILE_DEFAULT_ACCEPT;
    });
    /**
   * 上传图片
   */ var uploadImage = useRefFunction(function(forGallery) {
        return _async_to_generator(function() {
            var _ref, isUploading, _iteratorNormalCompletion, _didIteratorError, _iteratorError, _iterator, _step, file, currentFileCount, errorMsg, accept, input;
            return _ts_generator(this, function(_state) {
                // 检查是否有文件正在上传中
                isUploading = false;
                _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
                try {
                    for(_iterator = ((fileMap === null || fileMap === void 0 ? void 0 : fileMap.values()) || [])[Symbol.iterator](); !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
                        file = _step.value;
                        if (file.status === 'uploading') {
                            isUploading = true;
                            break;
                        }
                    }
                } catch (err) {
                    _didIteratorError = true;
                    _iteratorError = err;
                } finally{
                    try {
                        if (!_iteratorNormalCompletion && _iterator.return != null) {
                            _iterator.return();
                        }
                    } finally{
                        if (_didIteratorError) {
                            throw _iteratorError;
                        }
                    }
                }
                if (isUploading) {
                    return [
                        2
                    ];
                }
                // 检查是否已达到最大文件数量限制
                currentFileCount = (fileMap === null || fileMap === void 0 ? void 0 : fileMap.size) || 0;
                if ((attachment === null || attachment === void 0 ? void 0 : attachment.maxFileCount) && currentFileCount >= attachment.maxFileCount) {
                    errorMsg = (locale === null || locale === void 0 ? void 0 : locale['markdownInput.maxFileCountExceeded']) ? locale['markdownInput.maxFileCountExceeded'].replace('${maxFileCount}', String(attachment.maxFileCount)) : "最多只能上传 ".concat(attachment.maxFileCount, " 个文件");
                    message.error(errorMsg);
                    return [
                        2
                    ];
                }
                accept = getAcceptValue(forGallery || false);
                input = document.createElement('input');
                input.id = 'uploadImage' + '_' + Math.random();
                input.type = 'file';
                input.accept = accept;
                input.multiple = (_ref = attachment === null || attachment === void 0 ? void 0 : attachment.allowMultiple) !== null && _ref !== void 0 ? _ref : true;
                input.style.display = 'none';
                input.onchange = function(e) {
                    return _async_to_generator(function() {
                        var selectedFiles, currentFileCount, errorMsg, totalFileCount, errorMsg1, error;
                        return _ts_generator(this, function(_state) {
                            switch(_state.label){
                                case 0:
                                    if (input.dataset.readonly) {
                                        return [
                                            2
                                        ];
                                    }
                                    input.dataset.readonly = 'true';
                                    _state.label = 1;
                                case 1:
                                    _state.trys.push([
                                        1,
                                        3,
                                        4,
                                        5
                                    ]);
                                    selectedFiles = e.target.files;
                                    if (!selectedFiles || selectedFiles.length === 0) {
                                        return [
                                            2
                                        ];
                                    }
                                    // 检查选择的文件数量是否超过限制
                                    currentFileCount = (fileMap === null || fileMap === void 0 ? void 0 : fileMap.size) || 0;
                                    if (attachment === null || attachment === void 0 ? void 0 : attachment.maxFileCount) {
                                        // 如果一次选择的文件数量超过最大限制，完全拒绝
                                        if (selectedFiles.length > attachment.maxFileCount) {
                                            errorMsg = (locale === null || locale === void 0 ? void 0 : locale['markdownInput.maxFileCountExceeded']) ? locale['markdownInput.maxFileCountExceeded'].replace('${maxFileCount}', String(attachment.maxFileCount)) : "最多只能上传 ".concat(attachment.maxFileCount, " 个文件");
                                            message.error(errorMsg);
                                            return [
                                                2
                                            ];
                                        }
                                        // 如果选择的文件数量加上已有文件数量超过限制，完全拒绝
                                        totalFileCount = selectedFiles.length + currentFileCount;
                                        if (totalFileCount > attachment.maxFileCount) {
                                            errorMsg1 = (locale === null || locale === void 0 ? void 0 : locale['markdownInput.maxFileCountExceeded']) ? locale['markdownInput.maxFileCountExceeded'].replace('${maxFileCount}', String(attachment.maxFileCount)) : "最多只能上传 ".concat(attachment.maxFileCount, " 个文件");
                                            message.error(errorMsg1);
                                            return [
                                                2
                                            ];
                                        }
                                    }
                                    return [
                                        4,
                                        upLoadFileToServer(selectedFiles, _object_spread_props(_object_spread({}, attachment), {
                                            fileMap: fileMap,
                                            onFileMapChange: function onFileMapChange(newFileMap) {
                                                updateAttachmentFiles(newFileMap);
                                            },
                                            locale: locale
                                        }))
                                    ];
                                case 2:
                                    _state.sent();
                                    return [
                                        3,
                                        5
                                    ];
                                case 3:
                                    error = _state.sent();
                                    console.error('Error uploading files:', error);
                                    return [
                                        3,
                                        5
                                    ];
                                case 4:
                                    input.value = '';
                                    delete input.dataset.readonly;
                                    return [
                                        7
                                    ];
                                case 5:
                                    return [
                                        2
                                    ];
                            }
                        });
                    })();
                };
                if (input.dataset.readonly) {
                    return [
                        2
                    ];
                }
                document.body.appendChild(input);
                input.click();
                input.remove();
                return [
                    2
                ];
            });
        })();
    });
    /**
   * 处理文件删除
   */ var handleFileRemoval = useRefFunction(function(file) {
        return _async_to_generator(function() {
            var _attachment_onDelete, map, error;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        _state.trys.push([
                            0,
                            2,
                            ,
                            3
                        ]);
                        return [
                            4,
                            attachment === null || attachment === void 0 ? void 0 : (_attachment_onDelete = attachment.onDelete) === null || _attachment_onDelete === void 0 ? void 0 : _attachment_onDelete.call(attachment, file)
                        ];
                    case 1:
                        _state.sent();
                        map = new Map(fileMap);
                        map.delete(file.uuid);
                        updateAttachmentFiles(map);
                        return [
                            3,
                            3
                        ];
                    case 2:
                        error = _state.sent();
                        console.error('Error removing file:', error);
                        return [
                            3,
                            3
                        ];
                    case 3:
                        return [
                            2
                        ];
                }
            });
        })();
    });
    /**
   * 处理文件重试
   */ var handleFileRetry = useRefFunction(function(file) {
        return _async_to_generator(function() {
            var map, url, isSuccess, errorMsg, uploadResult, failedMsg, error, map1, errorMessage;
            return _ts_generator(this, function(_state) {
                switch(_state.label){
                    case 0:
                        _state.trys.push([
                            0,
                            5,
                            ,
                            6
                        ]);
                        file.status = 'uploading';
                        map = new Map(fileMap);
                        map.set(file.uuid || '', file);
                        updateAttachmentFiles(map);
                        isSuccess = false;
                        errorMsg = null;
                        if (!(attachment === null || attachment === void 0 ? void 0 : attachment.uploadWithResponse)) return [
                            3,
                            2
                        ];
                        return [
                            4,
                            attachment.uploadWithResponse(file, 0)
                        ];
                    case 1:
                        uploadResult = _state.sent();
                        url = uploadResult.fileUrl;
                        isSuccess = uploadResult.uploadStatus === 'SUCCESS';
                        errorMsg = uploadResult.errorMessage || null;
                        // 将完整的响应数据存储到 file 对象中
                        file.uploadResponse = uploadResult;
                        return [
                            3,
                            4
                        ];
                    case 2:
                        if (!(attachment === null || attachment === void 0 ? void 0 : attachment.upload)) return [
                            3,
                            4
                        ];
                        return [
                            4,
                            attachment.upload(file, 0)
                        ];
                    case 3:
                        url = _state.sent();
                        isSuccess = !!url;
                        _state.label = 4;
                    case 4:
                        if (isSuccess && url) {
                            file.status = 'done';
                            file.url = url;
                            map.set(file.uuid || '', file);
                            updateAttachmentFiles(map);
                            message.success((locale === null || locale === void 0 ? void 0 : locale.uploadSuccess) || 'Upload success');
                        } else {
                            file.status = 'error';
                            map.set(file.uuid || '', file);
                            updateAttachmentFiles(map);
                            failedMsg = errorMsg || (locale === null || locale === void 0 ? void 0 : locale.uploadFailed) || 'Upload failed';
                            message.error(failedMsg);
                        }
                        return [
                            3,
                            6
                        ];
                    case 5:
                        error = _state.sent();
                        console.error('Error retrying file upload:', error);
                        file.status = 'error';
                        map1 = new Map(fileMap);
                        map1.set(file.uuid || '', file);
                        updateAttachmentFiles(map1);
                        errorMessage = _instanceof(error, Error) ? error.message : (locale === null || locale === void 0 ? void 0 : locale.uploadFailed) || 'Upload failed';
                        message.error(errorMessage);
                        return [
                            3,
                            6
                        ];
                    case 6:
                        return [
                            2
                        ];
                }
            });
        })();
    });
    return {
        fileMap: fileMap,
        fileUploadDone: fileUploadDone,
        supportedFormat: supportedFormat,
        uploadImage: uploadImage,
        updateAttachmentFiles: updateAttachmentFiles,
        handleFileRemoval: handleFileRemoval,
        handleFileRetry: handleFileRetry
    };
};
