import {
  BaseController,
  CoolController,
  CoolTag,
  CoolUrlTag,
  TagTypes,
} from '@cool-midway/core';
import { Body, Inject, Post } from '@midwayjs/core';
import { PassThrough } from 'stream';
import { FlowRunService } from '../../service/run';

/**
 * 流程运行
 */
@CoolUrlTag()
@CoolController()
export class OpenFlowRunController extends BaseController {
  @Inject()
  flowRunService: FlowRunService;

  @Inject()
  ctx;

  @CoolTag(TagTypes.IGNORE_TOKEN)
  @Post('/invoke', { summary: '调用' })
  async invoke(
    @Body('params') params: any,
    @Body('label') label: string,
    @Body('stream') stream = false
  ) {
    if (stream) {
      // 设置响应头
      this.ctx.set('Content-Type', 'text/event-stream');
      this.ctx.set('Cache-Control', 'no-cache');
      this.ctx.set('Connection', 'keep-alive');

      const stream = new PassThrough();
      // 发送数据
      const send = (data: any) => {
        stream.write(`data:${JSON.stringify(data)}\n\n`);
      };
      const result = await this.flowRunService.invoke(params, label, true);
      const output = async () => {
        // 流式输出
        for await (const chunk of result.stream) {
          send({ isEnd: false, content: chunk.toString() });
        }
        send({ isEnd: true });
        this.ctx.res.end();
      };
      output();
      this.ctx.status = 200;
      this.ctx.body = stream;
    } else {
      return this.ok(await this.flowRunService.invoke(params, label));
    }
  }
}
