"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.MagicController = void 0;
const http_1 = require("@midwayjs/core/dist/error/http");
const decorator_1 = require("@midwayjs/decorator");
const entity_1 = require("../entity");
const magic_1 = require("../magic");
const middleware_1 = require("../middleware");
const validate_1 = require("@midwayjs/validate");
let MagicController = class MagicController {
    /**
     * 获取所有资源
     */
    async resource() {
        return await magic_1.MagicProvideContainer.getAllResource();
    }
    /**
     * 导入
     * @param files 文件
     * @param fields 表单字段
     */
    async importResource(files, fields) {
        if (files == null || files.length === 0) {
            throw new http_1.BadRequestError('导入文件不能为空');
        }
        if (!files[0].filename.endsWith('.zip')) {
            throw new http_1.BadRequestError('请上传zip文件');
        }
        if (fields == null ||
            (fields.mode != 'increment' && fields.mode != 'full')) {
            throw new http_1.BadRequestError('请选择增量导入还是全量导入');
        }
        const filePath = files[0].data;
        await this.magicResourceService.importResourceZip(filePath, fields.mode);
    }
    /**
     * 导出
     * @param body
     */
    async exportResource(body) {
        var _a;
        if (((_a = body === null || body === void 0 ? void 0 : body.ids) === null || _a === void 0 ? void 0 : _a.length) > 0) {
            return this.response.download(await this.magicResourceService.exportResourceZip(body === null || body === void 0 ? void 0 : body.ids), 'magic-node.zip');
        }
        throw new http_1.BadRequestError('导出资源ID不能为空');
    }
    /**
     * 分组创建或修改
     * @param resource 资源对象
     */
    async folderSave(resource) {
        resource.isFolder = true;
        return await this.magicResourceService.saveOrUpdate(resource);
    }
    /**
     * 分组查询
     * @param type 分组类型
     * @param groupId 分组id
     */
    async folder(type, groupId = '0') {
        return await this.magicResourceService.findByGroupId(type, groupId, true);
    }
    /**
     * 删除分组
     * @param id 分组id
     */
    async folderDelete(id) {
        return await this.magicResourceService.deleteById(id);
    }
    /**
     * 资源创建或修改
     * @param resource 资源对象
     */
    async fileSave(resource) {
        resource.isFolder = false;
        if ((0, magic_1.isBlank)(resource.path)) {
            throw new http_1.BadRequestError('路径不能为空');
        }
        return await this.magicResourceService.saveOrUpdate(resource);
    }
    /**
     * 根据id查询资源
     * @param id 资源id
     */
    async fileById(id) {
        return await this.magicResourceService.findById(id);
    }
    /**
     * 根据groupId查询资源
     * @param type 资源类型
     * @param groupId 资源分组id
     */
    async fileByGroupId(type, groupId) {
        return await this.magicResourceService.findByGroupId(type, groupId);
    }
    /**
     * 删除资源
     * @param id 资源id
     */
    async filerDelete(id) {
        return await this.magicResourceService.deleteById(id);
    }
    /**
     * 测试数据源
     * @param resource
     */
    async testDataSource(resource) {
        await this.magicDataSource.testDataSource(resource);
    }
    /**
     * 运行日志
     */
    async log() {
        this.ctx.request.socket.setTimeout(0);
        this.ctx.req.socket.setNoDelay(true);
        this.ctx.req.socket.setKeepAlive(true);
        const stream = new magic_1.SSEStream();
        this.ctx.status = 200;
        this.ctx.body = stream;
        this.magicLog.addStream(stream);
        stream.on('close', () => {
            this.magicLog.removeStream(stream);
        });
    }
    /**
     * 用户登录
     * @param body
     */
    async login(body) {
        const user = this.magicConfig.security.filter(u => u.username === body.username && u.password === body.password)[0];
        if (user != null) {
            this.ctx.session.user = {
                username: user.username,
                permission: user.permission,
            };
            return user;
        }
        throw new http_1.UnauthorizedError('账号或密码错误');
    }
    /**
     * 用户登出
     */
    async logout() {
        this.ctx.session = null;
    }
    /**
     * 用户信息
     */
    async info() {
        return this.ctx.session.user;
    }
    /**
     * 类型定义
     */
    async spec() {
        const functionSpec = this.magicFunction.generateSpec();
        const dataSourceSpec = this.magicDataSource.generateSpec();
        return [functionSpec, dataSourceSpec].join('\r\n');
    }
};
__decorate([
    (0, decorator_1.Inject)(),
    __metadata("design:type", Object)
], MagicController.prototype, "ctx", void 0);
__decorate([
    (0, decorator_1.Inject)(),
    __metadata("design:type", magic_1.MagicLog)
], MagicController.prototype, "magicLog", void 0);
__decorate([
    (0, decorator_1.Inject)(),
    __metadata("design:type", magic_1.MagicDataSource)
], MagicController.prototype, "magicDataSource", void 0);
__decorate([
    (0, decorator_1.Inject)(),
    __metadata("design:type", magic_1.MagicFunction)
], MagicController.prototype, "magicFunction", void 0);
__decorate([
    (0, decorator_1.Inject)(),
    __metadata("design:type", magic_1.MagicResourceService)
], MagicController.prototype, "magicResourceService", void 0);
__decorate([
    (0, decorator_1.Config)('magic'),
    __metadata("design:type", Object)
], MagicController.prototype, "magicConfig", void 0);
__decorate([
    (0, decorator_1.Inject)(),
    __metadata("design:type", magic_1.Response)
], MagicController.prototype, "response", void 0);
__decorate([
    (0, decorator_1.Get)(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "resource", null);
__decorate([
    (0, decorator_1.Post)('/import', { middleware: [middleware_1.ReadonlyMiddleware] }),
    __param(0, (0, decorator_1.Files)()),
    __param(1, (0, decorator_1.Fields)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Array, Object]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "importResource", null);
__decorate([
    (0, decorator_1.Post)('/export'),
    __param(0, (0, decorator_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "exportResource", null);
__decorate([
    (0, decorator_1.Post)('/folder/save', { middleware: [middleware_1.ReadonlyMiddleware] }),
    (0, validate_1.Validate)(),
    __param(0, (0, decorator_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [entity_1.Resource]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "folderSave", null);
__decorate([
    (0, decorator_1.Get)('/folder/:type/:groupId'),
    __param(0, (0, decorator_1.Param)('type')),
    __param(1, (0, decorator_1.Param)('groupId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, Object]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "folder", null);
__decorate([
    (0, decorator_1.Del)('/folder/:id', { middleware: [middleware_1.ReadonlyMiddleware] }),
    __param(0, (0, decorator_1.Param)('id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "folderDelete", null);
__decorate([
    (0, decorator_1.Post)('/file/save', { middleware: [middleware_1.ReadonlyMiddleware] }),
    (0, validate_1.Validate)(),
    __param(0, (0, decorator_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [entity_1.Resource]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "fileSave", null);
__decorate([
    (0, decorator_1.Get)('/file/:id'),
    __param(0, (0, decorator_1.Param)('id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "fileById", null);
__decorate([
    (0, decorator_1.Get)('/file/:type/:groupId'),
    __param(0, (0, decorator_1.Param)('type')),
    __param(1, (0, decorator_1.Param)('groupId')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String, String]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "fileByGroupId", null);
__decorate([
    (0, decorator_1.Del)('/file/:id', { middleware: [middleware_1.ReadonlyMiddleware] }),
    __param(0, (0, decorator_1.Param)('id')),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [String]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "filerDelete", null);
__decorate([
    (0, decorator_1.Post)('/datasource/test'),
    (0, validate_1.Validate)(),
    __param(0, (0, decorator_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [entity_1.Resource]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "testDataSource", null);
__decorate([
    (0, decorator_1.Get)('/console/log'),
    (0, decorator_1.SetHeader)('Content-Type', 'text/event-stream'),
    (0, decorator_1.SetHeader)('Content-Type', 'no-cache'),
    (0, decorator_1.SetHeader)('Cache-Control', 'keep-alive'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "log", null);
__decorate([
    (0, decorator_1.Post)('/login'),
    __param(0, (0, decorator_1.Body)()),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "login", null);
__decorate([
    (0, decorator_1.Get)('/logout'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "logout", null);
__decorate([
    (0, decorator_1.Get)('/info'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "info", null);
__decorate([
    (0, decorator_1.Get)('/spec'),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", []),
    __metadata("design:returntype", Promise)
], MagicController.prototype, "spec", null);
MagicController = __decorate([
    (0, decorator_1.Controller)('/resource')
], MagicController);
exports.MagicController = MagicController;
//# sourceMappingURL=magic.controller.js.map