/*!
 * D43 离线租房比较器 · 核心计算模块 rent-core.js
 * ------------------------------------------------------------
 * UMD：Node（CommonJS）与浏览器（window.RentCore）双端可用。
 * 纯函数、无 DOM、无网络、无依赖、无随机数，便于直接测试与复用。
 *
 * 核心口径：
 *   年度消费成本 = 12 × (月租 + 月服务费) + 一次性费用
 *   可退占款     = 押金（不计入消费成本）
 *   首期现金     = 押金 + 首月租金 + 首月服务费 + 一次性费用
 * 缺失值一律保留为 null / "待补"，绝不默认按 0 计算。
 */
(function (root, factory) {
  if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else {
    root.RentCore = factory();
  }
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
  "use strict";

  var MONTHS = 12;
  var MAX_AMOUNT = 1000000000; // 单值上限，防误输入

  var DEFAULT_WEIGHTS = { cost: 40, commute: 30, area: 30 };

  var DIMENSIONS = [
    {
      key: "cost",
      label: "年度成本",
      short: "成本",
      rawKey: "annualCost",
      direction: "lower",
      unit: "元/年"
    },
    {
      key: "commute",
      label: "通勤时间",
      short: "通勤",
      rawKey: "commuteMinutes",
      direction: "lower",
      unit: "分钟"
    },
    {
      key: "area",
      label: "使用面积",
      short: "面积",
      rawKey: "area",
      direction: "higher",
      unit: "㎡"
    }
  ];

  var FIELD_LABELS = {
    rent: "月租",
    service: "月服务费",
    oneTimeFee: "一次性费用",
    deposit: "押金",
    commuteMinutes: "通勤时间",
    area: "面积"
  };

  var COST_FIELDS = ["rent", "service", "oneTimeFee"];

  function isFiniteNumber(value) {
    return typeof value === "number" && isFinite(value);
  }

  function round(value, digits) {
    var factor = Math.pow(10, digits);
    return Math.round((value + Number.EPSILON) * factor) / factor;
  }

  /** 全角数字/小数点/逗号转半角，便于手机中文输入法。 */
  function toHalfWidth(value) {
    return String(value)
      .replace(/[\uFF10-\uFF19]/g, function (ch) {
        return String.fromCharCode(ch.charCodeAt(0) - 0xfee0);
      })
      .replace(/\uFF0E/g, ".")
      .replace(/\uFF0C/g, "")
      .replace(/\u3000/g, " ")
      .trim();
  }

  /**
   * 解析用户输入的数字（支持数字或字符串）。
   * 返回 { ok, value } 或 { ok:false, error }。
   * 空串明确报“不能为空”，不会被 Number("") 悄悄变成 0。
   */
  function parseNumberInput(raw) {
    if (raw === null || raw === undefined) {
      return { ok: false, error: "不能为空" };
    }
    if (typeof raw === "number") {
      if (!isFinite(raw)) return { ok: false, error: "必须是有效数字" };
      if (raw < 0) return { ok: false, error: "不能为负数" };
      if (raw > MAX_AMOUNT) return { ok: false, error: "数值过大" };
      return { ok: true, value: raw };
    }
    if (typeof raw === "string") {
      var text = toHalfWidth(raw).replace(/,/g, "");
      if (text === "") return { ok: false, error: "不能为空" };
      if (!/^[+-]?(\d+(\.\d*)?|\.\d+)$/.test(text)) {
        return { ok: false, error: "请输入有效数字" };
      }
      var number = Number(text);
      if (!isFinite(number)) return { ok: false, error: "必须是有效数字" };
      if (number < 0) return { ok: false, error: "不能为负数" };
      if (number > MAX_AMOUNT) return { ok: false, error: "数值过大" };
      return { ok: true, value: number };
    }
    return { ok: false, error: "请输入有效数字" };
  }

  function asAmount(value) {
    return isFiniteNumber(value) && value >= 0 ? value : null;
  }

  /**
   * 计算单套房源。
   * 返回的 annualCost / firstCash 在费用缺失时为 null（而不是 0）。
   */
  function computeHome(home) {
    var source = home || {};
    var rent = asAmount(source.rent);
    var service = asAmount(source.service);
    var oneTimeFee = asAmount(source.oneTimeFee);
    var deposit = asAmount(source.deposit);
    var commuteMinutes = asAmount(source.commuteMinutes);
    var area = asAmount(source.area);

    var missingKeys = [];
    if (rent === null) missingKeys.push("rent");
    if (service === null) missingKeys.push("service");
    if (oneTimeFee === null) missingKeys.push("oneTimeFee");
    if (deposit === null) missingKeys.push("deposit");
    if (commuteMinutes === null) missingKeys.push("commuteMinutes");
    if (area === null) missingKeys.push("area");

    var monthlyTotal =
      rent !== null && service !== null ? rent + service : null;
    var annualCost =
      monthlyTotal !== null && oneTimeFee !== null
        ? MONTHS * monthlyTotal + oneTimeFee
        : null;
    // 首期现金含首月租金与服务费；服务费未知时首期现金也不臆测。
    var firstCash =
      deposit !== null && monthlyTotal !== null && oneTimeFee !== null
        ? deposit + monthlyTotal + oneTimeFee
        : null;

    return {
      id: String(source.id === undefined || source.id === null ? "" : source.id),
      name: String(
        source.name === undefined || source.name === null
          ? source.id || "未命名房源"
          : source.name
      ),
      rent: rent,
      service: service,
      oneTimeFee: oneTimeFee,
      deposit: deposit,
      commuteMinutes: commuteMinutes,
      area: area,
      monthlyTotal: monthlyTotal,
      annualCost: annualCost,
      refundableDeposit: deposit,
      firstCash: firstCash,
      costKnown: annualCost !== null,
      supplemented: !!source.supplemented,
      missingKeys: missingKeys,
      missingLabels: missingKeys.map(function (key) {
        return FIELD_LABELS[key];
      }),
      // 以下字段由 evaluate 填充
      eligible: false,
      exclusionReasons: [],
      norm: { cost: null, commute: null, area: null },
      contrib: { cost: null, commute: null, area: null },
      score: null,
      costRank: null,
      compositeRank: null,
      costRankTied: false,
      compositeRankTied: false
    };
  }

  /**
   * 权重校验与归一化：wᵢ = Wᵢ / ΣW。
   * 负权重、空值、非数字、总和为 0 都返回错误，不猜默认值。
   */
  function normalizeWeights(weights) {
    var input = weights || {};
    var raw = {};
    var errors = [];
    var sum = 0;

    DIMENSIONS.forEach(function (dim) {
      var parsed = parseNumberInput(input[dim.key]);
      if (!parsed.ok) {
        raw[dim.key] = null;
        errors.push({
          key: dim.key,
          label: dim.label,
          message: dim.label + "权重" + parsed.error
        });
      } else {
        raw[dim.key] = parsed.value;
        sum += parsed.value;
      }
    });

    if (errors.length === 0 && sum <= 0) {
      errors.push({
        key: "sum",
        label: "权重合计",
        message: "三项权重之和必须大于 0，否则无法计算加权分"
      });
    }

    var normalized = null;
    if (errors.length === 0) {
      normalized = {};
      DIMENSIONS.forEach(function (dim) {
        normalized[dim.key] = raw[dim.key] / sum;
      });
    }

    return {
      ok: errors.length === 0,
      errors: errors,
      raw: raw,
      sum: sum,
      normalized: normalized
    };
  }

  /** 竞技排名：同值同名次，后续名次跳号（1, 1, 3）。入参需按分数从高到低排好。 */
  function competitionRankMap(entries) {
    var map = {};
    var previous = null;
    var rank = 0;
    entries.forEach(function (entry, index) {
      if (previous === null || Math.abs(entry.value - previous) > 1e-9) {
        rank = index + 1;
        previous = entry.value;
      }
      map[entry.id] = rank;
    });
    return map;
  }

  function countRanks(rows, key) {
    var counts = {};
    rows.forEach(function (row) {
      if (row[key] !== null && row[key] !== undefined) {
        counts[row[key]] = (counts[row[key]] || 0) + 1;
      }
    });
    return counts;
  }

  /** 低价排名（只看年度成本，成本可算即可参与）。 */
  function rankLowPrice(rows) {
    var entries = rows
      .filter(function (row) {
        return row.costKnown;
      })
      .map(function (row) {
        return { id: row.id, value: -row.annualCost }; // 成本越低，排序值越高
      })
      .sort(function (a, b) {
        return b.value - a.value;
      });
    return competitionRankMap(entries);
  }

  /**
   * 归一化并计算综合分。
   * - 只在“参与综合排名”的房源池内做 min-max；
   * - 成本/通勤为负向：(max - x) / (max - min)；
   * - 面积为正向：(x - min) / (max - min)；
   * - 区间为 0 时统一记 1（无区分度），避免除以 0 或强行拉开差距。
   */
  function scorePool(pool, normalizedWeights) {
    var dimensionStats = {};
    var rows = pool.slice();

    DIMENSIONS.forEach(function (dim) {
      var values = rows.map(function (row) {
        return row[dim.rawKey];
      });
      var min = Math.min.apply(null, values);
      var max = Math.max.apply(null, values);
      var zeroRange = Math.abs(max - min) < 1e-12;

      dimensionStats[dim.key] = {
        min: min,
        max: max,
        zeroRange: zeroRange
      };

      rows.forEach(function (row) {
        var value = row[dim.rawKey];
        var norm;
        if (zeroRange) {
          norm = 1;
        } else if (dim.direction === "lower") {
          norm = (max - value) / (max - min);
        } else {
          norm = (value - min) / (max - min);
        }
        row.norm[dim.key] = norm;
        row.contrib[dim.key] = normalizedWeights[dim.key] * norm;
      });
    });

    rows.forEach(function (row) {
      var total = 0;
      DIMENSIONS.forEach(function (dim) {
        total += row.contrib[dim.key];
      });
      row.score = round(total * 100, 6);
    });

    var ranked = rows
      .slice()
      .sort(function (a, b) {
        return b.score - a.score;
      })
      .map(function (row) {
        return { id: row.id, value: row.score };
      });

    return {
      pool: rows,
      dimensionStats: dimensionStats,
      rankMap: competitionRankMap(ranked)
    };
  }

  function makeSummary(rows, weights) {
    var costKnown = rows.filter(function (row) {
      return row.costKnown;
    });
    var firstCashKnown = rows.filter(function (row) {
      return row.firstCash !== null;
    });
    var eligible = rows.filter(function (row) {
      return row.eligible;
    });

    function cheapestOf(list, key) {
      if (!list.length) return null;
      var min = Math.min.apply(
        null,
        list.map(function (item) {
          return item[key];
        })
      );
      var homes = list
        .filter(function (item) {
          return Math.abs(item[key] - min) < 1e-9;
        })
        .map(function (item) {
          return { id: item.id, name: item.name };
        });
      return {
        value: min,
        homes: homes,
        tied: homes.length > 1
      };
    }

    return {
      total: rows.length,
      costKnownCount: costKnown.length,
      eligibleCount: eligible.length,
      pendingCostCount: rows.length - costKnown.length,
      pendingCostHomes: rows
        .filter(function (row) {
          return !row.costKnown;
        })
        .map(function (row) {
          return { id: row.id, name: row.name, missingLabels: row.missingLabels };
        }),
      missingServiceCount: rows.filter(function (row) {
        return row.service === null;
      }).length,
      cheapest: cheapestOf(costKnown, "annualCost"),
      lowestFirstCash: cheapestOf(firstCashKnown, "firstCash"),
      singleCandidate: eligible.length === 1,
      rankingPaused: !weights.ok
    };
  }

  /**
   * 主计算入口。
   * @param {Array} homes 房源数据
   * @param {{cost:number,commute:number,area:number}} weights 原始相对权重
   */
  function evaluate(homes, weights) {
    var inputHomes = Array.isArray(homes) ? homes : [];
    var weightResult = normalizeWeights(weights || DEFAULT_WEIGHTS);
    var rows = inputHomes.map(computeHome);

    // 1) 低价排名：只要求年成本可算，与权重无关。
    var lowPriceRanks = rankLowPrice(rows);
    rows.forEach(function (row) {
      row.costRank = lowPriceRanks[row.id] === undefined ? null : lowPriceRanks[row.id];
    });

    var result = {
      ok: weightResult.ok,
      errors: weightResult.errors,
      weightsRaw: weightResult.raw,
      weightsSum: weightResult.sum,
      weights: weightResult.normalized,
      rankingPaused: !weightResult.ok,
      months: MONTHS,
      rows: rows,
      dimensions: DIMENSIONS.map(function (dim) {
        return {
          key: dim.key,
          label: dim.label,
          short: dim.short,
          rawKey: dim.rawKey,
          direction: dim.direction,
          unit: dim.unit
        };
      }),
      dimensionStats: null
    };

    // 2) 综合排名资格：成本必须可算（核心指标）；有权重（>0）的维度必须有数据。
    if (weightResult.ok) {
      rows.forEach(function (row) {
        var reasons = [];
        if (!row.costKnown) {
          reasons.push("年度成本未知（缺费用），不参与综合排名");
        }
        if (
          weightResult.normalized.commute > 0 &&
          row.commuteMinutes === null
        ) {
          reasons.push("通勤时间缺失，不参与综合排名（不以 0 分代替）");
        }
        if (weightResult.normalized.area > 0 && row.area === null) {
          reasons.push("面积缺失，不参与综合排名（不以 0 分代替）");
        }
        row.exclusionReasons = reasons;
        row.eligible = reasons.length === 0;
      });
    } else {
      rows.forEach(function (row) {
        row.eligible = false;
        row.exclusionReasons = ["权重输入有误，综合排名暂停"];
      });
    }

    // 3) 综合评分与名次。
    if (weightResult.ok) {
      var pool = rows.filter(function (row) {
        return row.eligible;
      });
      if (pool.length > 0) {
        var scored = scorePool(pool, weightResult.normalized);
        result.dimensionStats = scored.dimensionStats;
        scored.pool.forEach(function (row) {
          row.compositeRank = scored.rankMap[row.id];
        });
      }
    }

    // 4) 并列标记。
    var costCounts = countRanks(rows, "costRank");
    var compositeCounts = countRanks(rows, "compositeRank");
    rows.forEach(function (row) {
      row.costRankTied =
        row.costRank !== null && (costCounts[row.costRank] || 0) > 1;
      row.compositeRankTied =
        row.compositeRank !== null &&
        (compositeCounts[row.compositeRank] || 0) > 1;
    });

    result.summary = makeSummary(rows, weightResult);
    return result;
  }

  /** 元 → "¥1,234.50"；缺失返回“待补”，不把 null 变成 0。 */
  function formatNumber(value, digits) {
    if (!isFiniteNumber(value)) return "待补";
    var d = digits === undefined ? 0 : digits;
    var text = round(value, d).toFixed(d);
    var parts = text.split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
  }

  function formatMoney(value) {
    if (!isFiniteNumber(value)) return "待补";
    var sign = value < 0 ? "-" : "";
    var text = formatNumber(Math.abs(value), 2).replace(/\.00$/, "");
    return sign + "¥" + text;
  }

  /** 纯数字 CSV 值：不带千分位、不带货币符号。 */
  function csvNumber(value) {
    if (!isFiniteNumber(value)) return "待补";
    return String(round(value, 2));
  }

  function csvCell(value) {
    var text = value === null || value === undefined ? "" : String(value);
    if (/[",\r\n]/.test(text)) {
      return '"' + text.replace(/"/g, '""') + '"';
    }
    return text;
  }

  function describeRow(row, result) {
    var parts = [];
    if (row.supplemented) parts.push("月服务费由用户补齐");
    if (!row.costKnown) {
      var missingCostLabels = row.missingKeys
        .filter(function (key) {
          return COST_FIELDS.indexOf(key) !== -1;
        })
        .map(function (key) {
          return FIELD_LABELS[key];
        });
      parts.push(
        "缺" +
          missingCostLabels.join("、") +
          "，年度成本与首期现金无法计算，不参与低价排名"
      );
    }
    if (!result.rankingPaused) {
      if (row.eligible) {
        parts.push("数据完整，参与综合排名");
      } else if (row.exclusionReasons.length) {
        parts.push(row.exclusionReasons.join("；"));
      }
    } else {
      parts.push("权重输入有误，综合排名暂停");
    }
    return parts.join("；");
  }

  function rowStatus(row, result) {
    if (!row.costKnown) return "成本待补，不参与排名";
    if (result.rankingPaused) return "权重待修正，综合排名暂停";
    if (!row.eligible) return "缺项，不参与综合排名";
    return "参与综合排名";
  }

  /**
   * 导出 CSV：UTF-8 BOM + CRLF，数值不分组，缺失写“待补”。
   * 可直接用 Excel / Numbers / 表格软件打开。
   */
  function buildCsv(result) {
    var headers = [
      "编号",
      "名称",
      "月租(元)",
      "月服务费(元)",
      "一次性费用(元)",
      "年度消费成本(元)",
      "押金/可退占款(元)",
      "首期现金(元)",
      "通勤(分钟)",
      "面积(㎡)",
      "成本归一",
      "通勤归一",
      "面积归一",
      "成本权重(归一)",
      "通勤权重(归一)",
      "面积权重(归一)",
      "综合分",
      "年成本名次",
      "综合名次",
      "状态",
      "说明"
    ];

    function normText(row, key) {
      return isFiniteNumber(row.norm[key])
        ? round(row.norm[key], 4).toFixed(4)
        : "—";
    }

    function weightText(key) {
      return result.weights && isFiniteNumber(result.weights[key])
        ? round(result.weights[key], 4).toFixed(4)
        : "—";
    }

    var lines = [headers.map(csvCell).join(",")];

    result.rows.forEach(function (row) {
      var values = [
        row.id,
        row.name,
        csvNumber(row.rent),
        csvNumber(row.service),
        csvNumber(row.oneTimeFee),
        csvNumber(row.annualCost),
        csvNumber(row.refundableDeposit),
        csvNumber(row.firstCash),
        csvNumber(row.commuteMinutes),
        csvNumber(row.area),
        normText(row, "cost"),
        normText(row, "commute"),
        normText(row, "area"),
        weightText("cost"),
        weightText("commute"),
        weightText("area"),
        isFiniteNumber(row.score) ? row.score.toFixed(2) : "—",
        row.costRank === null ? "—" : row.costRank,
        row.compositeRank === null ? "—" : row.compositeRank,
        rowStatus(row, result),
        describeRow(row, result)
      ];
      lines.push(values.map(csvCell).join(","));
    });

    return "\uFEFF" + lines.join("\r\n") + "\r\n";
  }

  /**
   * 补齐某套房源的月服务费（纯函数，返回新数组）。
   * 空值、负数、非数字都会拒绝，并保持原数据不变。
   */
  function applyServiceFee(homes, id, rawValue) {
    var parsed = parseNumberInput(rawValue);
    var list = Array.isArray(homes) ? homes : [];
    if (!parsed.ok) {
      return { ok: false, error: parsed.error, homes: cloneHomes(list) };
    }
    var found = false;
    var next = list.map(function (home) {
      if (home.id !== id) return Object.assign({}, home);
      found = true;
      return Object.assign({}, home, {
        service: parsed.value,
        supplemented: true
      });
    });
    if (!found) {
      return { ok: false, error: "未找到该房源", homes: next };
    }
    return { ok: true, value: parsed.value, homes: next };
  }

  /** 撤销补齐：把服务费恢复为缺失（null），不默认写 0。 */
  function clearServiceFee(homes, id) {
    return (Array.isArray(homes) ? homes : []).map(function (home) {
      if (home.id !== id) return Object.assign({}, home);
      return Object.assign({}, home, { service: null, supplemented: false });
    });
  }

  /** 深拷贝房源，重置时不会污染初始数据。 */
  function cloneHomes(homes) {
    return (Array.isArray(homes) ? homes : []).map(function (home) {
      return Object.assign({}, home);
    });
  }

  return {
    MONTHS: MONTHS,
    MAX_AMOUNT: MAX_AMOUNT,
    DEFAULT_WEIGHTS: DEFAULT_WEIGHTS,
    DIMENSIONS: DIMENSIONS,
    FIELD_LABELS: FIELD_LABELS,
    parseNumberInput: parseNumberInput,
    normalizeWeights: normalizeWeights,
    computeHome: computeHome,
    evaluate: evaluate,
    applyServiceFee: applyServiceFee,
    clearServiceFee: clearServiceFee,
    buildCsv: buildCsv,
    formatMoney: formatMoney,
    formatNumber: formatNumber,
    round: round,
    cloneHomes: cloneHomes
  };
});