var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
import { Button, message, Modal, Typography } from 'antd';
import { ApiCore } from './api-core';
import { OpType } from '@mometa/fs-handler/const';
import React from 'react';
import PQueue from 'p-queue';
import { Form } from 'antd';
import { CodeEditor } from '../../../../shared/code-editor';
import { openReactStandalone } from '../../../../shared/open-react-element';
import { createPreload } from '../../utils/utils';
const getReactWrap = (anotherTo) => ({
    startStr: '<>',
    endStr: '</>',
    anotherTo
});
export class ApiServerPack extends ApiCore {
    constructor(apiBaseURL = '') {
        super(apiBaseURL, {
            loading: (str) => message.loading(str, 0),
            error: (str) => message.error(str)
        });
        this.queue = new PQueue({ concurrency: 1 });
    }
    _submitOperation(requestData) {
        return __awaiter(this, void 0, void 0, function* () {
            yield this.axios.post('/submit-op', requestData);
            return true;
        });
    }
    handleViewOp(opType, dom, extraData) {
        return __awaiter(this, void 0, void 0, function* () {
            if (this.queue.pending && !this.closeTip) {
                this.closeTip = this.toast.loading('任务正在进行中，请等待');
            }
            try {
                return yield this.queue.add(() => {
                    if (this.queue.size === 0) {
                        if (this.closeTip) {
                            this.closeTip();
                            this.closeTip = null;
                        }
                    }
                    return this._handleViewOp(opType, dom, extraData);
                });
            }
            finally {
                if (this.queue.pending === 0 && this.queue.size === 0) {
                    if (this.closeTip) {
                        this.closeTip();
                        this.closeTip = null;
                    }
                }
            }
        });
    }
    confirmWhich(dom, opName, props) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const data = dom.__mometa.getMometaData();
            let p;
            if ((_a = data.container) === null || _a === void 0 ? void 0 : _a.isFirstElement) {
                p = openReactStandalone((cb) => (React.createElement(Modal, { visible: true, footer: React.createElement("div", null,
                        React.createElement(Button, Object.assign({ type: 'primary', onClick: () => cb('container') }, props),
                            opName,
                            "\u5BB9\u5668"),
                        React.createElement(Button, Object.assign({ type: 'primary', onClick: () => cb('self') }, props),
                            opName,
                            "\u81EA\u8EAB"),
                        React.createElement(Button, { type: 'default', size: 'small', onClick: () => cb() }, "\u53D6\u6D88")) },
                    React.createElement(Typography, null,
                        "\u68C0\u6D4B\u5230\u5143\u7D20\u5728\u5BB9\u5668\u5934\u90E8\uFF0C\u8BF7\u9009\u62E9\u5177\u4F53",
                        opName,
                        "\u54EA\u4E2A\uFF0C\u4EE3\u7801\u5982\u4E0B\uFF1A"),
                    React.createElement(Form, { layout: 'vertical', style: { marginTop: 10 } },
                        React.createElement(Form.Item, { label: '自身代码' },
                            React.createElement(CodeEditor, { readOnly: true, value: data.text, height: '100px' })),
                        React.createElement(Form.Item, { label: '容器代码' },
                            React.createElement(CodeEditor, { readOnly: true, value: data.container.text, height: '200px' }))))));
            }
            else {
                p = new Promise((res) => {
                    Modal.confirm({
                        title: `确认${opName}如下代码片段吗？`,
                        content: React.createElement(CodeEditor, { readOnly: true, value: data.text, style: { marginTop: 10 } }),
                        okText: '确认',
                        cancelText: '取消',
                        okButtonProps: Object.assign({}, props),
                        onOk: () => res('self'),
                        onCancel: () => res(null)
                    });
                });
            }
            return yield p;
        });
    }
    _handleViewOp(opType, dom, extraData) {
        var _a, _b;
        return __awaiter(this, void 0, void 0, function* () {
            const data = dom.__mometa.getMometaData();
            let locationData = data;
            if ((_a = data.container) === null || _a === void 0 ? void 0 : _a.isFirstElement) {
                locationData = data.container;
            }
            switch (opType) {
                case 'move-dom': {
                    const { direction, toDom } = extraData;
                    const toData = toDom.__mometa.getMometaData();
                    const common = {
                        filename: data.filename,
                        relativeFilename: data.relativeFilename,
                        start: data.start,
                        end: data.end,
                        text: data.text
                    };
                    if (direction === 'up' || direction === 'down') {
                        return this.submitOperation({
                            type: OpType.MOVE_NODE,
                            preload: Object.assign(Object.assign({}, common), { data: {
                                    to: direction === 'up' ? toData.start : toData.end
                                } })
                        });
                    }
                    else if (direction === 'child') {
                        return this.submitOperation({
                            type: OpType.MOVE_NODE,
                            preload: Object.assign(Object.assign({}, common), { data: {
                                    to: toData.innerEnd
                                } })
                        });
                    }
                    break;
                }
                case 'insert-asset': {
                    const { asset, direction } = extraData;
                    if (direction === 'up' || direction === 'down') {
                        return this.submitOperation({
                            type: OpType.INSERT_NODE,
                            preload: {
                                filename: data.filename,
                                relativeFilename: data.relativeFilename,
                                to: direction === 'up' ? data.start : data.end,
                                data: {
                                    material: asset,
                                    wrap: data.isFirst ? getReactWrap(direction === 'down' ? data.start : data.end) : undefined
                                }
                            }
                        });
                    }
                    else if (direction === 'child') {
                        return this.submitOperation({
                            type: OpType.INSERT_NODE,
                            preload: {
                                relativeFilename: data.relativeFilename,
                                filename: data.filename,
                                to: data.innerEnd,
                                data: {
                                    material: asset
                                }
                            }
                        });
                    }
                    break;
                }
                case 'del': {
                    const result = yield this.confirmWhich(dom, '删除', { danger: true });
                    if (result === 'self') {
                        return this.submitOperation({
                            type: OpType.REPLACE_NODE,
                            preload: Object.assign(Object.assign({}, data), { data: {
                                    newText: data.isFirst ? 'null' : ''
                                } })
                        }, '删除');
                    }
                    else if (result === 'container') {
                        return this.submitOperation({
                            type: OpType.DEL,
                            preload: createPreload(data, data.container)
                        });
                    }
                    break;
                }
                case 'up':
                case 'down': {
                    let to = opType === 'up' ? data.previousSibling.start : data.nextSibling.end;
                    return this.submitOperation({
                        type: OpType.MOVE_NODE,
                        preload: createPreload(data, Object.assign(Object.assign({}, locationData), { 
                            // @ts-ignore
                            data: {
                                to
                            } }))
                    });
                }
                case 'copy': {
                    let result;
                    if ((_b = data.container) === null || _b === void 0 ? void 0 : _b.isFirstElement) {
                        result = yield this.confirmWhich(dom, '复制');
                    }
                    else {
                        result = 'self';
                    }
                    if (result === 'container') {
                        return this.submitOperation({
                            type: OpType.INSERT_NODE,
                            preload: createPreload(data, {
                                to: locationData.end,
                                data: {
                                    newText: locationData.text
                                }
                            })
                        }, '复制');
                    }
                    else if (result === 'self') {
                        return this.submitOperation({
                            type: OpType.INSERT_NODE,
                            preload: createPreload(data, {
                                to: data.end,
                                data: {
                                    newText: data.text,
                                    wrap: data.isFirst ? getReactWrap(data.start) : undefined
                                }
                            })
                        }, '复制');
                    }
                }
            }
        });
    }
}
export default function createApi(apiBaseURL) {
    return new ApiServerPack(apiBaseURL);
}
//# sourceMappingURL=create-api.js.map