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 { CreateRoleResourceDto } from '../../generated/roleResource/dto/create-roleResource.dto';
import {
  EffectedCount,
  RoleResourceFindManyArgs,
  RoleResourceWhereSelect,
  UploudResponse,
} from '../../generated/roleResource/dto/roleResource-types.dto';
import { UpdateRoleResourceDto } from '../../generated/roleResource/dto/update-roleResource.dto';
import { RoleResourceEntity } from '../../generated/roleResource/entities/roleResource.entity';
import { RoleResourceService } from './roleResource.service';

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

@UseGuards(ACGuard)
@Controller('roleResource')
@ApiTags('roleResource')
export class RoleResourceController {
  constructor(
    private readonly roleResourceService: RoleResourceService,
    private readonly config: ConfigService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  @Post('createOne')
  @UseRoles({
    resource: 'roleResource',
    action: 'create',
    possession: 'any',
  })
  @ApiCreatedResponse({ type: RoleResourceEntity })
  async createOne(
    @Body() body: CreateRoleResourceDto,
    @ACAttrFilter() acAttrFilter,
    @Req() request: Request & { user: UserType },
  ) {
    body.creator = request.user.username;
    return new RoleResourceEntity(
      await this.roleResourceService.createOne({ data: acAttrFilter(body) }),
    );
  }

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

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

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

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

    // 其他个性化逻辑
    */

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

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

  @Post('upload')
  @UseRoles({
    resource: 'roleResource',
    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'] + '/roleResource/',
    );

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