"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "Uploader", {
    enumerable: true,
    get: function() {
        return Uploader;
    }
});
var _interop_require_default = require("@swc/helpers/_/_interop_require_default");
var _interop_require_wildcard = require("@swc/helpers/_/_interop_require_wildcard");
var _async_to_generator = require("@swc/helpers/_/_async_to_generator");
var _object_spread = require("@swc/helpers/_/_object_spread");
var _object_spread_props = require("@swc/helpers/_/_object_spread_props");
var _object_without_properties = require("@swc/helpers/_/_object_without_properties");
var _sliced_to_array = require("@swc/helpers/_/_sliced_to_array");
var _to_consumable_array = require("@swc/helpers/_/_to_consumable_array");
var _ts_generator = require("@swc/helpers/_/_ts_generator");
var _react = /*#__PURE__*/ _interop_require_wildcard._(require("react"));
var _classnames = /*#__PURE__*/ _interop_require_default._(require("classnames"));
var _iconsreact = require("@nutui/icons-react");
var _configprovider = require("../configprovider");
var _interceptor = require("../../utils/interceptor");
var _typings = require("../../utils/typings");
var _button = /*#__PURE__*/ _interop_require_default._(require("../button"));
var _usepropsvalue = require("../../hooks/use-props-value");
var _preview = require("./preview");
var _mergeprops = require("../../utils/merge-props");
var defaultProps = (0, _object_spread_props._)((0, _object_spread._)({}, _typings.ComponentDefaults), {
    maxCount: Number.MAX_VALUE,
    previewType: 'picture',
    fit: 'cover',
    name: 'file',
    accept: '*',
    disabled: false,
    autoUpload: true,
    multiple: false,
    maxFileSize: Number.MAX_VALUE,
    clearInput: true,
    preview: true,
    deletable: true,
    capture: false,
    uploadIcon: /*#__PURE__*/ _react.default.createElement(_iconsreact.Photograph, {
        width: "20px",
        height: "20px",
        color: "#808080"
    }),
    deleteIcon: /*#__PURE__*/ _react.default.createElement(_iconsreact.Failure, {
        color: "rgba(0,0,0,0.6)"
    }),
    beforeDelete: function beforeDelete(file, files) {
        return true;
    }
});
var InternalUploader = function InternalUploader(props, ref) {
    var locale = (0, _configprovider.useConfig)().locale;
    var fileListRef = (0, _react.useRef)([]);
    var _mergeProps = (0, _mergeprops.mergeProps)(defaultProps, props), children = _mergeProps.children, uploadIcon = _mergeProps.uploadIcon, deleteIcon = _mergeProps.deleteIcon, uploadLabel = _mergeProps.uploadLabel, name = _mergeProps.name, accept = _mergeProps.accept, defaultValue = _mergeProps.defaultValue, value = _mergeProps.value, previewType = _mergeProps.previewType, fit = _mergeProps.fit, disabled = _mergeProps.disabled, multiple = _mergeProps.multiple, previewUrl = _mergeProps.previewUrl, preview = _mergeProps.preview, deletable = _mergeProps.deletable, maxCount = _mergeProps.maxCount, capture = _mergeProps.capture, maxFileSize = _mergeProps.maxFileSize, className = _mergeProps.className, autoUpload = _mergeProps.autoUpload, clearInput = _mergeProps.clearInput, upload = _mergeProps.upload, onDelete = _mergeProps.onDelete, onChange = _mergeProps.onChange, onFileItemClick = _mergeProps.onFileItemClick, onOversize = _mergeProps.onOversize, onOverCount = _mergeProps.onOverCount, beforeUpload = _mergeProps.beforeUpload, beforeDelete = _mergeProps.beforeDelete, onUploadQueueChange = _mergeProps.onUploadQueueChange, restProps = (0, _object_without_properties._)(_mergeProps, [
        "children",
        "uploadIcon",
        "deleteIcon",
        "uploadLabel",
        "name",
        "accept",
        "defaultValue",
        "value",
        "previewType",
        "fit",
        "disabled",
        "multiple",
        "previewUrl",
        "preview",
        "deletable",
        "maxCount",
        "capture",
        "maxFileSize",
        "className",
        "autoUpload",
        "clearInput",
        "upload",
        "onDelete",
        "onChange",
        "onFileItemClick",
        "onOversize",
        "onOverCount",
        "beforeUpload",
        "beforeDelete",
        "onUploadQueueChange"
    ]);
    var _usePropsValue = (0, _sliced_to_array._)((0, _usepropsvalue.usePropsValue)({
        value: value,
        defaultValue: defaultValue,
        finalValue: [],
        onChange: function onChange1(v) {
            onChange === null || onChange === void 0 ? void 0 : onChange(v);
        }
    }), 2), fileList = _usePropsValue[0], setFileList = _usePropsValue[1];
    var _useState = (0, _sliced_to_array._)((0, _react.useState)([]), 2), uploadQueue = _useState[0], setUploadQueue = _useState[1];
    var classes = (0, _classnames.default)(className, 'nut-uploader');
    (0, _react.useEffect)(function() {
        fileListRef.current = fileList;
    }, [
        fileList
    ]);
    (0, _react.useEffect)(function() {
        onUploadQueueChange === null || onUploadQueueChange === void 0 ? void 0 : onUploadQueueChange(uploadQueue);
    }, [
        uploadQueue
    ]);
    (0, _react.useImperativeHandle)(ref, function() {
        return {
            submit: /*#__PURE__*/ (0, _async_to_generator._)(function() {
                return (0, _ts_generator._)(this, function(_state) {
                    switch(_state.label){
                        case 0:
                            return [
                                4,
                                uploadAction(uploadQueue)
                            ];
                        case 1:
                            _state.sent();
                            return [
                                2
                            ];
                    }
                });
            }),
            clear: function clear() {
                clearUploadQueue();
            }
        };
    });
    var clearUploadQueue = function clearUploadQueue() {
        var index = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : -1;
        if (index > -1) {
            uploadQueue.splice(index, 1);
            setUploadQueue(uploadQueue);
        } else {
            setUploadQueue([]);
            setFileList([]);
        }
    };
    var idCountRef = (0, _react.useRef)(0);
    var filterFiles = function filterFiles(files) {
        var maximum = maxCount * 1;
        var oversizes = new Array();
        var filterFile = files.filter(function(file) {
            if (file.size > maxFileSize) {
                oversizes.push(file);
                return false;
            }
            return true;
        });
        oversizes.length && (onOversize === null || onOversize === void 0 ? void 0 : onOversize(files));
        if (filterFile.length > maximum) {
            onOverCount === null || onOverCount === void 0 ? void 0 : onOverCount(filterFile.length);
            filterFile.splice(maximum, filterFile.length - maximum);
        }
        if (fileList.length !== 0) {
            var index = maximum - fileList.length;
            filterFile.splice(index, filterFile.length - index);
        }
        return filterFile;
    };
    var deleted = function deleted(file, index) {
        var deletedFileList = fileListRef.current.filter(function(file, idx) {
            return idx !== index;
        });
        onDelete === null || onDelete === void 0 ? void 0 : onDelete(file, deletedFileList);
        setFileList(deletedFileList);
    };
    var onDeleteItem = function onDeleteItem(file, index) {
        clearUploadQueue(index);
        (0, _interceptor.funcInterceptor)(beforeDelete, {
            args: [
                file,
                fileList
            ],
            done: function done() {
                return deleted(file, index);
            }
        });
    };
    var fileChange = /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function(event) {
            var $el, files, _files, filesArr, tasks;
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        if (disabled) return [
                            2
                        ];
                        $el = event.target;
                        files = $el.files;
                        _files = [];
                        filesArr = new Array().slice.call(files);
                        if (!beforeUpload) return [
                            3,
                            2
                        ];
                        return [
                            4,
                            beforeUpload(filesArr)
                        ];
                    case 1:
                        _files = _state.sent();
                        if (!_files.length) $el.value = '';
                        _state.label = 2;
                    case 2:
                        _files = filterFiles(filesArr);
                        tasks = _files.map(function(file) {
                            var _file_type;
                            var info = {
                                uid: idCountRef.current++,
                                status: autoUpload ? 'uploading' : 'ready',
                                file: file,
                                message: autoUpload ? locale.uploader.uploading : locale.uploader.waitingUpload,
                                name: file.name,
                                type: file.type
                            };
                            if (preview && ((_file_type = file.type) === null || _file_type === void 0 ? void 0 : _file_type.includes('image'))) {
                                var reader = new FileReader();
                                reader.onload = function(event) {
                                    fileListRef.current = (0, _to_consumable_array._)(fileListRef.current).concat([
                                        (0, _object_spread_props._)((0, _object_spread._)({}, info), {
                                            url: event.target.result
                                        })
                                    ]);
                                    setFileList(fileListRef.current);
                                };
                                reader.readAsDataURL(file);
                            }
                            return info;
                        });
                        if (!!autoUpload) return [
                            3,
                            3
                        ];
                        setUploadQueue(tasks);
                        return [
                            3,
                            5
                        ];
                    case 3:
                        return [
                            4,
                            uploadAction(tasks)
                        ];
                    case 4:
                        _state.sent();
                        _state.label = 5;
                    case 5:
                        if (clearInput) {
                            $el.value = '';
                        }
                        return [
                            2
                        ];
                }
            });
        });
        return function fileChange(event) {
            return _ref.apply(this, arguments);
        };
    }();
    var uploadAction = /*#__PURE__*/ function() {
        var _ref = (0, _async_to_generator._)(function(tasks) {
            var taskIds;
            return (0, _ts_generator._)(this, function(_state) {
                switch(_state.label){
                    case 0:
                        taskIds = tasks.map(function(task) {
                            return task.uid;
                        });
                        setFileList(fileList.map(function(file) {
                            if (taskIds.includes(file.uid)) {
                                return (0, _object_spread_props._)((0, _object_spread._)({}, file), {
                                    status: 'uploading',
                                    message: locale.uploader.uploading
                                });
                            }
                            return file;
                        }));
                        return [
                            4,
                            Promise.all(tasks.map(/*#__PURE__*/ function() {
                                var _ref = (0, _async_to_generator._)(function(currentTask, index) {
                                    var result, list, e, list1;
                                    return (0, _ts_generator._)(this, function(_state) {
                                        switch(_state.label){
                                            case 0:
                                                _state.trys.push([
                                                    0,
                                                    2,
                                                    ,
                                                    3
                                                ]);
                                                return [
                                                    4,
                                                    upload(currentTask.file)
                                                ];
                                            case 1:
                                                result = _state.sent();
                                                list = fileListRef.current.map(function(item) {
                                                    if (item.uid === currentTask.uid) {
                                                        item.status = 'success';
                                                        item.message = locale.uploader.success;
                                                        item.url = result.url;
                                                    }
                                                    return item;
                                                });
                                                setFileList(list);
                                                return [
                                                    3,
                                                    3
                                                ];
                                            case 2:
                                                e = _state.sent();
                                                list1 = fileListRef.current.map(function(item) {
                                                    if (item.uid === currentTask.uid) {
                                                        item.status = 'error';
                                                        item.message = locale.uploader.error;
                                                    }
                                                    return item;
                                                });
                                                setFileList(list1);
                                                throw e;
                                            case 3:
                                                return [
                                                    2
                                                ];
                                        }
                                    });
                                });
                                return function(currentTask, index) {
                                    return _ref.apply(this, arguments);
                                };
                            }())).catch(function(errs) {
                                return console.error(errs);
                            })
                        ];
                    case 1:
                        _state.sent();
                        return [
                            2
                        ];
                }
            });
        });
        return function uploadAction(tasks) {
            return _ref.apply(this, arguments);
        };
    }();
    var handleItemClick = function handleItemClick(file, index) {
        onFileItemClick === null || onFileItemClick === void 0 ? void 0 : onFileItemClick(file, index);
    };
    var renderImageUploader = function renderImageUploader() {
        var shouldShow = Number(maxCount) > fileList.length && previewType === 'picture';
        return shouldShow && /*#__PURE__*/ _react.default.createElement("div", {
            className: (0, _classnames.default)('nut-uploader-upload', previewType, {
                'nut-uploader-upload-disabled': disabled
            })
        }, /*#__PURE__*/ _react.default.createElement("div", {
            className: "nut-uploader-icon"
        }, uploadIcon, /*#__PURE__*/ _react.default.createElement("span", {
            className: "nut-uploader-icon-tip"
        }, uploadLabel)), /*#__PURE__*/ _react.default.createElement("input", {
            className: "nut-uploader-input",
            type: "file",
            capture: capture,
            name: name,
            accept: accept,
            disabled: disabled,
            multiple: multiple,
            onChange: fileChange
        }));
    };
    var renderListUploader = function renderListUploader() {
        return previewType === 'list' && /*#__PURE__*/ _react.default.createElement("div", {
            className: "nut-uploader-slot"
        }, /*#__PURE__*/ _react.default.createElement(_button.default, {
            size: "small",
            type: "primary"
        }, locale.uploader.list), Number(maxCount) > fileList.length && /*#__PURE__*/ _react.default.createElement("input", {
            className: "nut-uploader-input",
            type: "file",
            capture: capture,
            name: name,
            accept: accept,
            disabled: disabled,
            multiple: multiple,
            onChange: fileChange
        }));
    };
    return /*#__PURE__*/ _react.default.createElement("div", (0, _object_spread._)({
        className: classes
    }, restProps), renderListUploader(), /*#__PURE__*/ _react.default.createElement(_preview.Preview, {
        fileList: fileList,
        previewType: previewType,
        deletable: deletable,
        onDeleteItem: onDeleteItem,
        handleItemClick: handleItemClick,
        previewUrl: previewUrl,
        children: children,
        deleteIcon: deleteIcon
    }), renderImageUploader());
};
var Uploader = /*#__PURE__*/ _react.default.forwardRef(InternalUploader);
Uploader.displayName = 'NutUploader';
