import { __assign, __awaiter, __generator, __read, __rest, __spreadArray } from "tslib";
import * as React from 'react';
import { Upload, Button, Icon, message, ErrorTip, ImagePreview, ConfigProvider, } from 'tea-component';
import { v4 } from 'uuid';
import classNames from '../../../utils/classnames';
import { getCloudInstance, getTempFileURL } from '../../../utils/tcb';
import { isCloudFileID } from '../../../utils/platform';
import isObjectEqual from '../../../utils/isObjectEqual';
import * as PropTypes from 'prop-types';
// 默认组件类前缀
export var CLASS_PREFIX = 'weda-uploader-pc';
// 默认图片类型
var IMAGE_TYPES = [
    'image/jpg',
    'image/png',
    'image/tif',
    'image/bmp',
    'image/jpeg',
    'image/tiff',
];
/**
 * 上传图片-官方组件
 */
// eslint-disable-next-line react/prop-types
export function UploaderPC(_a) {
    var _b;
    var layout = _a.layout, className = _a.className, id = _a.id, style = _a.style, title = _a.title, tips = _a.tips, props = __rest(_a, ["layout", "className", "id", "style", "title", "tips"]);
    var cls = classNames((_b = {
            'weda-ui': true
        },
        _b[CLASS_PREFIX] = true,
        _b[layout] = layout,
        _b[className] = className,
        _b));
    return (React.createElement("div", { className: cls, id: id, style: style },
        React.createElement("div", { className: CLASS_PREFIX + "__header" },
            title && React.createElement("div", { className: CLASS_PREFIX + "__title" }, title),
            tips && (React.createElement("div", { className: CLASS_PREFIX + "__description" }, tips || ''))),
        React.createElement(UploaderPCInner, __assign({}, props))));
}
export function UploaderPCInner(props) {
    var _this = this;
    var _a = props.tips, tips = _a === void 0 ? '' : _a, _b = props.btnTitle, btnTitle = _b === void 0 ? '上传图片' : _b, _c = props.maxUploadCount, maxUploadCount = _c === void 0 ? 9 : _c, _d = props.maxSize, maxSize = _d === void 0 ? 10 : _d, value = props.value, // 需要兼容 cloud:和https: 协议，需要兼容 字符串和字符串数组
    _e = props.acceptTypes, // 需要兼容 cloud:和https: 协议，需要兼容 字符串和字符串数组
    acceptTypes = _e === void 0 ? IMAGE_TYPES : _e, _f = props.uploadPath, uploadPath = _f === void 0 ? 'weda-uploader' : _f, _g = props.uploadFileName, uploadFileName = _g === void 0 ? 'image' : _g, _h = props.events, events = _h === void 0 ? {} : _h, _j = props.single, single = _j === void 0 ? false : _j, onChange = props.onChange;
    var initialValue = []
        .concat(value)
        .filter(function (d) { return typeof d === 'string' && d !== ''; });
    if (single) {
        maxUploadCount = 1;
        initialValue = initialValue[0] ? [initialValue[0]] : [];
    }
    // 上传中
    var _k = __read(React.useState(false), 2), uploading = _k[0], setUploading = _k[1];
    //上传进度
    var _l = __read(React.useState(0), 2), progress = _l[0], setProgress = _l[1];
    // 文件列表
    var _m = __read(React.useState(initialValue), 2), fileIDList = _m[0], setfileIDList = _m[1];
    var fileRef = React.useRef(fileIDList);
    // 值变化事件
    React.useEffect(function () {
        if (!isObjectEqual(fileRef.current, fileIDList)) {
            events.change && events.change({ value: fileIDList });
            if (single) {
                var file = fileIDList[0] || '';
                file && onChange && onChange(file);
            }
            else {
                onChange && onChange(fileIDList);
            }
            fileRef.current = fileIDList;
        }
    });
    // 方法：上传前，判断图片大小、数量是否满足，取消默认组件的上传事件，用自定义的 tcb 上传方法
    var beforeHandle = function (file, fileList, isAccepted, error) {
        if (!isAccepted) {
            try {
                var errorList = [];
                if (error.find(function (item) { return (item === null || item === void 0 ? void 0 : item.code) === 'file-invalid-type'; })) {
                    errorList.push('上传图片类型错误');
                }
                if (error.find(function (item) { return (item === null || item === void 0 ? void 0 : item.code) === 'file-too-large'; })) {
                    errorList.push("\u4E0A\u4F20\u56FE\u7247\u5927\u5C0F\u4E0D\u80FD\u8D85\u8FC7" + maxSize + "M");
                }
                message.error({ content: errorList.join(', ') });
            }
            catch (e) { }
            return false;
        }
        uploadTcb(file);
        return false;
    };
    // 自定义上传到 Tcb 的 COS
    var uploadTcb = function (file) {
        setUploading(true);
        getCloudInstance().then(function (tcb) { return __awaiter(_this, void 0, void 0, function () {
            var fileType, cloudPath, fileID_1, e_1;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, 3, 4]);
                        fileType = (_a = file.type.split('/')) === null || _a === void 0 ? void 0 : _a[1];
                        cloudPath = uploadPath + "/" + uploadFileName + "-" + v4() + "." + fileType;
                        return [4 /*yield*/, tcb.uploadFile({
                                cloudPath: cloudPath,
                                filePath: file,
                                onUploadProgress: onProgress,
                            })];
                    case 1:
                        fileID_1 = (_b.sent()).fileID;
                        fileID_1 && setfileIDList(function (list) { return __spreadArray(__spreadArray([], __read(list), false), [fileID_1], false); });
                        fileID_1 && events.success && events.success({ value: fileID_1, file: file });
                        return [3 /*break*/, 4];
                    case 2:
                        e_1 = _b.sent();
                        events.error && events.error({ value: e_1, file: file });
                        return [3 /*break*/, 4];
                    case 3:
                        setUploading(false);
                        setProgress(0);
                        return [7 /*endfinally*/];
                    case 4: return [2 /*return*/];
                }
            });
        }); });
    };
    // 计算上传进度
    var onProgress = function (progressEvent) {
        var percentCompleted = 0;
        try {
            percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            percentCompleted < 100 ? percentCompleted : 100;
        }
        catch (e) { }
        setProgress(percentCompleted);
    };
    // 删除图片
    var deleteHandle = function (fileID) {
        setfileIDList(function (list) { return list.filter(function (d) { return d !== fileID; }); });
    };
    // 转换后的属性
    var extraProps = {};
    extraProps['accept'] =
        acceptTypes.includes('image/*') || acceptTypes.length === 0
            ? IMAGE_TYPES
            : Array.from(new Set(acceptTypes));
    tips && (extraProps['title'] = tips);
    maxSize && (extraProps['maxSize'] = maxSize * 1024 * 1024);
    return (React.createElement(ConfigProvider, { classPrefix: "wedatea2td" },
        React.createElement("div", { className: "_weda-fn-upload-result" },
            fileIDList.map(function (d) { return (React.createElement("div", { className: "_weda-fn-upload-result__item", key: d },
                React.createElement(TcbImage, { fileID: d }),
                React.createElement("div", { className: "_weda-fn-upload-result__op" },
                    React.createElement(Button, { onClick: function () { return deleteHandle(d); }, className: CLASS_PREFIX + "__btn" }, "\u5220\u9664")))); }),
            uploading && (React.createElement("div", { className: "_weda-fn-upload-result__item" },
                React.createElement("div", { className: "_weda-fn-upload-result__status", key: "_place_image" },
                    React.createElement(Icon, { type: "loading" }),
                    !!progress && React.createElement("span", { className: "wedatea2td-mt-1n wedatea2td-text-label wedatea2td-fz-reset" },
                        "\u4E0A\u4F20",
                        progress,
                        "%...")))),
            React.createElement("div", { className: CLASS_PREFIX + "__input-box" }, fileIDList.length < maxUploadCount &&
                React.createElement(Upload, __assign({}, extraProps, { beforeUpload: beforeHandle }),
                    React.createElement("li", { className: "_weda-fn-upload-result__item _weda-fn-upload-result__item--upload" },
                        React.createElement("div", { className: "_weda-fn-upload-result__status" },
                            React.createElement("i", { className: "wedatea2td-icon wedatea2td-icon-plus", role: "img", "aria-label": "plus" }),
                            React.createElement("span", { className: "wedatea2td-mt-1n wedatea2td-text-label wedatea2td-fz-reset" }, btnTitle))))))));
}
/**
 * 单张图片回显组件
 */
