import { Init, Inject, Provide } from '@midwayjs/decorator';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Equal, Repository } from 'typeorm';
import { FlowConfigEntity } from '../entity/config';
import { AllConfig, NodeConfig, NodeTypeKey } from '../nodes';
import { KnowDataTypeService } from '../../know/service/data/type';

/**
 * 流程配置
 */
@Provide()
export class FlowConfigService extends BaseService {
  @InjectEntityModel(FlowConfigEntity)
  flowConfigEntity: Repository<FlowConfigEntity>;

  @Inject()
  knowDataTypeService: KnowDataTypeService;

  @Inject()
  ctx;

  @Init()
  async init() {
    await super.init();
    this.setEntity(this.flowConfigEntity);
  }

  /**
   * 获得配置
   * @param node 节点
   * @param type 类型
   */
  async config(node: NodeTypeKey, type?: string) {
    // 知识库
    if (node == 'know') {
      return {
        knows: await this.knowDataTypeService.getKnows(),
      };
    }
    return type ? NodeConfig[node][type] : NodeConfig[node];
  }

  /**
   * 所有配置
   * @returns
   */
  async all() {
    return AllConfig;
  }

  /**
   * 获得配置
   * @param configId
   * @returns
   */
  async getOptions(configId: number) {
    const config = await this.flowConfigEntity.findOneBy({
      id: Equal(configId),
    });
    return config?.options;
  }

  /**
   * 通过名称获取配置
   * @param node 类型
   * @param type 类型
   * @returns
   */
  async getByNode(node: string, type?: string): Promise<FlowConfigEntity[]> {
    const find = await this.flowConfigEntity.createQueryBuilder('a');
    if (type) {
      find.where('a.type = :type', { type });
    }
    if (node) {
      find.andWhere('a.node = :node', { node });
    }
    return await find.getMany();
  }
}
