"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RichTextImg = exports.CustomUploader = void 0;
var tslib_1 = require("tslib");
var react_1 = (0, tslib_1.__importStar)(require("react"));
var braft_editor_1 = (0, tslib_1.__importDefault)(require("braft-editor"));
var react_use_1 = require("react-use");
var prop_types_1 = require("prop-types");
var braft_utils_1 = require("braft-utils");
var classnames_1 = (0, tslib_1.__importDefault)(require("../../utils/classnames"));
var formcell_1 = (0, tslib_1.__importDefault)(require("../form/formcell"));
var tcb_1 = require("../../utils/tcb");
var tea_component_1 = require("tea-component");
var uuid_1 = require("uuid");
var const_1 = require("./const");
require("./index.css");
require("braft-editor/dist/index.css");
// 默认图片类型
var IMAGE_TYPES = [
    'image/jpeg',
    'image/png',
    'image/gif',
    'image/bmp',
    'image/tiff',
    'image/svg+xml',
];
function RichText(_a) {
    var _b;
    var 
    // 系统属性
    id = _a.id, style = _a.style, className = _a.className, events = _a.events, 
    // 组件属性
    label = _a.label, labelVisible = _a.labelVisible, initialValue = _a.value, readOnly = _a.readOnly, layout = _a.layout, requiredFlag = _a.requiredFlag, onChange = _a.onChange, maxSize = _a.maxSize, acceptTypes = _a.acceptTypes, cloudPath = _a.cloudPath, disabled = _a.disabled;
    var _c = (0, tslib_1.__read)((0, react_1.useState)(), 2), editorState = _c[0], setEditorState = _c[1];
    var cls = (0, classnames_1.default)((_b = {
            'weda-ui': true,
            'weda-richText': true
        },
        _b[className] = className,
        _b));
    var subCls = (0, classnames_1.default)({
        'weui-cell': true,
        'weui-cell_active': true,
        'weui-cell_form': true,
        'weui-cell_disabled': disabled,
    });
    var onDataChange = function (value) {
        events.change && events.change({ value: value === '<p></p>' ? '' : value });
        if (onChange) {
            if (value === '<p></p>') {
                onChange('');
            }
            else {
                onChange(value);
            }
        }
    };
    (0, react_1.useEffect)(function () {
        var state = braft_editor_1.default.createEditorState(initialValue);
        setEditorState(state);
    }, []);
    var extendControls = [
        {
            key: 'richtext-uploader',
            type: 'component',
            component: (react_1.default.createElement(exports.CustomUploader, { acceptTypes: acceptTypes, maxSize: maxSize, cloudPath: cloudPath, onChange: function (url) {
                    var state = braft_utils_1.ContentUtils.insertMedias(editorState, [
                        { type: 'IMAGE', url: url },
                    ]);
                    setEditorState(state);
                } })),
        },
    ];
    // 修改img显示逻辑
    var blockRenderFn = function (contentBlock, _a) {
        var editor = _a.editor, editorState = _a.editorState;
        if (contentBlock.getType() === 'atomic') {
            var entity = editorState
                .getCurrentContent()
                .getEntity(contentBlock.getEntityAt(0));
            if (entity.getType() === 'IMAGE') {
                return {
                    component: exports.RichTextImg,
                    editable: false,
                    props: { editor: editor, editorState: editorState }, // 传入的内容可以在组件中通过this.props.blockProps获取到
                };
            }
        }
    };
    return (react_1.default.createElement(formcell_1.default, { className: cls, label: labelVisible ? label : null, layout: layout, multiCell: false, requiredFlag: requiredFlag },
        react_1.default.createElement("div", { className: subCls },
            react_1.default.createElement("div", { style: (0, tslib_1.__assign)({ border: '1px solid #d1d1d1', backgroundColor: '#fff' }, style) },
                react_1.default.createElement(braft_editor_1.default, { key: id, value: editorState, readOnly: readOnly, blockRendererFn: blockRenderFn, onBlur: function (s) {
                        setEditorState(s);
                        onDataChange(s.toHTML());
                        if (s.toHTML().length > 32768) {
                            tea_component_1.message.warning({
                                content: '富文本长度过长，可能导致保存失败',
                            });
                        }
                    }, excludeControls: ['media', 'fullscreen'], extendControls: extendControls, handleKeyCommand: function (command, editState) {
                        var newState = braft_utils_1.ContentUtils.handleKeyCommand(editState, command);
                        if (newState) {
                            setEditorState(newState);
                            return true;
                        }
                        return false;
                    } })))));
}
exports.default = RichText;
var CustomUploader = function (props) {
    var _a = props.onChange, onChange = _a === void 0 ? function () { } : _a, acceptTypes = props.acceptTypes, maxSize = props.maxSize, cloudPath = props.cloudPath;
    var _b = (0, tslib_1.__read)((0, react_use_1.useSetState)({
        fileList: [],
        percent: 0,
        visible: false,
        uploading: false,
        inputUrl: '',
        previewImg: const_1.defaultBase64,
    }), 2), _c = _b[0], fileList = _c.fileList, percent = _c.percent, visible = _c.visible, uploading = _c.uploading, inputUrl = _c.inputUrl, previewImg = _c.previewImg, setState = _b[1];
    // 获取base64
    var getBase64 = function (file) {
        var reader = new FileReader();
        reader.onloadend = function () {
            setState({ previewImg: reader.result });
        };
        reader.readAsDataURL(file);
    };
    // 计算上传进度
    var onProgress = function (progressEvent) {
        var percentCompleted = 0;
        try {
            percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
            percentCompleted < 100 ? percentCompleted : 100;
        }
        catch (e) {
            tea_component_1.message.error({
                content: '上传图片失败',
            });
        }
        setState({ uploading: true, percent: percentCompleted });
    };
    return (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("button", { role: "richtext", type: "button", "data-title": "\u5A92\u4F53\u4E0A\u4F20", className: "control-item button", onClick: function () { return setState({ visible: true }); } },
            react_1.default.createElement("svg", { viewBox: "64 64 896 896", focusable: "false", "data-icon": "file-image", width: "1em", height: "1em", fill: "currentColor", "aria-hidden": "true" },
                react_1.default.createElement("path", { d: "M534 352V136H232v752h560V394H576a42 42 0 01-42-42zm-134 50c22.1 0 40 17.9 40 40s-17.9 40-40 40-40-17.9-40-40 17.9-40 40-40zm296 294H328.1c-6.7 0-10.4-7.7-6.3-12.9l99.8-127.2a8 8 0 0112.6 0l41.1 52.4 77.8-99.2a8.1 8.1 0 0112.7 0l136.5 174c4.1 5.2.4 12.9-6.3 12.9z", fill: "#e6f7ff" }),
                react_1.default.createElement("path", { d: "M854.6 288.6L639.4 73.4c-6-6-14.1-9.4-22.6-9.4H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V311.3c0-8.5-3.4-16.7-9.4-22.7zM602 137.8L790.2 326H602V137.8zM792 888H232V136h302v216a42 42 0 0042 42h216v494z", fill: "#006eff" }),
                react_1.default.createElement("path", { d: "M553.1 509.1l-77.8 99.2-41.1-52.4a8 8 0 00-12.6 0l-99.8 127.2a7.98 7.98 0 006.3 12.9H696c6.7 0 10.4-7.7 6.3-12.9l-136.5-174a8.1 8.1 0 00-12.7 0zM360 442a40 40 0 1080 0 40 40 0 10-80 0z", fill: "#006eff" }))),
        react_1.default.createElement(tea_component_1.Modal, { onClose: function () {
                setState({ visible: false });
            }, visible: visible, maskClosable: true },
            react_1.default.createElement("p", null, "\u8F93\u5165\u94FE\u63A5\u63D2\u5165\u56FE\u7247"),
            react_1.default.createElement("div", { className: "richText-upload-link" },
                react_1.default.createElement(tea_component_1.Input, { value: inputUrl, placeholder: "\u8F93\u5165\u56FE\u7247\u5730\u5740", onChange: function (value) { return setState({ inputUrl: value }); } }),
                "\u00A0",
                react_1.default.createElement(tea_component_1.Button, { type: "primary", onClick: function () {
                        onChange(inputUrl);
                        setState({ visible: false });
                    } }, "\u786E\u8BA4")),
            react_1.default.createElement("p", { style: { marginBottom: '16px' } }, "\u6216\u62D6\u62FD\u4E0A\u4F20\u63D2\u5165\u56FE\u7247"),
            react_1.default.createElement(tea_component_1.Upload, { accept: acceptTypes.join(), maxSize: 1024 * 1024, beforeUpload: function (file) {
                    getBase64(file);
                    var typeRegex = new RegExp("^((" + acceptTypes.join(')|(').replace('+', '\\+') + "))$");
                    if (acceptTypes.join().includes('*')) {
                        typeRegex = new RegExp("^image/.+$");
                    }
                    if (!typeRegex.test(file.type)) {
                        tea_component_1.message.error({
                            content: '文件格式不支持',
                        });
                        return false;
                    }
                    if (file.size > maxSize * 1024 * 1024) {
                        tea_component_1.message.error({
                            content: "\u6587\u4EF6\u5927\u5C0F\u8D85\u8FC7\u4E0A\u9650" + maxSize + "M",
                        });
                        return false;
                    }
                    setState({
                        uploading: true,
                        percent: 0,
                        fileList: [
                            {
                                name: file.name,
                            },
                        ],
                    });
                    (0, tcb_1.getCloudInstance)().then(function (tcb) { return (0, tslib_1.__awaiter)(void 0, void 0, void 0, function () {
                        var fileType, path, fileID, e_1;
                        return (0, tslib_1.__generator)(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    _a.trys.push([0, 2, 3, 4]);
                                    fileType = file.name.split('.').pop().toLowerCase();
                                    path = cloudPath + "/uploader-" + (0, uuid_1.v4)() + "." + fileType;
                                    return [4 /*yield*/, tcb.uploadFile({
                                            cloudPath: path,
                                            filePath: file,
                                            onUploadProgress: onProgress,
                                        })];
                                case 1:
                                    fileID = (_a.sent()).fileID;
                                    onChange(fileID);
                                    setState({
                                        visible: false,
                                        fileList: [],
                                    });
                                    return [3 /*break*/, 4];
                                case 2:
                                    e_1 = _a.sent();
                                    setState({
                                        fileList: [],
                                    });
                                    tea_component_1.message.error({
                                        content: '上传图片失败',
                                    });
                                    return [3 /*break*/, 4];
                                case 3:
                                    setState({ uploading: false, percent: 100 });
                                    return [7 /*endfinally*/];
                                case 4: return [2 /*return*/];
                            }
                        });
                    }); });
                    return false;
                } }, function (_a) {
                var open = _a.open, isDragging = _a.isDragging;
                return (react_1.default.createElement(tea_component_1.Upload.Dragger, { filename: fileList[0] && fileList[0].name, percent: percent, image: previewImg, className: "richtext_upload_dragger" }, isDragging ? ('释放鼠标') : (react_1.default.createElement(react_1.default.Fragment, null,
                    react_1.default.createElement("a", { onClick: open }, "\u70B9\u51FB\u4E0A\u4F20"),
                    react_1.default.createElement(tea_component_1.Text, { theme: "weak" }, "/\u62D6\u62FD\u5230\u6B64\u533A\u57DF")))));
            }),
            uploading && (react_1.default.createElement(tea_component_1.Progress, { style: { marginTop: '10px' }, percent: percent })))));
};
exports.CustomUploader = CustomUploader;
var RichTextImg = function (_a) {
    var contentState = _a.contentState, block = _a.block;
    var blockData = contentState.getEntity(block.getEntityAt(0)).getData();
    var url = (blockData || {}).url;
    var _b = (0, tslib_1.__read)(react_1.default.useState(''), 2), src = _b[0], setSrc = _b[1];
    var _c = (0, tslib_1.__read)(react_1.default.useState('unset'), 2), width = _c[0], setWidth = _c[1];
    (0, react_1.useEffect)(function () {
        var getSrc = function () { return (0, tslib_1.__awaiter)(void 0, void 0, void 0, function () {
            var _src, e_2;
            return (0, tslib_1.__generator)(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 4, , 5]);
                        if (!url.includes('cloud://')) return [3 /*break*/, 2];
                        return [4 /*yield*/, (0, tcb_1.getTempFileURL)(url)];
                    case 1:
                        _src = _a.sent();
                        setSrc(_src || url);
                        return [3 /*break*/, 3];
                    case 2:
                        setSrc(url);
                        _a.label = 3;
                    case 3: return [3 /*break*/, 5];
                    case 4:
                        e_2 = _a.sent();
                        tea_component_1.message.error({
                            content: "\u663E\u793A\u56FE\u7247\u5931\u8D25\uFF1A" + (e_2.message || '未知原因'),
                        });
                        return [3 /*break*/, 5];
                    case 5: return [2 /*return*/];
                }
            });
        }); };
        getSrc();
    }, [url]);
    return (src && (react_1.default.createElement(react_1.default.Fragment, null,
        react_1.default.createElement("div", { className: "bf-media" },
            react_1.default.createElement("div", { draggable: "true", className: "bf-image", style: { float: 'left' } },
                react_1.default.createElement("div", { style: { position: 'relative', display: 'inline-block' } },
                    react_1.default.createElement("img", { src: src, key: url + Math.random(), style: { maxWidth: '100%', width: width }, onError: function () {
                            setSrc(const_1.defaultBase64);
                            setWidth('80px');
                        } }),
                    react_1.default.createElement("div", { className: "bf-pre-csize" }))),
            react_1.default.createElement("div", { style: {
                    clear: 'both',
                    height: '0px',
                    lineHeight: 0,
                    float: 'none',
                } })))));
};
exports.RichTextImg = RichTextImg;
RichText.propTypes = {
    // 系统属性
    id: prop_types_1.string,
    style: prop_types_1.object,
    value: prop_types_1.string,
    className: prop_types_1.string,
    events: prop_types_1.object,
    // 组件属性
    label: prop_types_1.string,
    labelVisible: prop_types_1.bool,
    name: prop_types_1.string,
    readOnly: prop_types_1.bool,
    layout: (0, prop_types_1.oneOf)(['horizontal', 'vertical']),
    requiredFlag: prop_types_1.bool,
    onChange: prop_types_1.func,
    maxSize: prop_types_1.number,
    acceptTypes: prop_types_1.array,
    cloudPath: prop_types_1.string,
    disabled: prop_types_1.bool
};
RichText.defaultProps = {
    // 系统属性
    events: {},
    style: { width: '100%' },
    // 组件属性
    label: '标题',
    labelVisible: true,
    name: 'formRichText',
    value: '',
    readOnly: false,
    layout: 'vertical',
    requiredFlag: false,
    maxSize: 10,
    acceptTypes: IMAGE_TYPES,
    cloudPath: 'weda-richtext-upload',
};
exports.CustomUploader.propTypes = {
    onChange: prop_types_1.func,
    maxSize: prop_types_1.number,
    acceptTypes: prop_types_1.array,
    cloudPath: prop_types_1.string,
};
exports.CustomUploader.defaultProps = {
    maxSize: 10,
    acceptTypes: IMAGE_TYPES,
    cloudPath: 'weda-richtext-upload',
};
exports.RichTextImg.propTypes = {
    contentState: prop_types_1.object,
    block: prop_types_1.object,
};
exports.RichTextImg.defaultProps = {};
//# sourceMappingURL=index.js.map