import * as __WEBPACK_EXTERNAL_MODULE_react__ from "react";
import * as __WEBPACK_EXTERNAL_MODULE__tachybase_schema__ from "@tachybase/schema";
import * as __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__ from "../../../api-client/index.mjs";
import * as __WEBPACK_EXTERNAL_MODULE__placeholder_mjs__ from "./placeholder.mjs";
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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.isValid)(value)) return [];
    if (0 === Object.keys(value).length) return [];
    return (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.toArr)(value);
};
const testOpts = (ext, options)=>{
    if (options && (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.isArr)(options.include)) return options.include.some((url)=>ext.test(url));
    if (options && (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.isArr)(options.exclude)) return !options.exclude.some((url)=>ext.test(url));
    return true;
};
const getImageByUrl = (url, options)=>{
    for(let i = 0; i < __WEBPACK_EXTERNAL_MODULE__placeholder_mjs__.UPLOAD_PLACEHOLDER.length; i++)if (__WEBPACK_EXTERNAL_MODULE__placeholder_mjs__.UPLOAD_PLACEHOLDER[i].ext.test(url) && testOpts(__WEBPACK_EXTERNAL_MODULE__placeholder_mjs__.UPLOAD_PLACEHOLDER[i].ext, options)) return __WEBPACK_EXTERNAL_MODULE__placeholder_mjs__.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, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.useField)();
    (0, __WEBPACK_EXTERNAL_MODULE_react__.useEffect)(()=>{
        const dispose = (0, __WEBPACK_EXTERNAL_MODULE__tachybase_schema__.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, __WEBPACK_EXTERNAL_MODULE__api_client_index_mjs__.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;
    });
export { getErrorMessage, getImageByUrl, getState, getThumbURL, getURL, isImage, isPdf, normalizeFileList, testOpts, toArr, toFileList, toImages, toItem, toMap, toValue, useUploadProps, useUploadValidator, useValidator };
