/**
 * scheduler-core.js — 座位轮换与值日安排核心算法（UMD 纯函数模块）
 *
 * 特性：
 *  - 纯函数、无 DOM 依赖、无网络请求、无数据收集；
 *  - UMD：浏览器 <script>、Node require、AMD 均可加载；
 *  - 硬约束优先（固定座位 / 左右分离 / 每人每天恰一座位 / 值日名额精确），
 *    软约束为"其余人员尽量每天换座位"，与硬约束冲突时一律让位于硬约束。
 */
(function (root, factory) {
  "use strict";
  if (typeof module === "object" && module.exports) {
    module.exports = factory();
  } else if (typeof define === "function" && define.amd) {
    define([], factory);
  } else {
    root.SchedulerCore = factory();
  }
})(typeof self !== "undefined" ? self : this, function () {
  "use strict";

  function seatKey(row, col) { return row + "-" + col; }

  /* ---------------- spec 校验 ---------------- */

  function validateSpec(spec) {
    var errors = [];
    if (!spec || typeof spec !== "object") {
      return { ok: false, errors: ["spec 必须为对象"] };
    }
    if (!Array.isArray(spec.people) || spec.people.length === 0) {
      errors.push("people 不能为空");
    } else {
      var seen = {};
      spec.people.forEach(function (p) {
        if (typeof p !== "string" || !p) errors.push("人员名必须为非空字符串");
        if (seen[p]) errors.push("人员重名：" + p);
        seen[p] = true;
      });
    }
    if (!Number.isInteger(spec.rows) || spec.rows < 1) errors.push("rows 必须为正整数");
    if (!Number.isInteger(spec.columns) || spec.columns < 1) errors.push("columns 必须为正整数");
    if (!Array.isArray(spec.days) || spec.days.length === 0) errors.push("days 不能为空");
    if (Array.isArray(spec.people) && Number.isInteger(spec.rows) && Number.isInteger(spec.columns) &&
        spec.rows * spec.columns < spec.people.length) {
      errors.push("座位总数（rows×columns=" + (spec.rows * spec.columns) + "）少于人数");
    }
    var f = spec.fixedSeat;
    if (!f || typeof f !== "object") {
      errors.push("缺少 fixedSeat");
    } else {
      if (!Array.isArray(spec.people) || spec.people.indexOf(f.person) < 0) {
        errors.push("fixedSeat.person 必须在 people 中");
      }
      if (!Number.isInteger(f.row) || f.row < 1 || (Number.isInteger(spec.rows) && f.row > spec.rows)) {
        errors.push("fixedSeat.row 越界");
      }
      if (!Number.isInteger(f.column) || f.column < 1 || (Number.isInteger(spec.columns) && f.column > spec.columns)) {
        errors.push("fixedSeat.column 越界");
      }
    }
    var sep = spec.separateHorizontal || [];
    if (!Array.isArray(sep)) {
      errors.push("separateHorizontal 必须为数组");
    } else {
      sep.forEach(function (p) {
        if (!Array.isArray(spec.people) || spec.people.indexOf(p) < 0) {
          errors.push("separateHorizontal 中的 " + p + " 不在 people 中");
        }
      });
    }
    if (!Number.isInteger(spec.dutyPeoplePerDay) || spec.dutyPeoplePerDay < 1) {
      errors.push("dutyPeoplePerDay 必须为正整数");
    }
    if (!Number.isInteger(spec.eachPersonDutyCount) || spec.eachPersonDutyCount < 0) {
      errors.push("eachPersonDutyCount 必须为非负整数");
    }
    if (Array.isArray(spec.days) && Number.isInteger(spec.dutyPeoplePerDay) &&
        Array.isArray(spec.people) &&
        spec.days.length * spec.dutyPeoplePerDay !== spec.people.length * (spec.eachPersonDutyCount || 0)) {
      errors.push("值日名额总数（天数×每天人数）与人员总配额（人数×每人次数）不相等，无法精确安排");
    }
    return { ok: errors.length === 0, errors: errors };
  }

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

  // 行优先扫描所有座位，跳过 reserved（"row-col" key 数组）中的位置
  function buildSeatOrder(rows, columns, reservedKeys) {
    var reserved = {};
    (reservedKeys || []).forEach(function (k) { reserved[k] = true; });
    var order = [];
    for (var r = 1; r <= rows; r++) {
      for (var c = 1; c <= columns; c++) {
        if (!reserved[seatKey(r, c)]) order.push({ row: r, col: c });
      }
    }
    return order;
  }

  // 字典序全排列（n! 条；本工具仅用于人数 ≤ 8 的小规模场景）
  function permutations(arr) {
    if (arr.length <= 1) return [arr.slice()];
    var result = [];
    (function rec(current, remaining) {
      if (remaining.length === 0) { result.push(current); return; }
      for (var i = 0; i < remaining.length; i++) {
        rec(current.concat(remaining[i]),
            remaining.slice(0, i).concat(remaining.slice(i + 1)));
      }
    })([], arr);
    return result;
  }

  /* ---------------- 排班生成 ---------------- */

  function planDuty(people, dayCount, perDay, eachCount) {
    var flat = [];
    people.forEach(function (p) {
      for (var k = 0; k < eachCount; k++) flat.push(p);
    });
    var total = dayCount * perDay;
    if (flat.length !== total) {
      return { ok: false, error: "值日名额总数(" + total + ")与人员总配额(" + flat.length + ")不一致" };
    }
    var plan = [];
    for (var d = 0; d < dayCount; d++) {
      plan.push(flat.slice(d * perDay, (d + 1) * perDay));
    }
    return { ok: true, plan: plan };
  }

  /**
   * 生成排班。策略：
   *  1) 固定座位人员每天不动（硬约束优先）；
   *  2) 其余人员在剩余座位上按"循环移位"轮换：第 d 天整体移位 d×shift；
   *     对每个候选移位量与基础排列做穷举，取第一个 4 天全部满足硬约束的组合；
   *  3) 值日按人员顺序精确分配（每人恰 eachPersonDutyCount 次）。
   * 返回 { ok:true, schedule } 或 { ok:false, error }。
   */
  function generateSchedule(spec) {
    var chk = validateSpec(spec);
    if (!chk.ok) return { ok: false, error: "spec 无效：" + chk.errors.join("；") };

    var people = spec.people, rows = spec.rows, columns = spec.columns, days = spec.days;
    var fixed = spec.fixedSeat;
    var seatOrder = buildSeatOrder(rows, columns, [seatKey(fixed.row, fixed.column)]);
    var others = people.filter(function (p) { return p !== fixed.person; });
    var sepList = spec.separateHorizontal || [];
    var n = seatOrder.length;

    function buildDaySeats(perm, dayIndex, shift) {
      var seats = [{ row: fixed.row, col: fixed.column, person: fixed.person }];
      for (var i = 0; i < n; i++) {
        var s = seatOrder[(i + dayIndex * shift) % n];
        seats.push({ row: s.row, col: s.col, person: perm[i] });
      }
      seats.sort(function (a, b) { return a.row - b.row || a.col - b.col; });
      return seats;
    }

    function dayViolations(seats) {
      var bySeat = {}, byPerson = {}, v = [];
      seats.forEach(function (s) {
        var k = seatKey(s.row, s.col);
        if (bySeat[k]) v.push("座位(" + s.row + "," + s.col + ")被分配多人：" + bySeat[k] + "/" + s.person);
        bySeat[k] = s.person;
        if (byPerson[s.person]) v.push("人员重复出现：" + s.person);
        byPerson[s.person] = s;
      });
      if (bySeat[seatKey(fixed.row, fixed.column)] !== fixed.person) {
        v.push("固定座位(" + fixed.row + "," + fixed.column + ")未由 " + fixed.person + " 占用");
      }
      people.forEach(function (p) { if (!byPerson[p]) v.push("缺座：" + p); });
      // 同一行左右不相邻（separateHorizontal 列表内任意两人）
      for (var i = 0; i < sepList.length; i++) {
        for (var j = i + 1; j < sepList.length; j++) {
          var a = byPerson[sepList[i]], b = byPerson[sepList[j]];
          if (a && b && a.row === b.row && Math.abs(a.col - b.col) === 1) {
            v.push(sepList[i] + " 与 " + sepList[j] + " 同行左右相邻：(" +
              a.row + "," + a.col + ")-(" + b.row + "," + b.col + ")");
          }
        }
      }
      return v;
    }

    var chosen = null, chosenShift = null;
    for (var shift = 1; shift <= n && !chosen; shift++) {
      var perms = permutations(others);
      for (var pi = 0; pi < perms.length; pi++) {
        var okAll = true;
        for (var d = 0; d < days.length; d++) {
          if (dayViolations(buildDaySeats(perms[pi], d, shift)).length > 0) { okAll = false; break; }
        }
        if (okAll) { chosen = perms[pi]; chosenShift = shift; break; }
      }
    }
    if (!chosen) {
      return { ok: false, error: "在轮换策略下未找到同时满足全部硬约束的方案" };
    }

    var duty = planDuty(people, days.length, spec.dutyPeoplePerDay, spec.eachPersonDutyCount);
    if (!duty.ok) return { ok: false, error: duty.error };

    var schedule = {
      meta: {
        strategy: "固定座位每天不动；其余人员按循环移位轮换（shift=" + chosenShift + "），硬约束优先于轮换效果",
        rotationShift: chosenShift
      },
      days: days.map(function (dayName, d) {
        return { day: dayName, seats: buildDaySeats(chosen, d, chosenShift), duty: duty.plan[d] };
      })
    };
    return { ok: true, schedule: schedule };
  }

  /* ---------------- 约束核对 ---------------- */

  /**
   * 对已生成的 schedule 逐条核对约束。
   * 返回 { ok, checks: [ { id, name, type:"hard"|"soft", scope:"perDay"|"overall",
   *                          days?: {dayName:{pass,detail}}, overall?: {pass,detail} } ] }
   */
  function validateSchedule(spec, schedule) {
    var people = spec.people, days = spec.days, fixed = spec.fixedSeat;
    var sepList = spec.separateHorizontal || [];
    var checks = [];
    var allHardPass = true;

    function perDaySeatIndex(seats) {
      var bySeat = {}, byPerson = {};
      seats.forEach(function (s) {
        bySeat[seatKey(s.row, s.col)] = s.person;
        byPerson[s.person] = s;
      });
      return { bySeat: bySeat, byPerson: byPerson };
    }

    // 1. 固定座位
    var fixedDays = {};
    schedule.days.forEach(function (d) {
      var idx = perDaySeatIndex(d.seats);
      var pass = idx.bySeat[seatKey(fixed.row, fixed.column)] === fixed.person;
      fixedDays[d.day] = {
        pass: pass,
        detail: "座位(" + fixed.row + "," + fixed.column + ")=" + idx.bySeat[seatKey(fixed.row, fixed.column)]
      };
      if (!pass) allHardPass = false;
    });
    checks.push({
      id: "fixedSeat", type: "hard", scope: "perDay", days: fixedDays,
      name: "固定座位：" + fixed.person + " 每天 (第" + fixed.row + "行,第" + fixed.column + "列)"
    });

    // 2. 左右分离（separateHorizontal 内任意两人不得同行相邻）
    var sepDays = {};
    schedule.days.forEach(function (d) {
      var idx = perDaySeatIndex(d.seats);
      var bad = [];
      for (var i = 0; i < sepList.length; i++) {
        for (var j = i + 1; j < sepList.length; j++) {
          var a = idx.byPerson[sepList[i]], b = idx.byPerson[sepList[j]];
          if (a && b && a.row === b.row && Math.abs(a.col - b.col) === 1) {
            bad.push(sepList[i] + "/" + sepList[j] + " 同行相邻");
          }
        }
      }
      sepDays[d.day] = {
        pass: bad.length === 0,
        detail: bad.length ? bad.join("；") :
          sepList.map(function (p) {
            var s = idx.byPerson[p];
            return p + "(" + s.row + "," + s.col + ")";
          }).join(" ")
      };
      if (bad.length) allHardPass = false;
    });
    checks.push({
      id: "separateHorizontal", type: "hard", scope: "perDay", days: sepDays,
      name: "左右分离：" + sepList.join("、") + " 不同行左右相邻"
    });

    // 3. 每人每天恰好一个座位（全员每天只出现一次，无重座/缺座）
    var uniqDays = {};
    schedule.days.forEach(function (d) {
      var problems = [];
      var seatCount = {}, personCount = {};
      d.seats.forEach(function (s) {
        seatCount[seatKey(s.row, s.col)] = (seatCount[seatKey(s.row, s.col)] || 0) + 1;
        personCount[s.person] = (personCount[s.person] || 0) + 1;
      });
      Object.keys(seatCount).forEach(function (k) {
        if (seatCount[k] > 1) problems.push("座位" + k + "重复分配");
      });
      people.forEach(function (p) {
        if (!personCount[p]) problems.push(p + "缺座");
        else if (personCount[p] > 1) problems.push(p + "出现" + personCount[p] + "次");
      });
      if (d.seats.length !== people.length) problems.push("座位条目数=" + d.seats.length);
      uniqDays[d.day] = { pass: problems.length === 0, detail: problems.length ? problems.join("；") : "全员各占一座，无重座无缺座" };
      if (problems.length) allHardPass = false;
    });
    checks.push({
      id: "seatUnique", type: "hard", scope: "perDay", days: uniqDays,
      name: "全员每天只出现一次（恰一座位）"
    });

    // 4. 每天值日人数
    var dutyDayChecks = {};
    schedule.days.forEach(function (d) {
      var pass = Array.isArray(d.duty) && d.duty.length === spec.dutyPeoplePerDay;
      dutyDayChecks[d.day] = { pass: pass, detail: "值日：" + (d.duty || []).join("、") };
      if (!pass) allHardPass = false;
    });
    checks.push({
      id: "dutyPerDay", type: "hard", scope: "perDay", days: dutyDayChecks,
      name: "每天值日 " + spec.dutyPeoplePerDay + " 人"
    });

    // 5. 每人值日次数（整体）
    var dutyCount = {};
    people.forEach(function (p) { dutyCount[p] = 0; });
    schedule.days.forEach(function (d) {
      (d.duty || []).forEach(function (p) {
        if (dutyCount[p] !== undefined) dutyCount[p]++;
      });
    });
    var dutyBad = people.filter(function (p) { return dutyCount[p] !== spec.eachPersonDutyCount; });
    checks.push({
      id: "dutyExact", type: "hard", scope: "overall",
      overall: {
        pass: dutyBad.length === 0,
        detail: dutyBad.length ? "异常：" + dutyBad.join("、") :
          people.map(function (p) { return p + "×" + dutyCount[p]; }).join("，")
      },
      name: "4 天内每人值日恰 " + spec.eachPersonDutyCount + " 次"
    });
    if (dutyBad.length) allHardPass = false;

    // 6. 座位轮换（软约束：除固定座位人员外，其余人员 4 天座位互不相同）
    var rotationOK = true, rotationDetail = [];
    var seatsOf = {};
    people.forEach(function (p) { seatsOf[p] = []; });
    schedule.days.forEach(function (d) {
      d.seats.forEach(function (s) {
        if (seatsOf[s.person]) seatsOf[s.person].push(seatKey(s.row, s.col));
      });
    });
    people.forEach(function (p) {
      if (p === fixed.person) return;
      var uniq = {};
      seatsOf[p].forEach(function (k) { uniq[k] = true; });
      if (Object.keys(uniq).length !== seatsOf[p].length) rotationOK = false;
      rotationDetail.push(p + ":" + seatsOf[p].join("→"));
    });
    checks.push({
      id: "rotation", type: "soft", scope: "overall",
      overall: {
        pass: rotationOK,
        detail: rotationOK ? rotationDetail.join("；") : "存在人员 4 天内座位未变化：" +
          people.filter(function (p) {
            if (p === fixed.person) return false;
            var uniq = {};
            seatsOf[p].forEach(function (k) { uniq[k] = true; });
            return Object.keys(uniq).length !== seatsOf[p].length;
          }).join("、")
      },
      name: "座位轮换（软约束，固定座位除外）"
    });

    return { ok: allHardPass, checks: checks };
  }

  /* ---------------- 冲突演示：同一座位分配两人 → 无解 ---------------- */

  /**
   * 求解"同一固定座位分配两人"的冲突场景。
   * sameSeat: [[person, row, col], ...]（与 spec.infeasibleCase.sameSeat 同构）
   * 一旦发现同一座位被要求分给 ≥2 人（或与 fixedSeat 冲突），
   * 立即判定无解，且不输出任何座位安排。
   */
  function solveSameSeatConflict(spec, sameSeat) {
    var entries = (sameSeat || []).map(function (e) {
      return { person: e[0], row: e[1], col: e[2] };
    });
    var bySeat = {};
    entries.forEach(function (e) {
      var k = seatKey(e.row, e.col);
      if (!bySeat[k]) bySeat[k] = { row: e.row, col: e.col, persons: [] };
      bySeat[k].persons.push(e.person);
    });
    var conflicts = Object.keys(bySeat).map(function (k) { return bySeat[k]; })
      .filter(function (g) { return g.persons.length > 1; });
    var f = spec.fixedSeat;
    var clashWithFixed = entries.filter(function (e) {
      return e.person !== f.person && e.row === f.row && e.col === f.column;
    });
    if (conflicts.length > 0 || clashWithFixed.length > 0) {
      var lines = conflicts.map(function (g) {
        return "座位(第" + g.row + "行,第" + g.col + "列)被同时固定给：" + g.persons.join("、");
      });
      clashWithFixed.forEach(function (e) {
        lines.push(e.person + " 与固定座位人员 " + f.person + " 冲突：座位(第" + e.row + "行,第" + e.col + "列)只能容纳一人");
      });
      return {
        ok: false,
        infeasible: true,
        reason: "一个座位在同一时刻只能容纳一人（鸽笼原理）。",
        conflicts: conflicts,
        clashWithFixed: clashWithFixed.map(function (e) { return e.person + "@" + e.row + "-" + e.col; }),
        rejectedInput: entries,
        conclusion: "无解：本工具拒绝输出任何违规座位安排。"
      };
    }
    // 无冲突时退回正常求解
    return generateSchedule(spec);
  }

  /* ---------------- 导出 ---------------- */

  function toCSV(schedule) {
    var lines = ["类型,日期,行,列,人员"];
    schedule.days.forEach(function (d) {
      d.seats.forEach(function (s) {
        lines.push(["座位", d.day, s.row, s.col, s.person].join(","));
      });
      (d.duty || []).forEach(function (p) {
        lines.push(["值日", d.day, "", "", p].join(","));
      });
    });
    // \ufeff BOM：保证 Excel 直接打开不乱码
    return "\ufeff" + lines.join("\r\n") + "\r\n";
  }

  function toJSON(spec, schedule) {
    return JSON.stringify({
      note: (spec && spec.note) || "",
      meta: schedule.meta,
      days: schedule.days.map(function (d) {
        return {
          day: d.day,
          seats: d.seats.map(function (s) { return { row: s.row, col: s.col, person: s.person }; }),
          duty: d.duty
        };
      })
    }, null, 2);
  }

  return {
    validateSpec: validateSpec,
    generateSchedule: generateSchedule,
    validateSchedule: validateSchedule,
    solveSameSeatConflict: solveSameSeatConflict,
    toCSV: toCSV,
    toJSON: toJSON
  };
});
