var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saleDetail/components/SummaryFinancialSections/index.tsx
var SummaryFinancialSections_exports = {};
__export(SummaryFinancialSections_exports, {
  SummaryFinancialSections: () => SummaryFinancialSections
});
module.exports = __toCommonJS(SummaryFinancialSections_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_decimal = __toESM(require("decimal.js"));
var import_lodash = require("lodash");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../hooks/useEngineContext"));
var import_salesSdk = require("../../../salesSdk");
var import_usePaymentMethodNameMap = require("../../../pisellSalesManagement/hooks/usePaymentMethodNameMap");
var import_index = require("./index.less");
var PREFIX = "pisell-sale-detail-summary-financial";
function toDecimal(value) {
  try {
    if (value instanceof import_decimal.default) return value;
    if (value === void 0 || value === null || value === "") {
      return new import_decimal.default(0);
    }
    return new import_decimal.default(value);
  } catch {
    return new import_decimal.default(0);
  }
}
function isNonZeroAmount(value) {
  return !toDecimal(value).isZero();
}
function formatMoney(value, symbol) {
  return (0, import_utils.formatAmount)(toDecimal(value).toString(), 2, symbol);
}
function formatPlainNumber(value) {
  return toDecimal(value).toFixed(2).replace(/\.?0+$/, "");
}
function formatDeduction(value, symbol) {
  const amount = toDecimal(value).abs().negated();
  return formatMoney(amount, symbol);
}
function asRecords(value) {
  return Array.isArray(value) ? value.filter(
    (item) => !!item && typeof item === "object"
  ) : [];
}
function firstDefined(record, keys) {
  if (!record) return void 0;
  for (const key of keys) {
    const value = record[key];
    if (value !== void 0 && value !== null && value !== "") {
      return value;
    }
  }
  return void 0;
}
function toDisplayText(value, translationOriginal) {
  if (!value) return "";
  if (typeof value === "string") return value;
  const translated = translationOriginal == null ? void 0 : translationOriginal(value);
  if (translated) return translated;
  const fallbackKeys = ["original", "auto", "en-US", "en", "zh-CN", "zh-HK"];
  for (const key of fallbackKeys) {
    const text = value[key];
    if (typeof text === "string" && text) return text;
  }
  const firstText = Object.values(value).find(
    (item) => typeof item === "string" && !!item
  );
  return firstText || "";
}
function getPaymentAmount(record) {
  return firstDefined(record, ["origin_amount", "amount"]);
}
function getPaymentSurchargeAmount(record) {
  return record.service_fee;
}
function isRefundPaymentRecord(record) {
  const rawType = String(record.type || record.status || "").toLowerCase();
  return rawType.includes("refund") || toDecimal(getPaymentAmount(record)).lt(0);
}
function isVoucherPaymentRecord(record) {
  return !!record.voucher_id;
}
function isPointCardPaymentRecord(record) {
  return String(record.code || "").toUpperCase() === "POINTCARD";
}
function isPointCardAdjustmentEntry(entry) {
  return String(entry.tag || entry.code || "").toUpperCase() === "POINTCARD";
}
function buildPaymentDetailEntry(record, fallbackKey, paymentMethodNameMap) {
  const isRefund = isRefundPaymentRecord(record);
  const amount = getPaymentAmount(record);
  const surchargeAmount = getPaymentSurchargeAmount(record);
  return {
    key: String(record.order_payment_id || record.id || fallbackKey),
    title: (0, import_usePaymentMethodNameMap.resolvePaymentMethodName)(record, paymentMethodNameMap),
    amount: isRefund ? toDecimal(amount).abs().negated() : amount,
    isRefund,
    surchargeAmount: isNonZeroAmount(surchargeAmount) ? isRefund ? toDecimal(surchargeAmount).abs().negated() : surchargeAmount : void 0
  };
}
function buildDiscountAdjustmentEntry(record, translationOriginal) {
  const amount = record.savedAmount || record.amount;
  if (!isNonZeroAmount(amount)) return null;
  return {
    key: record.id,
    code: record.code,
    title: toDisplayText(
      record.format_title,
      translationOriginal
    ),
    tag: record.tag ? String(record.tag) : void 0,
    amount: toDecimal(amount).abs().negated(),
    balance: record.balance,
    tone: "deduction"
  };
}
function buildVoucherPaymentAdjustmentEntry(record, translationOriginal) {
  const amount = record.amount;
  if (!isNonZeroAmount(amount)) return null;
  const fundRecord = record.fund_record || {};
  const title = toDisplayText(
    fundRecord.wallet_pass_name,
    translationOriginal
  ) || String(record.code || import_utils.locales.getText("pisell2.sale-detail.item"));
  const code = fundRecord.encoded || fundRecord.code;
  const isPointCard = isPointCardPaymentRecord(record);
  const pointUsage = isPointCard ? toDecimal(fundRecord.using_before_value).minus(toDecimal(fundRecord.using_after_value)).abs() : null;
  return {
    key: String(record.order_payment_id),
    title,
    code: code ? String(code) : void 0,
    tag: record.code ? String(record.code) : void 0,
    amount: toDecimal(amount).abs().negated(),
    balance: fundRecord.using_after_value,
    pointUsage: pointUsage && !pointUsage.isZero() ? pointUsage : void 0,
    tone: "deduction"
  };
}
var SectionCard = (0, import_react.memo)(function SectionCard2({
  children,
  iconType,
  title,
  tone
}) {
  return /* @__PURE__ */ import_react.default.createElement(
    "section",
    {
      className: (0, import_classnames.default)(`${PREFIX}__card`, {
        [`${PREFIX}__card--payment`]: tone === "payment",
        [`${PREFIX}__card--promotion`]: tone === "promotion"
      })
    },
    /* @__PURE__ */ import_react.default.createElement("header", { className: `${PREFIX}__card-header` }, /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: iconType }), /* @__PURE__ */ import_react.default.createElement("span", null, title)),
    children
  );
});
var AmountRows = (0, import_react.memo)(function AmountRows2({
  rows,
  symbol
}) {
  return /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__rows` }, rows.map((row) => /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: (0, import_classnames.default)(`${PREFIX}__row`, {
        [`${PREFIX}__row--deduction`]: row.tone === "deduction",
        [`${PREFIX}__row--highlight`]: row.tone === "highlight"
      }),
      key: row.key
    },
    /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__row-label` }, row.label),
    /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__row-value` }, row.tone === "deduction" ? formatDeduction(row.value, symbol) : formatMoney(row.value, symbol))
  )));
});
var PaymentDetailsContent = (0, import_react.memo)(function PaymentDetailsContent2({
  symbol,
  toPayAmount,
  payments,
  summary
}) {
  const currentLocale = import_utils.locales.getLocale();
  const paymentMethodNameMap = (0, import_usePaymentMethodNameMap.usePaymentMethodNameMap)();
  const entries = (0, import_react.useMemo)(() => {
    const nonVoucherPayments = payments.filter(
      (payment) => !isVoucherPaymentRecord(payment)
    );
    const nextEntries = nonVoucherPayments.map(
      (payment, index) => buildPaymentDetailEntry(
        payment,
        `payment-${index}`,
        paymentMethodNameMap
      )
    );
    if (!payments.length) {
      if (isNonZeroAmount(summary.order_paid_amount)) {
        nextEntries.push({
          key: "paid-summary",
          title: import_utils.locales.getText("pisell2.sale-detail.pay.payment"),
          amount: summary.order_paid_amount,
          isRefund: false
        });
      }
      if (isNonZeroAmount(summary.total_refund_amount)) {
        nextEntries.push({
          key: "refund-summary",
          title: import_utils.locales.getText("pisell2.sale-detail.refund"),
          amount: toDecimal(summary.total_refund_amount).abs().negated(),
          isRefund: true
        });
      }
    }
    return nextEntries;
  }, [
    currentLocale,
    paymentMethodNameMap,
    payments,
    summary.order_paid_amount,
    summary.total_refund_amount
  ]);
  const summaryRows = [
    {
      key: "toPay",
      label: import_utils.locales.getText("pisell2.sale-detail.to-pay"),
      value: toPayAmount,
      tone: "highlight"
    }
  ];
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, entries.length ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__payment-list` }, entries.map((entry) => /* @__PURE__ */ import_react.default.createElement(
    "article",
    {
      className: (0, import_classnames.default)(`${PREFIX}__payment`, {
        [`${PREFIX}__payment--refund`]: entry.isRefund
      }),
      key: entry.key
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__payment-content` }, /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__payment-title` }, entry.title), /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__payment-amount` }, formatMoney(entry.amount, symbol))),
    entry.surchargeAmount !== void 0 ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__payment-sub-content` }, /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__payment-sub-title` }, import_utils.locales.getText("pisell2.sale-detail.payment-surcharge")), /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__payment-sub-amount` }, formatMoney(entry.surchargeAmount, symbol))) : null
  ))) : null, /* @__PURE__ */ import_react.default.createElement(AmountRows, { rows: summaryRows, symbol }));
});
var AmountBreakdownSectionView = (0, import_react.memo)(function AmountBreakdownSectionView2({
  symbol,
  summary,
  taxTitle
}) {
  const currentLocale = import_utils.locales.getLocale();
  const amountRows = (0, import_react.useMemo)(() => {
    if (!summary) return [];
    return [
      {
        key: "subtotal",
        label: import_utils.locales.getText("pisell2.sale-detail.subtotal"),
        value: summary.product_amount
      },
      {
        key: "surcharge",
        label: import_utils.locales.getText("pisell2.sale-detail.surcharge"),
        value: summary.surcharge_fee
      },
      {
        key: "discount",
        label: import_utils.locales.getText("pisell2.sale-detail.discount"),
        value: summary.discount_amount,
        tone: isNonZeroAmount(summary.discount_amount) ? "deduction" : void 0
      },
      {
        key: "tax",
        label: summary.tax_title || taxTitle || import_utils.locales.getText("pisell2.sale-detail.tax"),
        value: summary.tax_fee
      },
      {
        key: "total",
        label: import_utils.locales.getText("pisell2.sale-detail.total-amount"),
        value: summary.expect_amount,
        tone: "highlight"
      }
    ];
  }, [currentLocale, summary, taxTitle]);
  if (!amountRows.length) return null;
  return /* @__PURE__ */ import_react.default.createElement(
    SectionCard,
    {
      iconType: "pisell2-file-05",
      title: import_utils.locales.getText("pisell2.sale-detail.amount-breakdown")
    },
    /* @__PURE__ */ import_react.default.createElement(AmountRows, { rows: amountRows, symbol })
  );
}, import_lodash.isEqual);
var AmountBreakdownSection = (0, import_react.memo)(function AmountBreakdownSection2() {
  const engineContext = (0, import_useEngineContext.default)();
  const sales = (0, import_salesSdk.useSalesSdk)();
  const summaryState = (0, import_salesSdk.useSalesSdkSummary)();
  const tempOrder = sales.tempOrder;
  const symbol = (tempOrder == null ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
  return /* @__PURE__ */ import_react.default.createElement(
    AmountBreakdownSectionView,
    {
      symbol,
      summary: summaryState.summary,
      taxTitle: tempOrder == null ? void 0 : tempOrder.tax_title
    }
  );
});
var PaymentDetailsSectionView = (0, import_react.memo)(function PaymentDetailsSectionView2({
  payments: rawPayments,
  symbol,
  summary
}) {
  const payments = (0, import_react.useMemo)(() => asRecords(rawPayments), [rawPayments]);
  const hasSummary = !!summary;
  const orderPaidAmount = summary == null ? void 0 : summary.order_paid_amount;
  const totalRefundAmount = summary == null ? void 0 : summary.total_refund_amount;
  const showPaymentDetails = (0, import_react.useMemo)(() => {
    if (!hasSummary) return false;
    const hasNonVoucherPayment = payments.some(
      (payment) => !isVoucherPaymentRecord(payment)
    );
    return hasNonVoucherPayment || !payments.length && (isNonZeroAmount(orderPaidAmount) || isNonZeroAmount(totalRefundAmount));
  }, [hasSummary, orderPaidAmount, payments, totalRefundAmount]);
  if (!showPaymentDetails || !summary) return null;
  return /* @__PURE__ */ import_react.default.createElement(
    SectionCard,
    {
      iconType: "pisell2-credit-card-02",
      title: import_utils.locales.getText("pisell2.sale-detail.payment-details"),
      tone: "payment"
    },
    /* @__PURE__ */ import_react.default.createElement(
      PaymentDetailsContent,
      {
        payments,
        summary,
        symbol,
        toPayAmount: summary.amount_gap
      }
    )
  );
}, import_lodash.isEqual);
var PaymentDetailsSection = (0, import_react.memo)(function PaymentDetailsSection2() {
  const engineContext = (0, import_useEngineContext.default)();
  const sales = (0, import_salesSdk.useSalesSdk)();
  const summaryState = (0, import_salesSdk.useSalesSdkSummary)();
  const tempOrder = sales.tempOrder;
  const symbol = (tempOrder == null ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
  return /* @__PURE__ */ import_react.default.createElement(
    PaymentDetailsSectionView,
    {
      payments: tempOrder == null ? void 0 : tempOrder.payments,
      symbol,
      summary: summaryState.summary
    }
  );
});
var AdjustmentSectionView = (0, import_react.memo)(function AdjustmentSectionView2({
  discountList,
  payments: rawPayments,
  shopDiscount,
  symbol,
  translationOriginal
}) {
  const payments = (0, import_react.useMemo)(() => asRecords(rawPayments), [rawPayments]);
  const currentLocale = import_utils.locales.getLocale();
  const adjustmentEntries = (0, import_react.useMemo)(() => {
    const entries = [];
    asRecords(discountList).filter((record) => record.isSelected).forEach((record) => {
      const entry = buildDiscountAdjustmentEntry(record, translationOriginal);
      if (entry) entries.push(entry);
    });
    payments.filter(isVoucherPaymentRecord).forEach((record) => {
      const entry = buildVoucherPaymentAdjustmentEntry(
        record,
        translationOriginal
      );
      if (entry) entries.push(entry);
    });
    if (isNonZeroAmount(shopDiscount)) {
      entries.push({
        key: "manual-order-discount",
        title: import_utils.locales.getText("pisell2.sale-detail.manual-order-adjustment"),
        amount: toDecimal(shopDiscount).abs().negated(),
        tone: "deduction"
      });
    }
    return entries;
  }, [
    currentLocale,
    discountList,
    payments,
    shopDiscount,
    translationOriginal
  ]);
  if (!adjustmentEntries.length) return null;
  return /* @__PURE__ */ import_react.default.createElement(
    SectionCard,
    {
      iconType: "pisell2-a-wallet-021",
      title: import_utils.locales.getText("pisell2.sale-detail.passes-vouchers"),
      tone: "promotion"
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__adjustment-list` }, adjustmentEntries.map((entry) => {
      const isPointCard = isPointCardAdjustmentEntry(entry);
      return /* @__PURE__ */ import_react.default.createElement("article", { className: `${PREFIX}__adjustment`, key: entry.key }, /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__adjustment-main` }, /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__adjustment-title` }, entry.title), /* @__PURE__ */ import_react.default.createElement(
        "span",
        {
          className: (0, import_classnames.default)(`${PREFIX}__adjustment-amount`, {
            [`${PREFIX}__adjustment-amount--addition`]: entry.tone === "addition"
          })
        },
        formatMoney(entry.amount, symbol),
        isPointCard && isNonZeroAmount(entry.pointUsage) ? ` (${formatPlainNumber(
          toDecimal(entry.pointUsage).abs().negated()
        )})` : null
      )), entry.code || entry.subtitle || entry.tag || entry.balance !== void 0 ? /* @__PURE__ */ import_react.default.createElement("div", { className: `${PREFIX}__adjustment-meta` }, entry.code || entry.subtitle || entry.tag ? /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__adjustment-subtitle` }, [entry.code || entry.subtitle, entry.tag].filter(Boolean).join(" · ")) : null, entry.balance !== void 0 ? /* @__PURE__ */ import_react.default.createElement("span", { className: `${PREFIX}__adjustment-balance` }, /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("pisell2.sale-detail.balance")), /* @__PURE__ */ import_react.default.createElement("span", null, isPointCard ? formatPlainNumber(entry.balance) : formatMoney(entry.balance, symbol))) : null) : null);
    }))
  );
}, import_lodash.isEqual);
var AdjustmentSection = (0, import_react.memo)(function AdjustmentSection2() {
  const engineContext = (0, import_useEngineContext.default)();
  const sales = (0, import_salesSdk.useSalesSdk)();
  const cart = (0, import_salesSdk.useSalesSdkCart)();
  const tempOrder = sales.tempOrder;
  const symbol = (tempOrder == null ? void 0 : tempOrder.currency_symbol) || engineContext.appHelper.utils.getSymbolic();
  const translationOriginal = engineContext.appHelper.utils.translationOriginal;
  return /* @__PURE__ */ import_react.default.createElement(
    AdjustmentSectionView,
    {
      discountList: cart.discountList,
      payments: tempOrder == null ? void 0 : tempOrder.payments,
      shopDiscount: tempOrder == null ? void 0 : tempOrder.shop_discount,
      symbol,
      translationOriginal
    }
  );
});
var SummaryFinancialSections = (0, import_react.memo)(function SummaryFinancialSections2({
  className
}) {
  return /* @__PURE__ */ import_react.default.createElement("div", { className: (0, import_classnames.default)(PREFIX, className) }, /* @__PURE__ */ import_react.default.createElement(PaymentDetailsSection, null), /* @__PURE__ */ import_react.default.createElement(AdjustmentSection, null));
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  SummaryFinancialSections
});
