import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Inject, Post } from '@midwayjs/core';
import { AuditOrderEntity } from '../../entity/order';
import { AuditOrderDetailEntity } from '../../entity/order_detail';
import { AuditOrderService } from '../../service/order';
import { AuditStatsService } from '../../service/stats';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';

/**
 * 审核订单管理 API（后台管理接口）
 */
@CoolController({
  api: ['info', 'list', 'page'],
  entity: AuditOrderEntity,
  pageQueryOp: {
    keyWordLikeFields: ['a.orderNo', 'a.remark', 'a.cardName', 'a.phone', 'a.carFrame', 'a.carPlate', 'a.policyNo', 'a.dealerCode', 'a.factoryName'],
    fieldEq: ['a.orderType', 'a.status', 'a.oemId', 'a.agentId', 'a.auditDecision', 'a.insuranceCompany', 'a.orderSource'],
    // 支持时间范围查询
    where: async (ctx) => {
      const conditions: string[] = [];
      const params: any = {};
      if (ctx.request.body?.startTime) {
        conditions.push('a.createTime >= :startTime');
        params.startTime = ctx.request.body.startTime;
      }
      if (ctx.request.body?.endTime) {
        conditions.push('a.createTime <= :endTime');
        params.endTime = ctx.request.body.endTime;
      }
      return conditions.length > 0
        ? [conditions.join(' AND '), params]
        : undefined;
    },
  },
})
export class AdminAuditOrderController extends BaseController {
  @Inject()
  auditOrderService: AuditOrderService;

  @Inject()
  auditStatsService: AuditStatsService;

  @InjectEntityModel(AuditOrderEntity)
  auditOrderEntity: Repository<AuditOrderEntity>;

  @InjectEntityModel(AuditOrderDetailEntity)
  auditOrderDetailEntity: Repository<AuditOrderDetailEntity>;

  /**
   * 删除审核订单（同时删除关联明细）
   */
  @Post('/remove', { summary: '删除审核订单' })
  async remove(@Body('ids') ids: number[]) {
    if (!ids || ids.length === 0) {
      return this.fail('ids不能为空');
    }
    // 先删明细
    await this.auditOrderDetailEntity
      .createQueryBuilder()
      .delete()
      .where('orderId IN (:...ids)', { ids })
      .execute();
    // 再删主表
    await this.auditOrderEntity.delete(ids);
    return this.ok();
  }

  /**
   * 获取审核订单详情（含步骤明细）
   */
  @Post('/detail', { summary: '审核详情（含步骤明细）' })
  async detail(@Body('id') id: number) {
    if (!id) {
      return this.fail('id不能为空');
    }

    // 直接用orderId查询明细
    const details = await this.auditOrderDetailEntity.find({
      where: { orderId: id },
      order: { createTime: 'ASC' },
    });

    return this.ok({ id, details });
  }

  /**
   * 重新审核
   */
  @Post('/retry', { summary: '重新审核' })
  async retry(@Body('id') id: number) {
    if (!id) {
      return this.fail('id不能为空');
    }
    try {
      await this.auditOrderService.retryAudit(id);
      return this.ok();
    } catch (e) {
      return this.fail(e.message);
    }
  }

  /**
   * 人工复审
   */
  @Post('/manual', { summary: '人工复审' })
  async manual(
    @Body('id') id: number,
    @Body('status') status: 'approved' | 'rejected',
    @Body('remark') remark: string
  ) {
    if (!id || !status) {
      return this.fail('参数不完整');
    }
    try {
      await this.auditOrderService.manualReview(id, status, remark || '');
      return this.ok();
    } catch (e) {
      return this.fail(e.message);
    }
  }

  /**
   * 审核统计
   */
  @Post('/stats', { summary: '审核统计' })
  async stats(
    @Body('startTime') startTime?: string,
    @Body('endTime') endTime?: string
  ) {
    const result = await this.auditOrderService.getStats({
      start: startTime,
      end: endTime,
    });
    return this.ok(result);
  }

  /**
   * 经营数据综合概览
   */
  @Post('/statsOverview', { summary: '经营数据综合概览' })
  async statsOverview(@Body() body: any) {
    const result = await this.auditStatsService.getOverview(body || {});
    return this.ok(result);
  }

  /**
   * 按产品维度统计
   */
  @Post('/statsByProduct', { summary: '按产品统计' })
  async statsByProduct(@Body() body: any) {
    const result = await this.auditStatsService.statsByProduct(body || {});
    return this.ok(result);
  }

  /**
   * 按门店维度统计
   */
  @Post('/statsByDealer', { summary: '按门店统计' })
  async statsByDealer(@Body() body: any) {
    const result = await this.auditStatsService.statsByDealer(body || {});
    return this.ok(result);
  }

  /**
   * 按车企维度统计
   */
  @Post('/statsByOem', { summary: '按车企统计' })
  async statsByOem(@Body() body: any) {
    const result = await this.auditStatsService.statsByOem(body || {});
    return this.ok(result);
  }

  /**
   * 按保险公司维度统计
   */
  @Post('/statsByInsurance', { summary: '按保险公司统计' })
  async statsByInsurance(@Body() body: any) {
    const result = await this.auditStatsService.statsByInsurance(body || {});
    return this.ok(result);
  }

  /**
   * 获取筛选下拉选项
   */
  @Post('/filterOptions', { summary: '获取筛选选项' })
  async filterOptions() {
    const result = await this.auditStatsService.getFilterOptions();
    return this.ok(result);
  }

  /**
   * 远程搜索门店
   */
  @Post('/searchDealers', { summary: '搜索门店' })
  async searchDealers(@Body('keyword') keyword: string) {
    const result = await this.auditStatsService.searchDealers(keyword || '');
    return this.ok(result);
  }

  /**
   * 远程搜索产品
   */
  @Post('/searchProducts', { summary: '搜索产品' })
  async searchProducts(@Body('keyword') keyword: string) {
    const result = await this.auditStatsService.searchProducts(keyword || '');
    return this.ok(result);
  }

  /**
   * 导出数据
   */
  @Post('/exportData', { summary: '导出统计数据' })
  async exportData(@Body() body: any) {
    const { dimension, ...query } = body || {};
    const result = await this.auditStatsService.exportData(query, dimension || 'product');
    return this.ok(result);
  }
}
