import { Body, Controller, Get, Inject, Param, Post } from '@midwayjs/core';
import { ExportConfigService } from '../service/exportConfig.service';
import { get, pick, upperFirst } from 'lodash';
import { AsyncExportService } from '../service/asyncExport.service';

@Controller('/ec')
export class ExportConfigController {
  @Inject()
  ecService: ExportConfigService;
  @Inject()
  aeService: AsyncExportService;

  @Get('/user/:table')
  async userFetch(@Param('table') table: string) {
    table = upperFirst(table);
    let data: any = await this.ecService.fetch({ table });
    if (!data) {
      const filters = ['id', 'created_time', , 'update_time', '__v'];
      const cols = await this.ecService.getModelColumns(table, filters);
      data = { config: cols };
    }
    let config = get(data, 'config', []);
    config = config.map(i => pick(i, ['column', 'zh']));
    data.config = config;
    return data;
  }

  @Get('/:table')
  async fetch(@Param('table') table: string) {
    table = upperFirst(table);
    let data: any = await this.ecService.fetch({ table });
    if (!data) {
      const filters = ['id', 'created_time', , 'update_time', '__v'];
      const cols = await this.ecService.getModelColumns(table, filters);
      data = { config: cols };
    }
    return data;
  }

  /**修改,根据表名修改 */
  @Post('/:table')
  async udpate(@Param('table') table: string, @Body() body: object) {
    table = upperFirst(table);
    const res = await this.ecService.update({ table }, body);
    return res;
  }

  @Get('/dict')
  async getDict() {
    const tableList = this.aeService.getDict_tables();
    const typeList = this.ecService.getDict_type();
    const sourceList = this.ecService.getDict_source();
    return { tableList, typeList, sourceList };
  }
}
