import {
  ACAttrFilter,
  ACGuard,
  ApiPaginatedResponse,
  diskStorage,
  PageDto,
  PageMetaDto,
  PageOptionsDto,
  pick,
  UserType,
} from '@gadmin2n/nest-common';
import {
  Body,
  Controller,
  Delete,
  Inject,
  NotFoundException,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Req,
  UploadedFile,
  UseGuards,
  UseInterceptors,
} from '@nestjs/common';
import {
  ApiCreatedResponse,
  ApiNotFoundResponse,
  ApiOkResponse,
  ApiTags,
} from '@nestjs/swagger';
import { Prisma } from '@prisma/client';
import { UseRoles } from 'nest-access-control';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import {
  AuditFindManyArgs,
  AuditWhereSelect,
  EffectedCount,
  UploudResponse,
} from '../../generated/audit/dto/audit-types.dto';
import { CreateAuditDto } from '../../generated/audit/dto/create-audit.dto';
import { UpdateAuditDto } from '../../generated/audit/dto/update-audit.dto';
import { AuditEntity } from '../../generated/audit/entities/audit.entity';
import { AuditService } from './audit.service';

import { ConfigService } from '@nestjs/config';
import { FileInterceptor } from '@nestjs/platform-express';
import * as path from 'path';

@UseGuards(ACGuard)
@Controller('audit')
@ApiTags('audit')
export class AuditController {
  constructor(
    private readonly auditService: AuditService,
    private readonly config: ConfigService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {
    this.logger = this.logger.child({
      file: path.basename(__filename),
    });
  }

  @Post('createOne')
  @ApiCreatedResponse({ type: AuditEntity })
  async createOne(
    @Body() body: CreateAuditDto,
    @Req() request: Request & { user: UserType },
  ) {
    body.creator = request.user.username;
    return new AuditEntity(await this.auditService.createOne({ data: body }));
  }

  @Post('findMany')
  @UseRoles({
    resource: 'audit',
    action: 'read',
    possession: 'any',
  })
  @ApiPaginatedResponse(AuditEntity)
  async findMany(
    @Body() body: AuditFindManyArgs,
    @ACAttrFilter() acAttrFilter,
  ): Promise<PageDto<AuditEntity>> {
    const { itemCount, entities } = await this.auditService.findMany(
      body as Prisma.AuditFindManyArgs,
    );
    const { skip = 0, take = 10 } = body as Prisma.AuditFindManyArgs;
    const pageOptionsDto: PageOptionsDto = { skip, take };
    const pageMetaDto = new PageMetaDto({ itemCount, pageOptionsDto });

    return new PageDto(
      entities.map((item) => new AuditEntity(acAttrFilter(item))),
      pageMetaDto,
    );
  }

  @Post('/findUnique/:id')
  @UseRoles({
    resource: 'audit',
    action: 'read',
    possession: 'any',
  })
  @ApiOkResponse({ type: AuditEntity })
  @ApiNotFoundResponse({ description: 'Cannot found this record.' })
  async findUnique(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: AuditWhereSelect,
    @ACAttrFilter() acAttrFilter,
  ) {
    const item = await this.auditService.findUnique(id, body);
    if (!item) {
      throw new NotFoundException();
    }
    return new AuditEntity(acAttrFilter(item));
  }

  @Patch('updateUnique/:id')
  @UseRoles({
    resource: 'audit',
    action: 'update',
    possession: 'any',
  })
  @ApiOkResponse({ type: AuditEntity })
  @ApiNotFoundResponse({ description: 'Cannot found this record.' })
  async updateUnique(
    @Param('id', ParseIntPipe) id: number,
    @Body() body: UpdateAuditDto,
    @ACAttrFilter() acAttrFilter,
  ) {
    /* 
    const origin = (await this.auditService.findUnique(id, {
      id: true,
      // 这里需要根据实际情况填写
    })) as AuditEntity | null;
    if (!origin) {
      throw new NotFoundException();
    }
    // 需要兼容从列表页change_value入口进来的情况，这里进来的是只有少量字段的数据
    const newBody = {
      ...origin,
      ...body,
    };

    // 其他个性化逻辑
    */

    const item = await this.auditService.updateUnique(id, acAttrFilter(body));
    return new AuditEntity(acAttrFilter(item));
  }

  @Delete('deleteUnique/:id')
  @UseRoles({
    resource: 'audit',
    action: 'delete',
    possession: 'any',
  })
  @ApiOkResponse({ type: EffectedCount })
  @ApiNotFoundResponse({ description: 'Cannot found this record.' })
  async deleteUnique(@Param('id', ParseIntPipe) id: number) {
    const res = await this.auditService.deleteUnique(id);
    if (!res.count) {
      throw new NotFoundException();
    }
    return res;
  }

  @Post('upload')
  @UseRoles({
    resource: 'audit',
    action: 'create',
    possession: 'any',
  })
  @ApiCreatedResponse({ type: UploudResponse })
  @UseInterceptors(FileInterceptor('file'))
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    const fileName = await diskStorage(
      file,
      this.config.get('media')['rootDir'] + '/audit/',
    );

    return {
      ...pick(file, ['mimetype', 'originalname', 'size']),
      url: this.config.get('media')['address'] + '/audit/' + fileName,
      name: fileName,
    };
  }
}
