/*!
 * profit-core.js — 退货后利润核算引擎（UMD）
 * 版本: 1.0.0
 * 作者: W29 赛博游园会练习交付
 *
 * 设计原则
 *  1) 只算账，不取数。不连接任何电商后台，输入由调用方传入。
 *  2) 缺失/null/空串一律记「待补」，绝不静默当 0。数字 0 与「未知」是两件事。
 *  3) 每一分钱都能在勾稽阶梯上逐行对上：逐单净利润之和 == 汇总净利润。
 *  4) 销售额只是勾稽起点，净利润永远另行计算，二者不混用。
 *
 * 用法
 *  浏览器: <script src="profit-core.js"></script>  ->  window.ProfitCore
 *  Node : const ProfitCore = require('./profit-core.js')
 *  AMD  : define(['profit-core'], ...)
 */
(function (root, factory) {
  'use strict';
  if (typeof define === 'function' && define.amd) {
    define([], factory);
  } else if (typeof module === 'object' && module.exports) {
    module.exports = factory();
  } else {
    root.ProfitCore = factory();
  }
})(typeof globalThis !== 'undefined' ? globalThis : (typeof self !== 'undefined' ? self : this), function () {
  'use strict';

  var VERSION = '1.0.0';

  /* ------------------------------------------------------------------ *
   * 字段字典：顺序即勾稽顺序，HTML / CSV / 校验共用同一份定义
   * ------------------------------------------------------------------ */
  var FIELD_DEFS = [
    { key: 'gross', label: '销售额', role: 'revenue' },
    { key: 'goodsCost', label: '货成本', role: 'cost' },
    { key: 'outbound', label: '去程运费', role: 'cost' },
    { key: 'platformFee', label: '平台费', role: 'cost' },
    { key: 'adAllocated', label: '广告分摊（给定值）', role: 'cost' },
    { key: 'refund', label: '退款', role: 'refund' },
    { key: 'returnShipping', label: '退回运费', role: 'cost' },
    { key: 'returnedGoodsRecovery', label: '退回货物回收价值', role: 'recovery' }
  ];

  var LABEL = {};
  FIELD_DEFS.forEach(function (d) { LABEL[d.key] = d.label; });

  /* 广告分摊方式 */
  var AD_METHODS = {
    fixed: {
      label: '按给定分摊额比例',
      desc: '沿用每单给定的广告分摊额，按比例缩放到广告总预算；未改写原始归因。'
    },
    revenue: {
      label: '按销售额比例',
      desc: '按每单销售额占全部可核算订单销售额合计的比例分摊广告总预算。'
    },
    netRevenue: {
      label: '按净销售额比例',
      desc: '按每单（销售额 − 退款）占比分摊，退款单承担更少广告，更贴近“成交才烧钱”。'
    }
  };

  /* 平台费退回假设 */
  var PLATFORM_METHODS = {
    none: {
      label: '平台费不退',
      desc: '退款只退货款，平台佣金/服务费不返还，退款单的平台费全额沉没。'
    },
    prorata: {
      label: '按退款比例退回',
      desc: '平台费按 退款 ÷ 销售额 的比例返还，部分退款也按比例退费。'
    },
    fullOnFullRefund: {
      label: '仅整单退款时全额退回',
      desc: '整单退款返还全部平台费；部分退款不返还任何平台费。'
    }
  };

  var DEFAULTS = {
    currency: 'CNY',
    adMethod: 'fixed',
    adBudget: null,            // null = 由各单给定分摊额加总得出
    platformFeeRefund: 'none',
    countRecovery: true,       // 退回货物回收价值是否计入本期
    tolerance: 0.005
  };

  /* ------------------------------------------------------------------ *
   * 基础工具
   * ------------------------------------------------------------------ */

  /** 金额四舍五入到分。null/NaN 原样返回 null，不吞异常。 */
  function round2(n) {
    if (n === null || n === undefined || typeof n !== 'number' || !isFinite(n)) return null;
    var sign = n < 0 ? -1 : 1;
    return sign * Math.round(Math.abs(n) * 100 + 1e-9) / 100;
  }

  /** 解析为数字：null / undefined / 空串 / 非数字 一律返回 null（= 待补）。 */
  function toNumber(v) {
    if (v === null || v === undefined) return null;
    if (typeof v === 'number') return isFinite(v) ? v : null;
    if (typeof v === 'string') {
      var s = v.trim().replace(/,/g, '');
      if (s === '') return null;
      if (!/^[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?$/.test(s)) return null;
      var n = Number(s);
      return isFinite(n) ? n : null;
    }
    return null; // 布尔、对象、数组等一概不认
  }

  function isNum(v) {
    return typeof v === 'number' && isFinite(v);
  }

  function sum(arr) {
    var t = 0;
    for (var i = 0; i < arr.length; i++) if (isNum(arr[i])) t += arr[i];
    return round2(t);
  }

  function closest(n) {
    return Math.abs(n) < 1e-9 ? 0 : n;
  }

  /**
   * 按权重把 pool 分摊到各权重上，用最大余额法，保证「分摊额之和 === pool（到分）」。
   * 这是逐单合计能对上汇总的前提，也是本引擎的硬约束。
   */
  function allocateByWeight(pool, weights) {
    var cents = Math.round(pool * 100);
    var total = 0, i;
    for (i = 0; i < weights.length; i++) total += weights[i];

    if (cents === 0) return weights.map(function () { return 0; });
    if (total <= 0) {
      // 权重全为 0：退化为等分（并在上层给出假设说明）
      var base = Math.floor(cents / weights.length);
      var rest = cents - base * weights.length;
      return weights.map(function (_, idx) { return (base + (idx < rest ? 1 : 0)) / 100; });
    }

    var raw = weights.map(function (w) { return cents * w / total; });
    var floors = raw.map(function (v) { return Math.floor(v); });
    var used = 0;
    for (i = 0; i < floors.length; i++) used += floors[i];
    var left = cents - used;

    var order = raw
      .map(function (v, idx) { return { idx: idx, frac: v - Math.floor(v) }; })
      .sort(function (a, b) { return (b.frac - a.frac) || (a.idx - b.idx); });

    for (i = 0; i < left; i++) floors[order[i % order.length].idx] += 1;
    return floors.map(function (c) { return c / 100; });
  }

  /** 千分位金额（展示用），null -> 「待补」 */
  function formatMoney(n, opts) {
    opts = opts || {};
    if (!isNum(n)) return '待补';
    var neg = n < 0;
    var s = Math.abs(n).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
    var prefix = opts.symbol === false ? '' : (opts.symbol || '¥');
    return (neg ? '−' : '') + prefix + s;
  }

  /* ------------------------------------------------------------------ *
   * 选项规范化：外部传错类型不崩，回落到安全默认并留痕
   * ------------------------------------------------------------------ */
  function normalizeOptions(options) {
    options = options || {};
    var warnings = [];

    var adMethod = AD_METHODS[options.adMethod] ? options.adMethod : DEFAULTS.adMethod;
    if (options.adMethod !== undefined && options.adMethod !== adMethod) {
      warnings.push('广告分摊方式「' + options.adMethod + '」无法识别，已回落到「' + AD_METHODS[adMethod].label + '」。');
    }

    var platformFeeRefund = PLATFORM_METHODS[options.platformFeeRefund]
      ? options.platformFeeRefund
      : DEFAULTS.platformFeeRefund;
    if (options.platformFeeRefund !== undefined && options.platformFeeRefund !== platformFeeRefund) {
      warnings.push('平台费退回假设无法识别，已回落到「' + PLATFORM_METHODS[platformFeeRefund].label + '」。');
    }

    var adBudget = null, adBudgetSource = 'derived';
    if (options.adBudget !== undefined && options.adBudget !== null && options.adBudget !== '') {
      var parsed = toNumber(options.adBudget);
      if (parsed === null) {
        warnings.push('广告总预算「' + options.adBudget + '」不是有效数字，已改为按各单给定分摊额加总。');
      } else if (parsed < 0) {
        warnings.push('广告总预算为负数，已按 0 处理。');
        adBudget = 0;
        adBudgetSource = 'manual';
      } else {
        adBudget = round2(parsed);
        adBudgetSource = 'manual';
      }
    }

    var countRecovery = options.countRecovery === undefined ? DEFAULTS.countRecovery : !!options.countRecovery;

    return {
      currency: options.currency || DEFAULTS.currency,
      adMethod: adMethod,
      adBudget: adBudget,
      adBudgetSource: adBudgetSource,
      platformFeeRefund: platformFeeRefund,
      countRecovery: countRecovery,
      tolerance: isNum(options.tolerance) ? options.tolerance : DEFAULTS.tolerance,
      warnings: warnings
    };
  }

  /* ------------------------------------------------------------------ *
   * 单订单字段体检：区分「缺失」「无法识别」「负数异常」
   * ------------------------------------------------------------------ */
  function inspectOrder(order, opts, index) {
    order = order || {};
    var values = {};        // 解析后的数字，未知为 null
    var absent = [];        // 键不存在 / null / 空串
    var unparsable = [];    // 有值但不是数字
    var negative = [];      // 负数

    FIELD_DEFS.forEach(function (def) {
      var has = Object.prototype.hasOwnProperty.call(order, def.key);
      var raw = has ? order[def.key] : undefined;
      var num = toNumber(raw);

      if (num === null) {
        values[def.key] = null;
        if (raw === null || raw === undefined || (typeof raw === 'string' && raw.trim() === '')) {
          absent.push(def.key);
        } else {
          unparsable.push(def.key);
        }
      } else if (num < 0) {
        values[def.key] = num;
        negative.push(def.key);
      } else {
        values[def.key] = num;
      }
    });

    // 广告分摊额：只有当分摊方式需要原值时才强制要求
    var needsGivenAd = opts.adMethod === 'fixed';
    var requiredKeys = FIELD_DEFS
      .map(function (d) { return d.key; })
      .filter(function (k) { return k !== 'adAllocated' || needsGivenAd; });

    var issues = [];

    requiredKeys.forEach(function (key) {
      if (absent.indexOf(key) >= 0) {
        issues.push({
          field: key,
          fieldLabel: LABEL[key],
          type: 'missing',
          message: LABEL[key] + '缺失',
          suggestion: '补齐该单的' + LABEL[key] + '后再纳入汇总；本单暂记「待补」，不按 0 参与计算。'
        });
      } else if (unparsable.indexOf(key) >= 0) {
        issues.push({
          field: key,
          fieldLabel: LABEL[key],
          type: 'unparsable',
          message: LABEL[key] + '无法识别为金额',
          suggestion: '填写纯数字（可带小数点），勿填单位、文字或区间；本单暂记「待补」。'
        });
      } else if (negative.indexOf(key) >= 0) {
        issues.push({
          field: key,
          fieldLabel: LABEL[key],
          type: 'negative',
          message: LABEL[key] + '为负数（' + values[key] + '）',
          suggestion: '成本、退款类字段不应为负；请确认是否为冲正或录入错误。本单暂记「待补」。'
        });
      }
    });

    // 退款不得超过销售额（订单级硬校验）
    if (isNum(values.gross) && isNum(values.refund) && values.refund > values.gross + opts.tolerance) {
      issues.push({
        field: 'refund',
        fieldLabel: '退款',
        type: 'refundOverGross',
        message: '退款 ' + values.refund + ' 超过销售额 ' + values.gross,
        suggestion: '核对是否把跨单退款并到本单；退款上限为销售额，本单暂记「待补」。'
      });
    }

    return {
      index: index,
      values: values,
      absent: absent,
      unparsable: unparsable,
      negative: negative,
      issues: issues,
      ok: issues.length === 0
    };
  }

  /* ------------------------------------------------------------------ *
   * 勾稽阶梯：每一行带余额，最后一行必然是净利润
   * ------------------------------------------------------------------ */
  function buildLadder(c) {
    var steps = [];
    var run = 0;
    var broken = false;   // 一旦遇到「待补」，后续余额不可继续累加

    function push(label, amount, o) {
      o = o || {};

      // 小计行 / 合计行：amount 即结果本身，不再累加，避免重复计入
      if (o.subtotal || o.total) {
        steps.push({
          label: label,
          amount: amount,
          running: amount,
          kind: o.total ? 'total' : 'subtotal',
          note: o.note || '',
          sign: 0
        });
        if (amount === null) broken = true;
        else run = amount;
        return;
      }

      if (amount === null) broken = true;
      if (!broken) run = round2(run + amount);
      steps.push({
        label: label,
        amount: amount,
        running: broken ? null : run,
        kind: amount !== null && amount >= 0 ? 'plus' : 'minus',
        note: o.note || '',
        sign: amount === null ? 0 : (amount >= 0 ? 1 : -1)
      });
    }

    push('销售额', c.gross, { note: '订单成交金额（毛额，仅作起点）' });
    push('退款', c.refund === null ? null : -c.refund, { note: '退回买家的货款' });
    push('净收入', c.netRevenue, { subtotal: true });

    push('货成本', c.goodsCost === null ? null : -c.goodsCost, { note: '商品成本，含入仓/采购' });
    push('去程运费', c.outbound === null ? null : -c.outbound, { note: '发货快递费，退款单通常不返还' });
    push('平台费（计入）', c.platformFeeCharged === null ? null : -c.platformFeeCharged, {
      note: c.platformFeeRefunded ? '原 ' + c.platformFeeOriginal + '，按假设退回 ' + c.platformFeeRefunded : '按当前假设不退回'
    });
    push('广告分摊（计入）', c.adCharged === null ? null : -c.adCharged, {
      note: c.adMethodLabel || ''
    });
    push('退回运费', c.returnShipping === null ? null : -c.returnShipping, { note: '退件回程运费' });
    push('退回货回收价值', c.recoveryCounted === null ? null : c.recoveryCounted, {
      note: c.countRecovery ? '可二次销售/残值，加回' : '本期不计入（was ' + (c.recoveryGiven === null ? '待补' : c.recoveryGiven) + '）'
    });
    push('净利润', c.netProfit, { total: true });

    return steps;
  }

  /* ------------------------------------------------------------------ *
   * 主计算
   * ------------------------------------------------------------------ */
  function compute(spec, options) {
    spec = spec || {};
    var opts = normalizeOptions(options);
    var rawOrders = Array.isArray(spec.orders) ? spec.orders : [];
    var warnings = opts.warnings.slice();
    var currency = spec.currency || opts.currency;

    if (!rawOrders.length) {
      warnings.push('没有可核算的订单：orders 为空。');
    }

    /* --- 第一轮：字段体检 --- */
    var inspected = rawOrders.map(function (o, i) { return inspectOrder(o, opts, i); });
    var okIdx = inspected
      .filter(function (r) { return r.ok; })
      .map(function (r) { return r.index; });

    /* --- 广告总预算 --- */
    var adBudget = opts.adBudget;
    var adBudgetSource = opts.adBudgetSource;
    var pendingAdExcluded = 0;
    var okAdMissing = 0;

    if (adBudget === null) {
      // 只取「可核算订单」的给定分摊额作为预算基数：
      // 待补订单的广告若并入预算，会摊到可核算订单头上，凭空压低它们的利润，属于口径污染。
      var derived = 0;
      inspected.forEach(function (r) {
        if (r.ok) {
          if (isNum(r.values.adAllocated)) derived += r.values.adAllocated;
          else okAdMissing += 1;
        } else if (isNum(r.values.adAllocated)) {
          pendingAdExcluded += r.values.adAllocated;
        }
      });
      adBudget = round2(derived);
      adBudgetSource = 'derived';
      if (adBudget === 0 && rawOrders.length) {
        warnings.push('广告总预算为 0（可核算订单的广告分摊额合计为 0），净利润可能偏高，请确认广告费是否漏记。');
      }
      if (okAdMissing > 0) {
        warnings.push(okAdMissing + ' 单可核算订单未给出广告分摊额，按当前方式推导的广告总预算可能偏低。');
      }
      if (pendingAdExcluded > 0) {
        warnings.push('待补订单的广告分摊 ' + formatMoney(round2(pendingAdExcluded)) +
          ' 未计入本次汇总（该单利润未知，不参与分摊），补齐后请重算。');
      }
    }

    /* --- 广告分摊：只在可核算订单之间分配 --- */
    var weights = [];
    var equalFallback = false;
    okIdx.forEach(function (i) {
      var v = inspected[i].values;
      var w;
      if (opts.adMethod === 'fixed') w = isNum(v.adAllocated) ? v.adAllocated : 0;
      else if (opts.adMethod === 'revenue') w = isNum(v.gross) ? v.gross : 0;
      else w = isNum(v.gross) && isNum(v.refund) ? Math.max(v.gross - v.refund, 0) : 0;
      weights.push(w);
    });

    var weightTotal = weights.reduce(function (a, b) { return a + b; }, 0);
    if (okIdx.length && weightTotal <= 0 && adBudget > 0) equalFallback = true;

    var allocated = allocateByWeight(adBudget, weights.length ? weights : [0]);
    var adMap = {};
    okIdx.forEach(function (i, k) { adMap[i] = allocated[k]; });

    if (equalFallback) {
      warnings.push('广告分摊权重全部为 0（销售额/净销售额为 0），已改为在可核算订单间等分广告总预算。');
    }

    /* --- 第二轮：逐单算钱并搭阶梯 --- */
    var orders = inspected.map(function (r, i) {
      var v = r.values;
      var isOk = r.ok;
      var c = {
        gross: v.gross,
        refund: v.refund,
        netRevenue: isNum(v.gross) && isNum(v.refund) ? round2(v.gross - v.refund) : null,

        goodsCost: v.goodsCost,
        outbound: v.outbound,
        returnShipping: v.returnShipping,

        platformFeeOriginal: v.platformFee,
        platformFeeRefunded: null,
        platformFeeCharged: null,

        adAllocatedGiven: v.adAllocated,
        adCharged: isOk ? adMap[i] : null,
        adMethodLabel: AD_METHODS[opts.adMethod].label,

        recoveryGiven: v.returnedGoodsRecovery,
        recoveryCounted: null,
        countRecovery: opts.countRecovery,

        costTotal: null,
        netProfit: null,
        netMargin: null,
        refundRate: null,
        contributionShare: null
      };

      /* 平台费退回 */
      if (isNum(v.platformFee)) {
        var pf = v.platformFee;
        var refunded = 0;
        if (opts.platformFeeRefund === 'prorata' && isNum(v.gross) && v.gross > 0 && isNum(v.refund)) {
          refunded = pf * Math.min(v.refund / v.gross, 1);
        } else if (opts.platformFeeRefund === 'fullOnFullRefund' && isNum(v.gross) && isNum(v.refund)) {
          refunded = (v.refund >= v.gross - opts.tolerance) ? pf : 0;
        }
        c.platformFeeRefunded = round2(refunded);
        c.platformFeeCharged = round2(pf - round2(refunded));
      }

      /* 回收价值 */
      if (isNum(v.returnedGoodsRecovery)) {
        c.recoveryCounted = opts.countRecovery ? round2(v.returnedGoodsRecovery) : 0;
      }

      /* 成本合计与净利润：全部用「已到分」的分量相加，保证阶梯闭合 */
      if (isOk) {
        c.costTotal = round2(
          (isNum(c.goodsCost) ? c.goodsCost : 0) +
          (isNum(c.outbound) ? c.outbound : 0) +
          (isNum(c.platformFeeCharged) ? c.platformFeeCharged : 0) +
          (isNum(c.adCharged) ? c.adCharged : 0) +
          (isNum(c.returnShipping) ? c.returnShipping : 0)
        );
        c.netProfit = round2(
          c.netRevenue - c.costTotal + (isNum(c.recoveryCounted) ? c.recoveryCounted : 0)
        );
        c.netMargin = c.gross > 0 ? round2(c.netProfit / c.gross * 10000) / 10000 : null;
        c.refundRate = c.gross > 0 ? round2(c.refund / c.gross * 10000) / 10000 : null;
      }

      return {
        id: String(o_id(rawOrders[i], i)),
        index: i,
        status: isOk ? 'ok' : 'pending',
        statusLabel: isOk ? '可核算' : '待补',
        issues: r.issues,
        absent: r.absent,
        unparsable: r.unparsable,
        negative: r.negative,
        calc: c,
        steps: buildLadder(c)
      };
    });

    /* --- 汇总：只累加可核算订单 --- */
    var okOrders = orders.filter(function (o) { return o.status === 'ok'; });
    var pendingOrders = orders.filter(function (o) { return o.status === 'pending'; });

    var totals = {
      orderCount: orders.length,
      okCount: okOrders.length,
      pendingCount: pendingOrders.length,
      isComplete: pendingOrders.length === 0,
      gross: sum(okOrders.map(function (o) { return o.calc.gross; })),
      refund: sum(okOrders.map(function (o) { return o.calc.refund; })),
      netRevenue: sum(okOrders.map(function (o) { return o.calc.netRevenue; })),
      goodsCost: sum(okOrders.map(function (o) { return o.calc.goodsCost; })),
      outbound: sum(okOrders.map(function (o) { return o.calc.outbound; })),
      platformFeeOriginal: sum(okOrders.map(function (o) { return o.calc.platformFeeOriginal; })),
      platformFeeRefunded: sum(okOrders.map(function (o) { return o.calc.platformFeeRefunded; })),
      platformFeeCharged: sum(okOrders.map(function (o) { return o.calc.platformFeeCharged; })),
      adCharged: sum(okOrders.map(function (o) { return o.calc.adCharged; })),
      returnShipping: sum(okOrders.map(function (o) { return o.calc.returnShipping; })),
      recovery: sum(okOrders.map(function (o) { return o.calc.recoveryCounted; })),
      costTotal: null,
      netProfit: null,
      netMargin: null,
      refundRate: null,
      adBudget: adBudget
    };

    totals.costTotal = round2(
      totals.goodsCost + totals.outbound + totals.platformFeeCharged +
      totals.adCharged + totals.returnShipping
    );
    totals.netProfit = sum(okOrders.map(function (o) { return o.calc.netProfit; }));
    totals.netMargin = totals.gross > 0 ? round2(totals.netProfit / totals.gross * 10000) / 10000 : null;
    totals.refundRate = totals.gross > 0 ? round2(totals.refund / totals.gross * 10000) / 10000 : null;

    /* 订单贡献占比：分母为汇总净利润，负贡献如实为负 */
    okOrders.forEach(function (o) {
      o.calc.contributionShare = (totals.netProfit !== null && Math.abs(totals.netProfit) > 1e-9)
        ? round2(o.calc.netProfit / totals.netProfit * 10000) / 10000
        : null;
    });

    /* --- 成本构成 --- */
    var costStructure = [
      { key: 'goodsCost', label: '货成本', amount: totals.goodsCost },
      { key: 'outbound', label: '去程运费', amount: totals.outbound },
      { key: 'platformFeeCharged', label: '平台费', amount: totals.platformFeeCharged },
      { key: 'adCharged', label: '广告分摊', amount: totals.adCharged },
      { key: 'returnShipping', label: '退回运费', amount: totals.returnShipping }
    ].map(function (it) {
      it.share = totals.costTotal > 0 ? round2(it.amount / totals.costTotal * 10000) / 10000 : null;
      return it;
    });

    /* --- 退款视图 --- */
    var refundOrders = okOrders.filter(function (o) { return o.calc.refund > 0; });
    var refundView = {
      orderCount: refundOrders.length,
      refundTotal: totals.refund,
      refundRate: totals.refundRate,
      returnShippingTotal: totals.returnShipping,
      platformFeeRefundedTotal: totals.platformFeeRefunded,
      recoveryTotal: totals.recovery,
      lostProfit: sum(refundOrders.map(function (o) {
        return round2(o.calc.refund + o.calc.returnShipping - (isNum(o.calc.recoveryCounted) ? o.calc.recoveryCounted : 0));
      }))
    };

    /* --- 运行时自校验：逐单合计必须等于汇总 --- */
    var orderProfitSum = sum(okOrders.map(function (o) { return o.calc.netProfit; }));
    var reconcile = {
      orderProfitSum: orderProfitSum,
      totalProfit: totals.netProfit,
      diff: round2(orderProfitSum - totals.netProfit),
      passed: Math.abs(orderProfitSum - totals.netProfit) < 0.005,
      adAllocatedSum: sum(okOrders.map(function (o) { return o.calc.adCharged; })),
      adPool: adBudget,
      adDiff: round2(sum(okOrders.map(function (o) { return o.calc.adCharged; })) - adBudget),
      adPassed: Math.abs(sum(okOrders.map(function (o) { return o.calc.adCharged; })) - adBudget) < 0.005
    };

    /* --- 假设说明（页面与 README/CSV 共用同一份文案来源） --- */
    var assumptions = [
      '口径：全部订单同一会计期，币种 ' + currency + '；金额保留 2 位小数，逐单先四舍五入到分再累加，保证逐单合计 = 汇总。',
      '净利润 = 销售额 − 退款 − 货成本 − 去程运费 − 平台费（按假设） − 广告分摊 − 退回运费 + 退回货回收价值。',
      '广告分摊：' + AD_METHODS[opts.adMethod].label + '；广告总预算 ' + formatMoney(adBudget) +
        '（' + (adBudgetSource === 'manual' ? '手工设定' : '由各单给定分摊额加总') + '），仅在本期可核算订单间分摊。',
      '平台费：' + PLATFORM_METHODS[opts.platformFeeRefund].label + '。' + PLATFORM_METHODS[opts.platformFeeRefund].desc,
      '退回货物回收价值：' + (opts.countRecovery ? '计入本期，作为成本的减项加回。' : '不计入本期，仅作为期后资产观察，净利润因此更低。'),
      '销售额不是利润：销售额仅作勾稽起点，净利润另行扣减退款与全部成本后才成立，勿用销售额替代利润口径。',
      '数据来源：题目目录 inputs/spec.json（合成练习数据），只读引用；本工具不连接任何电商后台，不做实时同步。'
    ];

    if (pendingOrders.length) {
      assumptions.push('完整性：' + pendingOrders.length + ' 单存在待补字段（' + pendingOrders.map(function (o) { return o.id; }).join('、') +
        '），已整体剔除出汇总，当前净利润为「部分口径」，不可当作全店利润。');
    }

    return {
      version: VERSION,
      currency: currency,
      options: {
        adMethod: opts.adMethod,
        adMethodLabel: AD_METHODS[opts.adMethod].label,
        adMethodDesc: AD_METHODS[opts.adMethod].desc,
        adBudget: adBudget,
        adBudgetSource: adBudgetSource,
        platformFeeRefund: opts.platformFeeRefund,
        platformFeeRefundLabel: PLATFORM_METHODS[opts.platformFeeRefund].label,
        platformFeeRefundDesc: PLATFORM_METHODS[opts.platformFeeRefund].desc,
        countRecovery: opts.countRecovery
      },
      orders: orders,
      okOrders: okOrders,
      pendingOrders: pendingOrders,
      totals: totals,
      costStructure: costStructure,
      refundView: refundView,
      reconcile: reconcile,
      assumptions: assumptions,
      warnings: warnings
    };
  }

  function o_id(order, i) {
    if (order && order.id !== undefined && order.id !== null && String(order.id).trim() !== '') return order.id;
    return '#' + (i + 1);
  }

  /* ------------------------------------------------------------------ *
   * CSV 导出（与页面同源，避免两套口径）
   * ------------------------------------------------------------------ */
  function csvCell(v) {
    if (v === null || v === undefined) return '';
    var s = String(v);
    if (/[",\n\r]/.test(s)) s = '"' + s.replace(/"/g, '""') + '"';
    return s;
  }

  function csvRow(cells) {
    return cells.map(csvCell).join(',');
  }

  function money4csv(n) {
    return isNum(n) ? n.toFixed(2) : '待补';
  }

  function pct4csv(n) {
    return isNum(n) ? (n * 100).toFixed(2) + '%' : '待补';
  }

  /** 逐单勾稽明细 CSV */
  function toDetailCSV(result) {
    var head = [
      '单号', '状态', '销售额', '退款', '净收入',
      '货成本', '去程运费', '平台费(原)', '平台费退回', '平台费(计入)',
      '广告分摊(计入)', '退回运费', '回收价值(计入)',
      '成本合计', '净利润', '净利率', '退款率', '占净利润比',
      '待补字段', '备注'
    ];
    var lines = [csvRow(head)];

    result.orders.forEach(function (o) {
      var c = o.calc;
      var isOk = o.status === 'ok';
      var notes = o.issues.map(function (x) { return x.message; }).join('；');
      if (c.platformFeeRefunded) notes = (notes ? notes + '；' : '') + '平台费按假设退回 ' + money4csv(c.platformFeeRefunded);
      if (!isOk) notes = (notes ? notes + '；' : '') + '本单未计入汇总，未参与广告分摊';

      lines.push(csvRow([
        o.id,
        isOk ? '可核算' : '待补',
        money4csv(c.gross),
        money4csv(c.refund),
        money4csv(c.netRevenue),
        money4csv(c.goodsCost),
        money4csv(c.outbound),
        money4csv(c.platformFeeOriginal),
        money4csv(c.platformFeeRefunded),
        money4csv(c.platformFeeCharged),
        money4csv(c.adCharged),
        money4csv(c.returnShipping),
        money4csv(c.recoveryCounted),
        money4csv(c.costTotal),
        money4csv(c.netProfit),
        pct4csv(c.netMargin),
        pct4csv(c.refundRate),
        pct4csv(c.contributionShare),
        o.issues.map(function (x) { return x.fieldLabel; }).join('、'),
        notes
      ]));
    });

    var t = result.totals;
    lines.push(csvRow([
      '合计（可核算 ' + t.okCount + ' 单）',
      t.isComplete ? '完整' : '部分口径',
      money4csv(t.gross), money4csv(t.refund), money4csv(t.netRevenue),
      money4csv(t.goodsCost), money4csv(t.outbound), money4csv(t.platformFeeOriginal),
      money4csv(t.platformFeeRefunded), money4csv(t.platformFeeCharged),
      money4csv(t.adCharged), money4csv(t.returnShipping), money4csv(t.recovery),
      money4csv(t.costTotal), money4csv(t.netProfit), pct4csv(t.netMargin), pct4csv(t.refundRate), '',
      t.pendingCount ? '待补 ' + t.pendingCount + ' 单' : '',
      '销售额不等于净利润，差额为退款与成本'
    ]));
    return '\uFEFF' + lines.join('\r\n') + '\r\n';
  }

  /** 汇总 / 成本构成 / 假设 CSV */
  function toSummaryCSV(result) {
    var t = result.totals;
    var lines = [];
    var push = function (a, b, c) { lines.push(csvRow([a, b, c === undefined ? '' : c])); };

    push('板块', '指标', '数值');
    push('订单', '订单总数', t.orderCount);
    push('订单', '可核算订单数', t.okCount);
    push('订单', '待补订单数', t.pendingCount);
    push('订单', '口径完整性', t.isComplete ? '完整' : '部分口径（待补订单未计入）');
    push('规模', '销售额', money4csv(t.gross));
    push('规模', '退款', money4csv(t.refund));
    push('规模', '净收入', money4csv(t.netRevenue));
    push('规模', '退款率', pct4csv(t.refundRate));
    push('利润', '净利润', money4csv(t.netProfit));
    push('利润', '净利率（对销售额）', pct4csv(t.netMargin));
    push('利润', '净利润率（对净收入）', isNum(t.netRevenue) && t.netRevenue > 0 ? pct4csv(round2(t.netProfit / t.netRevenue * 10000) / 10000) : '待补');
    push('成本', '成本合计', money4csv(t.costTotal));
    result.costStructure.forEach(function (it) {
      push('成本构成', it.label, money4csv(it.amount) + '（占比 ' + pct4csv(it.share) + '）');
    });
    push('退款', '发生退款的订单数', result.refundView.orderCount);
    push('退款', '退款金额', money4csv(result.refundView.refundTotal));
    push('退款', '退回运费', money4csv(result.refundView.returnShippingTotal));
    push('退款', '平台费按假设退回', money4csv(result.refundView.platformFeeRefundedTotal));
    push('退款', '回收价值', money4csv(result.refundView.recoveryTotal));
    push('退款', '退款相关净损失（退款+退回运费−回收）', money4csv(result.refundView.lostProfit));
    push('勾稽', '逐单净利润合计', money4csv(result.reconcile.orderProfitSum));
    push('勾稽', '汇总净利润', money4csv(result.reconcile.totalProfit));
    push('勾稽', '差额', money4csv(result.reconcile.diff));
    push('勾稽', '广告分摊合计 vs 总预算', money4csv(result.reconcile.adAllocatedSum) + ' vs ' + money4csv(result.reconcile.adPool));

    lines.push('');
    push('假设', '序号', '内容');
    result.assumptions.forEach(function (a, i) { push('假设', String(i + 1), a); });
    return '\uFEFF' + lines.join('\r\n') + '\r\n';
  }

  /* ------------------------------------------------------------------ *
   * 导出
   * ------------------------------------------------------------------ */
  return {
    VERSION: VERSION,
    FIELD_DEFS: FIELD_DEFS,
    LABEL: LABEL,
    AD_METHODS: AD_METHODS,
    PLATFORM_METHODS: PLATFORM_METHODS,
    DEFAULTS: DEFAULTS,
    compute: compute,
    toDetailCSV: toDetailCSV,
    toSummaryCSV: toSummaryCSV,
    formatMoney: formatMoney,
    round2: round2,
    toNumber: toNumber,
    allocateByWeight: allocateByWeight
  };
});
