import { Config, Inject, Provide } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { ExportMission } from '../entity/exportMission.entity';
import { BaseServiceV2 } from '../frame/BaseServiceV2';
import Axios from 'axios';
import { cloneDeep, get, head, isArray } from 'lodash';
import { User } from '../entity/system/user.entity';
import { Admin } from '../entity/system/admin.entity';
import { AsyncExportService } from './asyncExport.service';

@Provide()
export class ExportMissionService extends BaseServiceV2 {
  @InjectEntityModel(ExportMission)
  model: Repository<ExportMission>;

  @InjectEntityModel(User)
  user: Repository<User>;
  @InjectEntityModel(Admin)
  admin: Repository<Admin>;

  @Inject()
  aeService: AsyncExportService;

  @Config('modulesConfig.mq')
  mqServiceHttpPrefix: any;

  async dealData(data) {
    let list = [];
    const returnData = [];
    const isArr = isArray(data);
    if (isArr) list = data;
    else list.push(data);
    for (const i of list) {
      const obj = cloneDeep(i);
      const { user_type, user } = i;
      let model;
      if (user_type === 'ADMIN') {
        obj.user_type_name = '管理员';
        model = this.admin;
      } else if (user_type === 'USER') {
        obj.user_type_name = '用户';
        model = this.user;
      }
      if (!model) continue;
      const userInfo = await model.createQueryBuilder().where(`"id" =:id`, { id: user }).getOne();
      if (!userInfo) continue;
      obj.user_name = get(userInfo, 'nick_name');
      const config = get(i, 'config');
      if (config) {
        const table = get(config, 'table');
        if (table) {
          const table_name = this.aeService.getModelName(table);
          obj.table_name = table_name;
        }
      }
      returnData.push(obj);
    }
    if (isArr) return returnData;
    else return head(returnData);
  }

  /**
   * 发送mq消息
   * @param id 任务id
   */
  async toSendMq(id) {
    const url = `${this.mqServiceHttpPrefix}/mission`;
    const body = { id };
    try {
      await Axios.post(url, body, { responseType: 'json' });
    } catch (error) {
      console.log(error);
    }
  }
}
