import { CoolController, BaseController } from '@cool-midway/core';
import { Body, Inject, Post } from '@midwayjs/core';
import { AuditConfigEntity } from '../../entity/config';
import { AuditConfigService } from '../../service/config';
import { TycmDropdownService } from '../../service/tycm_dropdown';

/**
 * 审核配置管理 API（后台管理接口）
 */
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: AuditConfigEntity,
  pageQueryOp: {
    keyWordLikeFields: [
      'a.name',
      'a.oemName',
      'a.productKeyword',
      'a.productName',
      'a.productNo',
      'a.agentName',
    ],
    fieldEq: ['a.orderType', 'a.status', 'a.oemId', 'a.carType', 'a.carPower', 'a.agentId'],
    addOrderBy: { 'a.priority': 'DESC' },
  },
})
export class AdminAuditConfigController extends BaseController {
  @Inject()
  auditConfigService: AuditConfigService;

  @Inject()
  tycmDropdownService: TycmDropdownService;

  async add() {
    const result = await super.add();
    this.auditConfigService.clearCache();
    return result;
  }

  async update() {
    const result = await super.update();
    this.auditConfigService.clearCache();
    return result;
  }

  async delete() {
    const result = await super.delete();
    this.auditConfigService.clearCache();
    return result;
  }

  /**
   * 获取所有可用的Agent列表（供下拉选择）
   */
  @Post('/agents', { summary: '获取Agent列表' })
  async agents() {
    const list = await this.auditConfigService.getAvailableAgents();
    return this.ok(list);
  }

  /**
   * 获取TYCM主机厂下拉数据
   */
  @Post('/oems', { summary: '获取TYCM主机厂列表' })
  async oems(@Body('keyword') keyword?: string) {
    try {
      const list = await this.tycmDropdownService.getOems(keyword || '');
      return this.ok(list);
    } catch (e) {
      return this.fail(e.message || '获取TYCM主机厂列表失败');
    }
  }

  /**
   * 获取TYCM父产品下拉数据
   */
  @Post('/products', { summary: '获取TYCM父产品列表' })
  async products(
    @Body('oemId') oemId: number,
    @Body('carType') carType?: string,
    @Body('carPower') carPower?: string,
    @Body('keyword') keyword?: string
  ) {
    if (!oemId) {
      return this.fail('oemId不能为空');
    }
    try {
      const list = await this.tycmDropdownService.getParentProducts({
        oemId,
        carType,
        carPower,
        keyword,
      });
      return this.ok(list);
    } catch (e) {
      return this.fail(e.message || '获取TYCM父产品列表失败');
    }
  }

  /**
   * 测试规则匹配：输入订单条件，返回会命中哪条规则
   */
  @Post('/testMatch', { summary: '测试规则匹配' })
  async testMatch(
    @Body('orderType') orderType: string,
    @Body('oemId') oemId: number,
    @Body('productName') productName: string,
    @Body('carType') carType: string,
    @Body('carPower') carPower?: string,
    @Body('productNo') productNo?: string
  ) {
    const result = await this.auditConfigService.matchConfig(
      orderType,
      oemId,
      productName,
      carType,
      carPower,
      productNo
    );
    return this.ok(result);
  }
}