export var TcbImage = function (props) {
    var fileID = props.fileID, isZoom = props.isZoom, rest = __rest(props, ["fileID", "isZoom"]);
    var _a = __read(React.useState(''), 2), src = _a[0], setSrc = _a[1];
    var _b = __read(React.useState(false), 2), isError = _b[0], setIsError = _b[1];
    React.useEffect(function () {
        var getSrc = function () { return __awaiter(void 0, void 0, void 0, function () {
            var _src, e_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        return [4 /*yield*/, getTempFileURL(fileID)];
                    case 1:
                        _src = _a.sent();
                        _src ? setSrc(_src) : setIsError(true);
                        return [3 /*break*/, 3];
                    case 2:
                        e_2 = _a.sent();
                        message.error('图片加载失败');
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        }); };
        isCloudFileID(fileID) ? getSrc() : setSrc(fileID);
    }, [fileID]);
    return isError ? (React.createElement(ErrorTip, null)) : src ? (isZoom ? (React.createElement(ImagePreview, __assign({ key: fileID, className: CLASS_PREFIX + "__image" }, rest, { src: src, previewSrc: src, onError: function (e) {
            setIsError(true);
            (props === null || props === void 0 ? void 0 : props.onError) && props.onError(e);
        } }))) : (React.createElement("img", __assign({ key: fileID, className: CLASS_PREFIX + "__image" }, rest, { src: src, onError: function (e) {
            setIsError(true);
            (props === null || props === void 0 ? void 0 : props.onError) && props.onError(e);
        } })))) : null;
};
UploaderPCInner.propTypes = {
    className: PropTypes.string,
    title: PropTypes.string,
    tips: PropTypes.string,
    btnTitle: PropTypes.string,
    maxUploadCount: PropTypes.number,
    maxSize: PropTypes.number,
    acceptTypes: PropTypes.array,
    uploadPath: PropTypes.string,
    uploadFileName: PropTypes.string,
    single: PropTypes.bool,
    events: PropTypes.objectOf(PropTypes.func),
    value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
    onChange: PropTypes.objectOf(PropTypes.func),
    style: PropTypes.object,
    id: PropTypes.string,
    layout: PropTypes.oneOf(['horizontal', 'vertical']),
    disabled: PropTypes.bool
};
TcbImage.propTypes = {
    fileID: PropTypes.string,
    isZoom: PropTypes.bool,
    onError: PropTypes.func, // 图片显示错误事件
};
//# sourceMappingURL=uploaderPc.js.map