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 { CreatePageResourceDto } from '../../generated/pageResource/dto/create-pageResource.dto';
import {
  EffectedCount,
  PageResourceFindManyArgs,
  PageResourceWhereSelect,
  UploudResponse,
} from '../../generated/pageResource/dto/pageResource-types.dto';
import { UpdatePageResourceDto } from '../../generated/pageResource/dto/update-pageResource.dto';
import { PageResourceEntity } from '../../generated/pageResource/entities/pageResource.entity';
import { PageResourceService } from './pageResource.service';

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

@UseGuards(ACGuard)
@Controller('pageResource')
@ApiTags('pageResource')
export class PageResourceController {
  constructor(
    private readonly pageResourceService: PageResourceService,
    private readonly config: ConfigService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

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

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

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

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

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

    // 其他个性化逻辑
    */

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

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

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

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