import { AdminJwtAuthGuard } from '@api/modules/auth/admin/jwt.guard';
import { Roles } from '@api/modules/auth/admin/roles.decorator';
import { RolesGuard } from '@api/modules/auth/admin/roles.guard';
import { Body, Controller, Get, Header, Param, ParseIntPipe, Patch, Post, Query, Req, Res, UseGuards } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { plainToInstance } from 'class-transformer';
import { Request, Response } from 'express';
import { canViewCar } from '@api/modules/auth/admin/car-view-admin.guard';
import {
  AssignMemberDto,
  GetB2cOrderDetailListDto,
  GetB2cOrderDetailListResponseDto,
  UpdateB2cOrderDetailDto,
} from './b2c-analyze-admin.dto';
import { B2cAnalyzeAdminService } from './b2c-analyze-admin.service';

@ApiTags('[관리자] B2C 분석 관리')
@UseGuards(AdminJwtAuthGuard, RolesGuard)
@Roles('admin')
@Controller('admin/b2c-analyze')
export class B2cAnalyzeAdminController {
  constructor(private b2cAnalyzeAdminService: B2cAnalyzeAdminService) {}

  @ApiOperation({
    summary: `B2C 분석 목록,검색`,
  })
  @Get()
  @ApiOkResponse({ type: GetB2cOrderDetailListResponseDto })
  async getB2cOrderDetailList(@Query() query: GetB2cOrderDetailListDto) {
    const data = await this.b2cAnalyzeAdminService.getB2cOrderDetailList(query);
    return plainToInstance(GetB2cOrderDetailListResponseDto, data, {
      excludeExtraneousValues: true,
    });
  }

  @Get('download')
  @ApiOperation({
    summary: '엑셀다운로드',
    description: '모든 B2C 분석 목록을 다운로드합니다.',
  })
  @Header(
    'Content-Type',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  )
  @Header(
    'Content-Disposition',
    `attachment;filename*=utf-8''${encodeURIComponent('B2C분석목록')}.xlsx`,
  )
  async downloadB2cOrderDetailList(
    @Query() query: GetB2cOrderDetailListDto,
    @Res({ passthrough: true }) res: Response,
  ) {
    await this.b2cAnalyzeAdminService.downloadB2cOrderDetailList(query, res);
    return;
  }

  @Get(':bodId/download')
  @ApiOperation({
    summary: '원본데이터 엑셀다운로드',
    description: `해당 분석자료의 원본진료정보를 다운로드합니다.
                  ** 30일 보관후 삭제되므로 30일이 지난 분석자료의 경우 다운로드 버튼을 비노출처리바랍니다.`,
  })
  async downloadOriginalList(
    @Param('bodId', ParseIntPipe) bodId: number,
    @Res({ passthrough: true }) res: Response,
    @Req() req: Request,
  ) {
    await this.b2cAnalyzeAdminService.downloadOriginalList(
      bodId,
      res,
      canViewCar(req['admin']),
    );
    return;
  }

  @Get(':bodId')
  @ApiOperation({
    summary: 'B2C 분석 상세 조회',
  })
  @ApiOkResponse()
  async getB2cOrderDetail(@Param('bodId', ParseIntPipe) bodId: number) {
    const data = await this.b2cAnalyzeAdminService.getB2cOrderDetail(bodId);
    return data;
  }

  @Get('agency/:agcId/members')
  @ApiOperation({
    summary: '기업 회원 목록 조회',
    description: '담당자 지정을 위한 해당 기업의 회원 목록을 조회합니다.',
  })
  @ApiOkResponse()
  async getAgencyMembers(@Param('agcId', ParseIntPipe) agcId: number) {
    const members = await this.b2cAnalyzeAdminService.getAgencyMembers(agcId);
    return {
      success: true,
      list: members,
    };
  }

  @Patch(':bodId')
  @ApiOperation({
    summary: 'B2C 분석 수정',
    description: '노출여부를 수정합니다.',
  })
  @ApiOkResponse()
  async updateB2cOrderDetail(
    @Param('bodId', ParseIntPipe) bodId: number,
    @Body() dto: UpdateB2cOrderDetailDto,
  ) {
    await this.b2cAnalyzeAdminService.updateB2cOrderDetail(bodId, dto);
    return {
      success: true,
      message: '수정이 완료되었습니다.',
    };
  }

  @Post(':bodId/assign')
  @ApiOperation({
    summary: '담당자 지정',
    description: 'B2C 분석 건에 담당 회원을 지정합니다.',
  })
  @ApiOkResponse()
  async assignMember(
    @Param('bodId', ParseIntPipe) bodId: number,
    @Body() dto: AssignMemberDto,
  ) {
    await this.b2cAnalyzeAdminService.assignMember(bodId, dto.memberId);
    return {
      success: true,
      message: '담당자 지정이 완료되었습니다.',
    };
  }
}
