import { requestClient } from '#/api/request';

/** 金方库管理 API */
const prefix = 'golden-formula/';

/** 金方来源字典 API */
const sourcePrefix = 'golden-formula-source/';

/** 金方缺失药品 API */
const missingPrefix = 'golden-formula-missing-drug/';

export async function getGoldenFormulaList(data: any) {
  return requestClient.get<any>(`${prefix}list`, { params: data });
}

export async function getGoldenFormulaDetail(id: number) {
  return requestClient.get<any>(`${prefix}detail`, { params: { id } });
}

export async function createGoldenFormula(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}create`, data);
}

export async function updateGoldenFormula(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}update`, data);
}

export async function deleteGoldenFormula(data: Record<string, any>) {
  return requestClient.post<any>(`${prefix}delete`, data);
}

/** Excel 解析后的行批量导入（带全局金方来源 source_id） */
export async function importGoldenFormula(data: {
  rows: Record<string, any>[];
  source_id?: number;
}) {
  return requestClient.post<any>(`${prefix}import`, data);
}

/**
 * 药品存在性排查（全局中药饮片 type=1 + 别名表）
 * 预览页打开时调用，返回存在的药名 + 不存在的药名
 */
export async function checkGoldenFormulaDrugs(data: { drug_names: string[] }) {
  return requestClient.post<{ exists: string[]; missing: string[] }>(
    `${prefix}check-drugs`,
    data,
  );
}

/**
 * 药方设置详情：组成 + 本方缺失药名
 * xk-api GET /golden-formula/drugs-detail
 */
export async function getGoldenFormulaDrugsDetail(id: number) {
  return requestClient.get<{
    id: number;
    name: string;
    drugs_json: any[];
    herb_overview: string;
    is_abnormal: number;
    missing: string[];
  }>(`${prefix}drugs-detail`, { params: { id } });
}

/**
 * 药方设置保存：只更新 drugs_json 相关字段
 * xk-api POST /golden-formula/update-drugs
 */
export async function updateGoldenFormulaDrugs(data: {
  id: number;
  drugs_json: Record<string, any>[];
}) {
  return requestClient.post<any>(`${prefix}update-drugs`, data);
}

/** 金方来源字典 - 下拉选项 */
export async function getGoldenFormulaSourceOption() {
  return requestClient.get<any[]>(`${sourcePrefix}option`);
}

/** 金方来源字典 - 新增来源（预览页输入框新增） */
export async function createGoldenFormulaSource(data: { name: string }) {
  return requestClient.post<any>(`${sourcePrefix}create`, data);
}

/** 缺失药品分页列表 */
export async function getGoldenFormulaMissingDrugList(data: any) {
  return requestClient.get<any>(`${missingPrefix}list`, { params: data });
}

/** 批量标记缺失药品为已解决 */
export async function resolveGoldenFormulaMissingDrug(data: { ids: number[] }) {
  return requestClient.post<any>(`${missingPrefix}resolve`, data);
}

/** 重新校验待处理缺失药品（已存在的自动标已解决） */
export async function recheckGoldenFormulaMissingDrug() {
  return requestClient.post<{ checked: number; resolved: number }>(
    `${missingPrefix}recheck`,
    {},
  );
}

/** 软删除缺失药品记录 */
export async function deleteGoldenFormulaMissingDrug(data: { ids: number[] }) {
  return requestClient.post<any>(`${missingPrefix}delete`, data);
}

/**
 * 缺失药名新建为中药饮片
 * xk-api POST /golden-formula-missing-drug/create-as-drug
 */
export async function createMissingAsDrug(data: {
  id?: number;
  drug_name?: string;
}) {
  return requestClient.post<{
    drug_id: number;
    drug_name: string;
    refreshed: number;
  }>(`${missingPrefix}create-as-drug`, data);
}

/**
 * 仅标记缺失药已解决（中药管理弹窗新建成功后调用，不再二次建药）
 * xk-api POST /golden-formula-missing-drug/resolve-by-name
 */
export async function resolveMissingByName(data: {
  id?: number;
  drug_name?: string;
  remark?: string;
}) {
  return requestClient.post<{
    drug_name: string;
    refreshed: number;
  }>(`${missingPrefix}resolve-by-name`, data);
}

/**
 * 缺失药名挂到目标药材别名表
 * xk-api POST /golden-formula-missing-drug/bind-as-alias
 */
export async function bindMissingAsAlias(data: {
  id?: number;
  drug_name?: string;
  target_drug_id: number;
}) {
  return requestClient.post<{
    drug_id: number;
    drug_name: string;
    alias: string;
    refreshed: number;
  }>(`${missingPrefix}bind-as-alias`, data);
}

/**
 * 预览含某药名的金方（替换前勾选）
 * xk-api GET /golden-formula-missing-drug/formulas-by-drug-name
 */
export async function getFormulasByDrugName(drugName: string) {
  return requestClient.get<
    {
      id: number;
      name: string;
      clause_number: string;
      herb_overview: string;
      source_name: string;
      is_abnormal: number;
      has_unmatched: number;
      status: number;
      drug_count: number;
      /** 命中味克数（拆分后每味继承） */
      match_dose: string;
      match_unit: string;
      match_ancient_dose: string;
      /** 展示用：如 9g（三两） */
      match_dose_text: string;
    }[]
  >(`${missingPrefix}formulas-by-drug-name`, {
    params: { drug_name: drugName },
  });
}

/**
 * 替换为药材表已有药材（支持 1→N 拆分）
 * xk-api POST /golden-formula-missing-drug/replace-with-drug
 */
export async function replaceMissingWithDrug(data: {
  id?: number;
  drug_name?: string;
  /** 预览勾选的金方 ID 列表（必填） */
  formula_ids: number[];
  /** 目标药材列表；多味时把错误合并名拆成多行 */
  targets: Array<{ target_drug_id: number; dose?: string }>;
  /** 兼容旧单目标（可选） */
  target_drug_id?: number;
}) {
  return requestClient.post<{
    drug_id: number;
    old_name: string;
    new_name: string;
    new_names: string[];
    formula_count: number;
    refreshed: number;
  }>(`${missingPrefix}replace-with-drug`, data);
}