import {
  Controller,
  Get,
  Post,
  Put,
  Param,
  Body,
  Query,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import { SettlementService } from '@/modules/shared/finance/settlement.service';
import { JwtAuthGuard, RolesGuard } from '@/common';
import { Roles } from '@/common/decorators/roles.decorator';
import {
  QueryMerchantSettlementDto,
  ManualSettlementDto,
  ApproveSettlementDto,
  RejectSettlementDto,
} from '@/modules/shared/finance/dto/settlement.dto';

@ApiTags('结算管理(管理员)')
@Controller('admin/finance/settlements')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('admin')
@ApiBearerAuth()
export class SettlementAdminController {
  constructor(private readonly settlementService: SettlementService) {}

  @Get()
  @ApiOperation({ summary: '查询所有结算记录' })
  async getSettlements(@Query() dto: QueryMerchantSettlementDto) {
    return this.settlementService.getSettlements({
      merchantId: dto.merchantId,
      status: dto.status,
      startDate: dto.startDate,
      endDate: dto.endDate,
      page: dto.page,
      pageSize: dto.pageSize,
    });
  }

  @Get('preview-weekly')
  @ApiOperation({ summary: '预览周结算数据' })
  async previewWeeklySettlement() {
    return this.settlementService.previewWeeklySettlement();
  }

  @Get(':id')
  @ApiOperation({ summary: '查询结算详情' })
  async getSettlementDetail(@Param('id') id: number) {
    return this.settlementService.getSettlementDetail(id);
  }

  @Get(':id/items')
  @ApiOperation({ summary: '查询结算明细' })
  async getSettlementItems(
    @Param('id') id: number,
    @Query('page') page: number = 1,
    @Query('pageSize') pageSize: number = 10,
  ) {
    const settlement = await this.settlementService.getSettlementDetail(id);

    // 分页处理
    const items = settlement.items || [];
    const total = items.length;
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const paginatedItems = items.slice(start, end);

    return {
      items: paginatedItems,
      total,
      page,
      pageSize
    };
  }

  @Post('manual')
  @ApiOperation({ summary: '手动生成结算单（指定商家和周期）' })
  async manualSettlement(@Body() dto: ManualSettlementDto) {
    return this.settlementService.manualSettlement({
      merchantId: dto.merchantId,
      periodStart: dto.periodStart,
      periodEnd: dto.periodEnd,
    });
  }

  @Post('execute-weekly')
  @ApiOperation({ summary: '手动执行周结算（所有商家）' })
  async executeWeeklySettlement() {
    await this.settlementService.handleWeeklySettlement();
    return { message: '周结算任务已执行完成' };
  }

  @Put(':id/approve')
  @ApiOperation({ summary: '审核通过结算单' })
  async approveSettlement(
    @Param('id') id: number,
    @Body() dto: ApproveSettlementDto,
  ) {
    // TODO: 实现审核通过逻辑（如果需要审核流程）
    return { message: '当前结算单自动结算，无需审核' };
  }

  @Put(':id/reject')
  @ApiOperation({ summary: '拒绝结算单' })
  async rejectSettlement(
    @Param('id') id: number,
    @Body() dto: RejectSettlementDto,
  ) {
    // TODO: 实现拒绝逻辑（如果需要审核流程）
    return { message: '当前结算单自动结算，无需审核' };
  }
}
