"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.d = function(exports1, definition) {
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = function(obj, prop) {
        return Object.prototype.hasOwnProperty.call(obj, prop);
    };
})();
(()=>{
    __webpack_require__.r = function(exports1) {
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    getURL: ()=>getURL,
    toMap: ()=>toMap,
    isPdf: ()=>isPdf,
    toArr: ()=>toArr,
    getImageByUrl: ()=>getImageByUrl,
    getThumbURL: ()=>getThumbURL,
    toImages: ()=>toImages,
    toItem: ()=>toItem,
    toValue: ()=>toValue,
    getErrorMessage: ()=>getErrorMessage,
    isImage: ()=>isImage,
    testOpts: ()=>testOpts,
    useUploadProps: ()=>useUploadProps,
    normalizeFileList: ()=>normalizeFileList,
    useUploadValidator: ()=>useUploadValidator,
    useValidator: ()=>useValidator,
    toFileList: ()=>toFileList,
    getState: ()=>getState
});
const external_react_namespaceObject = require("react");
const schema_namespaceObject = require("@tachybase/schema");
const index_js_namespaceObject = require("../../../api-client/index.js");
const external_placeholder_js_namespaceObject = require("./placeholder.js");
const isImage = (extName)=>{
    const reg = /\.(png|jpg|gif|jpeg|webp)$/;
    return reg.test(extName);
};
const isPdf = (extName)=>extName.toLowerCase().endsWith('.pdf');
const toMap = (fileList)=>{
    if (!fileList) return [];
    if ('object' != typeof fileList) return [];
    let list = fileList;
    if (!Array.isArray(fileList)) {
        if (0 === Object.keys({
            ...fileList
        }).length) return [];
        list = [
            fileList
        ];
    }
    return list.map((item)=>[
            item.id || item.uid,
            toItem(item)
        ]);
};
const toImages = (fileList)=>{
    if (!fileList) return [];
    if ('object' != typeof fileList) return [];
    if (0 === Object.keys(fileList).length) return [];
    let list = fileList;
    if (!Array.isArray(fileList) && 'object' == typeof fileList) list = [
        fileList
    ];
    return list.map((item)=>({
            ...item,
            title: item.title || item.name,
            imageUrl: getImageByUrl(item.url, {
                exclude: [
                    '.png',
                    '.jpg',
                    '.jpeg',
                    '.gif'
                ]
            })
        }));
};
const toArr = (value)=>{
    if (!(0, schema_namespaceObject.isValid)(value)) return [];
    if (0 === Object.keys(value).length) return [];
    return (0, schema_namespaceObject.toArr)(value);
};
const testOpts = (ext, options)=>{
    if (options && (0, schema_namespaceObject.isArr)(options.include)) return options.include.some((url)=>ext.test(url));
    if (options && (0, schema_namespaceObject.isArr)(options.exclude)) return !options.exclude.some((url)=>ext.test(url));
    return true;
};
const getImageByUrl = (url, options)=>{
    for(let i = 0; i < external_placeholder_js_namespaceObject.UPLOAD_PLACEHOLDER.length; i++)if (external_placeholder_js_namespaceObject.UPLOAD_PLACEHOLDER[i].ext.test(url) && testOpts(external_placeholder_js_namespaceObject.UPLOAD_PLACEHOLDER[i].ext, options)) return external_placeholder_js_namespaceObject.UPLOAD_PLACEHOLDER[i].icon || url;
    return url;
};
const getURL = (target)=>(null == target ? void 0 : target['url']) || (null == target ? void 0 : target['downloadURL']) || (null == target ? void 0 : target['imgURL']);
const getThumbURL = (target)=>(null == target ? void 0 : target['thumbUrl']) || (null == target ? void 0 : target['url']) || (null == target ? void 0 : target['downloadURL']) || (null == target ? void 0 : target['imgURL']);
const getErrorMessage = (target)=>(null == target ? void 0 : target.errorMessage) || (null == target ? void 0 : target.errMsg) || (null == target ? void 0 : target.errorMsg) || (null == target ? void 0 : target.message) || 'string' == typeof (null == target ? void 0 : target.error) ? target.error : '';
const getState = (target)=>{
    if ((null == target ? void 0 : target.success) === false) return 'error';
    if ((null == target ? void 0 : target.failed) === true) return 'error';
    if (null == target ? void 0 : target.error) return 'error';
    return (null == target ? void 0 : target.state) || (null == target ? void 0 : target.status);
};
const normalizeFileList = (fileList)=>{
    if (fileList && fileList.length) return fileList.map((file, index)=>({
            ...file,
            uid: file.uid || "".concat(index),
            status: getState(file.response) || getState(file),
            url: getURL(file) || getURL(null == file ? void 0 : file.response),
            thumbUrl: getImageByUrl(getThumbURL(file) || getThumbURL(null == file ? void 0 : file.response), {
                exclude: [
                    '.png',
                    '.jpg',
                    '.jpeg',
                    '.gif'
                ]
            })
        }));
    return [];
};
const useValidator = (validator)=>{
    const field = (0, schema_namespaceObject.useField)();
    (0, external_react_namespaceObject.useEffect)(()=>{
        const dispose = (0, schema_namespaceObject.reaction)(()=>field.value, (value)=>{
            const message = validator(value);
            field.setFeedback({
                type: 'error',
                code: 'UploadError',
                messages: message ? [
                    message
                ] : []
            });
        });
        return ()=>{
            dispose();
        };
    }, []);
};
const useUploadValidator = function() {
    let serviceErrorMessage = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : 'Upload Service Error';
    useValidator((value)=>{
        const list = toArr(value);
        for(let i = 0; i < list.length; i++){
            var _list_i;
            if ((null === (_list_i = list[i]) || void 0 === _list_i ? void 0 : _list_i.status) === 'error') {
                var _list_i1;
                return getErrorMessage(null === (_list_i1 = list[i]) || void 0 === _list_i1 ? void 0 : _list_i1.response) || getErrorMessage(list[i]) || serviceErrorMessage;
            }
        }
    });
};
function useUploadProps(param) {
    let { serviceErrorMessage, ...props } = param;
    useUploadValidator(serviceErrorMessage);
    const onChange = (param)=>{
        var _props_onChange;
        null === (_props_onChange = props.onChange) || void 0 === _props_onChange || _props_onChange.call(props, normalizeFileList([
            ...param.fileList
        ]));
    };
    const api = (0, index_js_namespaceObject.useAPIClient)();
    return {
        ...props,
        customRequest (param) {
            let { action, data, file, filename, headers, onError, onProgress, onSuccess, withCredentials } = param;
            const formData = new FormData();
            if (data) Object.keys(data).forEach((key)=>{
                formData.append(key, data[key]);
            });
            formData.append(filename, file);
            api.axios.post(action, formData, {
                withCredentials,
                headers,
                onUploadProgress: (param)=>{
                    let { total, loaded } = param;
                    onProgress({
                        percent: Math.round(loaded / total * 100).toFixed(2)
                    }, file);
                }
            }).then((param)=>{
                let { data } = param;
                onSuccess(data, file);
            }).catch(onError).finally(()=>{});
            return {
                abort () {
                    console.warn('upload progress is aborted.');
                }
            };
        },
        onChange
    };
}
const toItem = (file)=>{
    var _file_response;
    if (null == file ? void 0 : null === (_file_response = file.response) || void 0 === _file_response ? void 0 : _file_response.data) file = {
        uid: file.uid,
        ...file.response.data
    };
    return {
        ...file,
        id: file.id || file.uid,
        title: file.title || file.name,
        imageUrl: getImageByUrl(file.url, {
            exclude: [
                '.png',
                '.jpg',
                '.jpeg',
                '.gif'
            ]
        })
    };
};
const toFileList = (fileList)=>toArr(fileList).filter(Boolean).map(toItem);
const toValue = (fileList)=>toArr(fileList).filter((file)=>!file.response || 'done' === file.status).map((file)=>{
        var _file_response;
        return (null == file ? void 0 : null === (_file_response = file.response) || void 0 === _file_response ? void 0 : _file_response.data) || file;
    });
var __webpack_export_target__ = exports;
for(var __webpack_i__ in __webpack_exports__)__webpack_export_target__[__webpack_i__] = __webpack_exports__[__webpack_i__];
if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
    value: true
});
