import { Controller, Post, Body, Inject, Get, Query } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { get, isObject, omit, pick } from 'lodash';
import { ErrorCode, ServiceError } from '../error/service.error';
import { ExportMissionService } from '../service/exportMission.service';
import { AsyncExportService } from '../service/asyncExport.service';
import { ApiTags } from '@midwayjs/swagger';
const namePrefix = '导出任务';
@ApiTags(['导出任务'])
@Controller('/asyncExport', { tagName: namePrefix })
export class AsyncExportController {
  @Inject()
  ctx: Context;
  @Inject()
  missionService: ExportMissionService;
  @Inject()
  aeService: AsyncExportService;

  @Get('/')
  async query(@Query() query: object) {
    const qobj: any = omit(query, ['skip', 'limit']);
    const others = pick(query, ['skip', 'limit']);
    const userInfo = get(this.ctx, 'user');
    if (!userInfo || !get(userInfo, 'id')) throw new ServiceError(ErrorCode.NOT_LOGIN);
    const user = get(userInfo, 'id');
    const is_super = get(userInfo, 'is_super');
    if (is_super !== '0') {
      const role = get(user, 'role', []);
      const isAdmin = role.find(f => f === 'Admin');
      let user_type = '';
      if (isAdmin) user_type = 'ADMIN';
      else user_type = 'USER';
      qobj.user = user;
      qobj.user_type = user_type;
    }
    const { data, total } = await this.missionService.query(qobj, others);
    const nd = await this.missionService.dealData(data);
    return { data: nd, total };
  }

  @Post('/reExecute', { routerName: `重执行${namePrefix}` })
  async reExecute(@Body('id') id: number) {
    await this.missionService.toSendMq(id);
  }

  @Post('/', { routerName: `创建${namePrefix}` })
  async index(@Body() body: object) {
    const user = get(this.ctx, 'user');
    if (!user || !get(user, 'id')) throw new ServiceError(ErrorCode.NOT_LOGIN);
    const table = get(body, 'table');
    const config = get(body, 'config');
    if (!table || !config) throw new ServiceError(ErrorCode.BODY_ERROR);
    const query = omit(body, ['table', 'config']);
    // 检查 查询范围内有没有数据,没有数据直接返回没数据: 无法导出会抛异常中断程序
    await this.aeService.checkHaveDataInQuery(table, query);
    // 下达任务,1.创建任务数据; 2.创建mq任务; 3.消费mq任务进行导出; 4.更新任务数据
    // 1.创建任务数据
    const role = get(user, 'role', []);
    const isAdmin = role.find(f => f === 'Admin');
    let user_type = '';
    if (isAdmin) user_type = 'ADMIN';
    else user_type = 'USER';
    const data = {
      user: get(user, 'id'),
      user_type,
      config: { table, config, query },
      progress: 0,
    };
    const res = await this.missionService.create(data);
    // 2.创建mq任务
    await this.missionService.toSendMq(get(res, 'id'));
  }
}
