/**

 * 中药处方毛利率计算（仅商品计费，不含诊疗费/加工费）

 */



export function isSeeRateEnabled(seeRate: unknown): boolean {

  return Number(seeRate) === 1;

}



function isValidBuyPrice(value: unknown): boolean {

  if (value === null || value === undefined || value === '') {

    return false;

  }

  const n = Number(value);

  return !Number.isNaN(n);

}



export function calcItemMarginPercent(

  price: number | string | undefined,

  buyPrice: number | string | undefined,

): string {

  const p = Number(price);

  if (!p || p <= 0 || !isValidBuyPrice(buyPrice)) {

    return '--';

  }

  const b = Number(buyPrice);

  return (((p - b) / p) * 100).toFixed(2);

}



export interface ChineseDrugMarginRow {

  price?: number | string;

  buy_price?: number | string;

  number?: number | string;

  select_number?: number | string;

}



export function calcTotalMarginPercent(

  drugs: ChineseDrugMarginRow[],

  dosage: number,

): string {

  if (!drugs?.length || dosage <= 0) {

    return '0.00';

  }

  let saleTotal = 0;

  let buyTotal = 0;

  for (const drug of drugs) {

    if (!isValidBuyPrice(drug.buy_price)) {

      return '--';

    }

    const qty = Number(drug.number ?? drug.select_number ?? 1);

    const price = Number(drug.price || 0);

    const buyPrice = Number(drug.buy_price);

    saleTotal += price * qty * dosage;

    buyTotal += buyPrice * qty * dosage;

  }

  if (saleTotal <= 0) {

    return '0.00';

  }

  return (((saleTotal - buyTotal) / saleTotal) * 100).toFixed(2);

}


