import { erpPriceMultiply } from '@vben/utils';

/** ERP 明细行中与金额、税额相关的字段 */
export interface ErpTaxLine {
  /** 数量 */
  count?: null | number;
  /** 产品单价（含税单价） */
  productPrice?: null | number;
  /** 税率，百分比，例如 13 */
  taxPercent?: null | number;
  /** 税额 */
  taxPrice?: null | number;
  /** 不含税金额 */
  totalProductPrice?: null | number;
  /** 含税总价 */
  totalPrice?: null | number;
}

/**
 * 按「产品单价为含税单价」的口径重算明细行金额
 *
 * 含税总价 = 数量 × 含税单价
 * 税额 = 含税总价 × 税率 ÷（100 + 税率）
 * 不含税金额 = 含税总价 − 税额
 */
export function calcTaxIncludedLine<T extends ErpTaxLine>(row: T): T {
  const totalPrice =
    erpPriceMultiply(Number(row.productPrice ?? 0), Number(row.count ?? 0)) ??
    0;
  const taxPercent = Number(row.taxPercent ?? 0);
  const taxPrice =
    taxPercent > 0
      ? Number(((totalPrice * taxPercent) / (100 + taxPercent)).toFixed(2))
      : 0;
  row.totalPrice = totalPrice;
  row.taxPrice = taxPrice;
  row.totalProductPrice = Number((totalPrice - taxPrice).toFixed(2));
  return row;
}
