import { ALL, Body, Controller, Get, Inject, Post, Provide, Query } from "@midwayjs/core";
import { CommonException, Constants, CrudController } from "@certd/lib-server";
import { AuthService } from "../../../modules/sys/authority/service/auth-service.js";
import { CertInfoService } from "../../../modules/monitor/index.js";
import { PipelineService } from "../../../modules/pipeline/service/pipeline-service.js";
import { SelectQueryBuilder } from "typeorm";
import { logger } from "@certd/basic";
import fs from "fs";

/**
 */
@Provide()
@Controller('/api/monitor/cert')
export class CertInfoController extends CrudController<CertInfoService> {
  @Inject()
  service: CertInfoService;
  @Inject()
  authService: AuthService;
  @Inject()
  pipelineService: PipelineService;

  getService(): CertInfoService {
    return this.service;
  }

  @Post('/page', { summary: Constants.per.authOnly })
  async page(@Body(ALL) body: any) {
    body.query = body.query ?? {};
    body.query.userId = this.getUserId();
    const domains = body.query?.domains;
    delete body.query.domains;
    const res = await this.service.page({
      query: body.query,
      page: body.page,
      sort: body.sort,
      buildQuery: (bq) => {
        if (domains) {
          bq.andWhere('domains like :domains', { domains: `%${domains}%` });
        }
      }
    });

    const records = res.records;
    const pipelineIds = records.map(r => r.pipelineId);
    const pipelines = await this.pipelineService.getSimplePipelines(pipelineIds);
    const pMap = new Map();
    for (const p of pipelines) {
      pMap.set(p.id, p);
    }
    for (const record of records) {
      record.pipeline = pMap.get(record.pipelineId);
    }
    return this.ok(res);
  }

  @Post('/list', { summary: Constants.per.authOnly })
  async list(@Body(ALL) body: any) {
    body.query = body.query ?? {};
    body.query.userId = this.getUserId();
    return await super.list(body);
  }


  @Post('/getOptionsByIds', { summary: Constants.per.authOnly })
  async getOptionsByIds(@Body(ALL) body: {ids:any[]}) {

    const list = await this.service.list({
      query:{
        userId: this.getUserId(),
      },
      buildQuery: (bq: SelectQueryBuilder<any>) => {
        bq.andWhere('id in (:...ids)', { ids: body.ids });
      }
    })

    const safeList =list.map((item:any) => {
      const domainsArr = item.domains? item.domains.split(',') : [];
      return {
        id: item.id,
        domain: item.domain,
        domains:domainsArr,
        userId: item.userId,
      }
    })
    return this.ok(safeList);
  }

  @Post('/add', { summary: Constants.per.authOnly })
  async add(@Body(ALL) bean: any) {
    bean.userId = this.getUserId();
    return await super.add(bean);
  }

  @Post('/update', { summary: Constants.per.authOnly })
  async update(@Body(ALL) bean) {
    await this.service.checkUserId(bean.id, this.getUserId());
    delete bean.userId;
    return await super.update(bean);
  }
  @Post('/info', { summary: Constants.per.authOnly })
  async info(@Query('id') id: number) {
    await this.service.checkUserId(id, this.getUserId());
    return await super.info(id);
  }

  @Post('/delete', { summary: Constants.per.authOnly })
  async delete(@Query('id') id: number) {
    await this.service.checkUserId(id, this.getUserId());
    return await super.delete(id);
  }

  @Post('/all', { summary: Constants.per.authOnly })
  async all() {
    const list: any = await this.service.find({
      where: {
        userId: this.getUserId(),
      },
    });
    return this.ok(list);
  }



  @Post('/getCert', { summary: Constants.per.authOnly })
  async getCert(@Query('id') id: number) {
    await this.service.checkUserId(id, this.getUserId());
    const certInfoEntity = await this.service.info(id);
    const certInfo = JSON.parse(certInfoEntity.certInfo);
    return this.ok(certInfo);
  }

  @Get('/download', { summary: Constants.per.authOnly })
  async download(@Query('id') id: number) {
    const certInfo = await this.service.info(id)
    if (certInfo == null) {
      throw new CommonException('file not found');
    }
    if (certInfo.userId !== this.getUserId()) {
      throw new CommonException('file not found');
    }
    // koa send file
    // 下载文件的名称
    // const filename = file.filename;
    // 要下载的文件的完整路径
    const path = certInfo.certFile;
    if (!path) {
      throw new CommonException('file not found');
    }
    logger.info(`download:${path}`);
    // 以流的形式下载文件
    this.ctx.attachment(path);
    this.ctx.set('Content-Type', 'application/octet-stream');

    return fs.createReadStream(path);
  }
}
