import { __awaiter, __generator, __read, __spreadArray } from "tslib";
import * as PropTypes from 'prop-types';
import * as React from 'react';
import weui from '../../../utils/weui';
import classNames from '../../../utils/classnames';
import { getCloudInstance } from '../../../utils/tcb';
import { useGetSet } from 'react-use';
/**
 * H5端
 */
export function UploaderH5(_a) {
    var _b;
    var title = _a.title, maxUploadCount = _a.maxUploadCount, className = _a.className, id = _a.id, events = _a.events, layout = _a.layout, value = _a.value, _c = _a.single, single = _c === void 0 ? false : _c, onChange = _a.onChange, style = _a.style;
    var cls = classNames((_b = {
            'weda-ui': true,
            'weui-cells': true,
            'weui-cells_form': true
        },
        _b[className] = className,
        _b));
    var initialValue = []
        .concat(value)
        .filter(function (d) { return typeof d === 'string' && d !== ''; });
    if (single) {
        maxUploadCount = 1;
        initialValue = initialValue[0] ? [initialValue[0]] : [];
    }
    var _d = __read(useGetSet(0), 2), uploadCount = _d[0], setUploadConut = _d[1];
    var _e = __read(React.useState(initialValue), 2), fileIDList = _e[0], setfileIDList = _e[1];
    React.useEffect(function () {
        events.change && events.change({ value: fileIDList });
        if (single) {
            var file = fileIDList[0] || '';
            file && onChange && onChange(file);
        }
        else {
            onChange && onChange(fileIDList);
        }
    }, [fileIDList]);
    React.useEffect(function () {
        var opts = {
            url: 'http://localhost:8081',
            auto: true,
            type: 'file',
            fileVal: 'fileVal',
            compress: {
                width: 1600,
                height: 1600,
                quality: 0.8,
            },
            onBeforeQueued: function (files) {
                // `this` 是轮询到的文件, `files` 是所有文件
                if (['image/jpg', 'image/jpeg', 'image/png', 'image/gif'].indexOf(this.type) < 0) {
                    weui.alert('请上传图片');
                    return false; // 阻止文件添加
                }
                if (this.size > 10 * 1024 * 1024) {
                    weui.alert('请上传不超过10M的图片');
                    return false;
                }
                if (files.length > maxUploadCount) {
                    // 防止一下子选择过多文件
                    weui.alert("\u6700\u591A\u53EA\u80FD\u4E0A\u4F20" + maxUploadCount + "\u5F20\u56FE\u7247\uFF0C\u8BF7\u91CD\u65B0\u9009\u62E9");
                    return false;
                }
                if (uploadCount() + 1 > maxUploadCount) {
                    weui.alert("\u6700\u591A\u53EA\u80FD\u4E0A\u4F20" + maxUploadCount + "\u5F20\u56FE\u7247");
                    return false;
                }
                setUploadConut(function (c) { return c + 1; });
            },
            onQueued: function () {
                var _this = this;
                var file = this;
                getCloudInstance().then(function (tcb) { return __awaiter(_this, void 0, void 0, function () {
                    var fileType, cloudPath, fileID_1, r, $el, $file, err_1;
                    var _a;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                _b.trys.push([0, 2, , 3]);
                                fileType = (_a = file.type.split('/')) === null || _a === void 0 ? void 0 : _a[1];
                                cloudPath = "temp/uploader-" + Date.now() + "." + fileType;
                                return [4 /*yield*/, tcb.uploadFile({
                                        cloudPath: cloudPath,
                                        filePath: file,
                                    })];
                            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 });
                                r = opts.onSuccess(file);
                                if (!r) {
                                    $el = document.querySelector("#" + id);
                                    $file = $el.querySelector("[data-id=\"" + file.id + "\"]");
                                    $file.classList.remove('weui-uploader__file_status');
                                    $file.querySelector('.weui-uploader__file-content').remove();
                                }
                                return [3 /*break*/, 3];
                            case 2:
                                err_1 = _b.sent();
                                opts.onError(file, err_1);
                                return [3 /*break*/, 3];
                            case 3: return [2 /*return*/];
                        }
                    });
                }); });
            },
            onBeforeSend: function () {
                // $.extend(data, { test: 1 }); // 可以扩展此对象来控制上传参数
                // $.extend(headers, { Origin: 'http://127.0.0.1' }); // 可以扩展此对象来控制上传头部
                return false; // 阻止文件上传
            },
            onProgress: function () {
                // console.log(this, percent);
                // return true; // 阻止默认行为，不使用默认的进度显示
            },
            onSuccess: function (ret) {
                events.success && events.success(ret);
                return false;
            },
            onError: function (err) {
                events.error && events.error(err);
                return false;
            },
        };
        weui.uploader("#" + id, opts);
    }, []);
    return (React.createElement("div", { className: cls, id: id, style: style },
        React.createElement("div", { className: "weui-cell" },
            React.createElement("div", { className: "weui-cell__bd" },
                React.createElement("div", { className: classNames("weui-uploader", layout) },
                    React.createElement("div", { className: classNames("weui-uploader__hd", layout) },
                        React.createElement("p", { className: "weui-uploader__title" }, title),
                        React.createElement("div", { className: "weui-uploader__info" },
                            React.createElement("span", { id: "uploadCount" }, uploadCount()), "/" + maxUploadCount)),
                    React.createElement("div", { className: "weui-uploader__bd" },
                        React.createElement("ul", { className: "weui-uploader__files", id: "uploaderFiles" }),
                        React.createElement("div", { className: "weui-uploader__input-box" },
                            React.createElement("input", { id: "uploaderInput", className: "weui-uploader__input", type: "file", accept: "image/*", multiple: "" }))))))));
}
UploaderH5.propTypes = {
    id: PropTypes.string,
    title: PropTypes.string,
    className: PropTypes.string,
    maxUploadCount: PropTypes.number,
    events: PropTypes.objectOf(PropTypes.func),
    style: PropTypes.object,
    layout: PropTypes.oneOf(['horizontal', 'vertical']),
    value: PropTypes.oneOfType([PropTypes.array, PropTypes.string]),
    single: PropTypes.bool,
    onChange: PropTypes.objectOf(PropTypes.func), // 值变化，该参数需配合 formily 使用
};
//# sourceMappingURL=uploaderH5.js.map