import { Controller, Get, Body, Post, Query } from '@nestjs/common';
import { TokenData } from 'src/common/decorator/token-data.decorator';
import { TokenDataEntity } from 'src/common/entities/token-data.entity';
import { DataSource } from 'typeorm';
import { ReportData } from './entities/report-data.entity';

@Controller('statistic')
export class StatisticController {
  constructor(private dataSource: DataSource) {}

  @Get()
  async findData(@Query() query, @TokenData() token: TokenDataEntity) {
    try {
      const { handler } = await import(
        `./service/${
          { 1: 'admin', 2: 'teacher', 3: 'student' }[token.baseRole]
        }/${query.module}/${query.fun}.js`
      );
      return handler(this.dataSource, { query, user: token });
    } catch (error) {
      console.error(error);

      throw '出错了，请稍后再试';
    }
  }

  @Post('reportData')
  async reportData(
    @Body() data: ReportData,
    @TokenData() token: TokenDataEntity,
  ) {
    const currentTime = new Date();
    if (data.id) {
      this.dataSource
        .getRepository(ReportData)
        .update(data.id, { ...data, endTime: currentTime });
    } else {
      const { raw } = await this.dataSource.getRepository(ReportData).insert({
        ...data,
        creator: token.userId,
        createTime: currentTime,
        endTime: currentTime,
      });
      data.id = raw.insertId;
    }

    return data.id;
  }
}
