import * as N from "three";
const ot = 300;
function W(t) {
  const u = [t[12], t[13], t[14]], a = t[0], o = t[4], r = t[8], l = t[1], x = t[5], $ = t[9], e = t[2], h = t[6], m = t[10], S = Math.sqrt(a * a + l * l + e * e), A = Math.sqrt(o * o + x * x + h * h), b = Math.sqrt(r * r + $ * $ + m * m), E = [S, A, b], j = [a / S, o / A, r / b, l / S, x / A, $ / b, e / S, h / A, m / b], O = et(j);
  return { position: u, quaternion: O, scale: E };
}
function et(t) {
  const u = t[0] + t[4] + t[8];
  let a, o = [0, 0, 0, 0];
  return u > 0 ? (a = Math.sqrt(u + 1) * 2, o[3] = 0.25 * a, o[0] = (t[7] - t[5]) / a, o[1] = (t[2] - t[6]) / a, o[2] = (t[3] - t[1]) / a) : t[0] > t[4] && t[0] > t[8] ? (a = Math.sqrt(1 + t[0] - t[4] - t[8]) * 2, o[3] = (t[7] - t[5]) / a, o[0] = 0.25 * a, o[1] = (t[1] + t[3]) / a, o[2] = (t[2] + t[6]) / a) : t[4] > t[8] ? (a = Math.sqrt(1 + t[4] - t[0] - t[8]) * 2, o[3] = (t[2] - t[6]) / a, o[0] = (t[1] + t[3]) / a, o[1] = 0.25 * a, o[2] = (t[5] + t[7]) / a) : (a = Math.sqrt(1 + t[8] - t[0] - t[4]) * 2, o[3] = (t[3] - t[1]) / a, o[0] = (t[2] + t[6]) / a, o[1] = (t[5] + t[7]) / a, o[2] = 0.25 * a), o;
}
function st({ x: t, y: u, z: a, order: o = "XYZ" }) {
  const r = Math.cos(t / 2), l = Math.cos(u / 2), x = Math.cos(a / 2), $ = Math.sin(t / 2), e = Math.sin(u / 2), h = Math.sin(a / 2);
  let m, S, A, b;
  switch (o) {
    case "XYZ":
      m = $ * l * x + r * e * h, S = r * e * x - $ * l * h, A = r * l * h + $ * e * x, b = r * l * x - $ * e * h;
      break;
    default:
      m = $ * l * x + r * e * h, S = r * e * x - $ * l * h, A = r * l * h + $ * e * x, b = r * l * x - $ * e * h;
  }
  return [m, S, A, b];
}
function k(t) {
  if (typeof t == "string" && !isNaN(Number(t)))
    return [0, -(Number(t) * Math.PI) / 180, 0];
  if (Array.isArray(t) && t.length === 3)
    return [t[0], -t[1], t[2]];
}
function D(t, u) {
  if (!u)
    return t;
  const a = st({ x: u[0], y: u[1], z: u[2] }), [o, r, l, x] = a, [$, e, h, m] = t;
  return [
    x * $ + o * m + r * h - l * e,
    x * e - o * h + r * m + l * $,
    x * h + o * e - r * $ + l * m,
    x * m - o * $ - r * e - l * h
  ];
}
function at(t, u) {
  const a = new N.Vector3(u.x - t.x, u.y - t.y, u.z - t.z).normalize(), o = new N.Vector3(0, 0, 1), r = new N.Quaternion();
  return r.setFromUnitVectors(o, a), [r.x, r.y, r.z, r.w];
}
function rt(t, u = 0, a = 300) {
  var H, L, V, J;
  if (!((H = t.track) != null && H.path) || t.track.path.length === 0) {
    const i = W(t.matrix), n = [
      {
        visible: !0,
        timeStamp: 0 + u,
        position: i.position,
        quaternion: i.quaternion,
        scale: i.scale
      }
    ];
    return {
      name: t.name || "默认角色",
      type: "model",
      model: t.modelUrl,
      keyframes: n
    };
  }
  const o = W(t.matrix);
  let r = o.quaternion.slice();
  const l = t.track.points.find(
    (i) => Math.abs(i.point.x - o.position[0]) < 1e-3 && Math.abs(i.point.y - o.position[1]) < 1e-3 && Math.abs(i.point.z - o.position[2]) < 1e-3
  );
  let x = t.animationUrl, $ = t.repeat === "loop";
  const e = [], h = [];
  if (l) {
    let i = 0;
    for (const n of l.actions)
      if (n.duration > 0) {
        const s = typeof n.animationUrl == "string" && n.animationUrl && n.animationUrl.trim() && n.animationUrl !== "none" && n.animationUrl !== "x_turn";
        m({
          visible: !0,
          timeStamp: i,
          position: o.position,
          quaternion: r,
          scale: o.scale,
          animation: {
            url: s ? n.animationUrl : t.animationUrl,
            repeat: !s || (n == null ? void 0 : n.repeat),
            needRender: s,
            item: (L = n.subAction) != null && L.url ? n.subAction : void 0
          }
        }), i += n.duration * 1e3;
      }
    if (!l.actions.some((n) => n.duration > 0)) {
      const n = l.actions.find((s) => s.duration > 0 && s.animationUrl !== "none");
      n ? (x = n.animationUrl, $ = !1, console.log(`初始位置与action point重合，使用动作动画: ${x}`)) : console.log("初始位置与action point重合，但没有有效动作，使用默认动画");
    }
  } else
    console.log("初始位置独立，使用默认移动动画");
  function m(i) {
    var s, y, d;
    i.timeStamp += u, i.animation.url === "none" && delete i.animation;
    const n = e.findIndex((M) => M.timeStamp === i.timeStamp);
    n !== -1 ? ((s = e[n].animation) == null ? void 0 : s.url) !== ((y = i.animation) == null ? void 0 : y.url) && i.animation && ((d = i.animation) == null ? void 0 : d.url) !== t.animationUrl && (e[n] = i) : e.push(i);
  }
  m({
    visible: !0,
    timeStamp: 0,
    position: o.position,
    quaternion: r,
    scale: o.scale,
    animation: {
      url: x,
      repeat: $
    }
  });
  let S = 0;
  if (l) {
    let i = 0;
    for (const n of l.actions)
      if (n.duration > 0 || n.animationUrl === "x_turn") {
        if (n.animationUrl === "x_turn") {
          n.duration = 1;
          const s = k(n.rotation);
          s && (r = D(r, s));
        }
        i += n.duration * 1e3, S += n.duration * 1e3, m({
          visible: !0,
          timeStamp: i,
          position: o.position,
          quaternion: r,
          scale: o.scale,
          animation: {
            url: t.animationUrl,
            // 恢复默认移动动画
            repeat: t.repeat === "loop"
          }
        });
      }
    i > 0 && h.push({ start: 0 + u, end: i + u }), console.log(`初始action point处理完成，总延迟: ${S}ms`);
  }
  function A(i, n) {
    return Math.sqrt(Math.pow(n.x - i.x, 2) + Math.pow(n.y - i.y, 2) + Math.pow(n.z - i.z, 2));
  }
  let b = 0;
  const E = [];
  for (let i = 0; i < t.track.path.length - 1; i++) {
    const n = A(t.track.path[i], t.track.path[i + 1]);
    E.push(n), b += n;
  }
  const j = b / t.track.duration;
  console.log(`路径分析:
    - 总距离: ${b.toFixed(2)}
    - 移动时间: ${t.track.duration}s
    - 移动速度: ${j.toFixed(2)} 单位/秒
    - 路径段距离: [${E.map((i) => i.toFixed(2)).join(", ")}]`);
  const O = /* @__PURE__ */ new Map();
  for (const i of t.track.points) {
    const n = `${i.point.x.toFixed(3)}_${i.point.y.toFixed(3)}_${i.point.z.toFixed(3)}`;
    let s = 1 / 0, y = 0;
    for (let d = 0; d < t.track.path.length - 1; d++) {
      const M = tt(i.point, t.track.path[d], t.track.path[d + 1]);
      M < s && (s = M, y = d);
    }
    O.set(n, y);
  }
  let _ = S, B = 0;
  const G = /* @__PURE__ */ new Set();
  for (let i = 0; i < t.track.path.length - 1; i++) {
    const n = t.track.path[i], s = t.track.path[i + 1], y = E[i], d = B / b * t.track.duration * 1e3;
    B += y;
    const M = B / b * t.track.duration * 1e3, w = d + _, Q = M + _;
    console.log(
      `路径段${i}: 距离${y.toFixed(2)}, 基础时间${d.toFixed(0)}-${M.toFixed(
        0
      )}ms, 实际时间${w.toFixed(0)}-${Q.toFixed(0)}ms`
    ), m({
      visible: !0,
      timeStamp: w,
      position: [n.x, n.y, n.z],
      quaternion: r,
      scale: o.scale,
      animation: {
        url: t.animationUrl,
        // 默认移动动画
        repeat: t.repeat === "loop"
      }
    });
    for (const c of t.track.points) {
      if (l && c === l && i === 0) {
        console.log("跳过初始action point，已在初始关键帧中处理");
        continue;
      }
      const T = `${c.point.x.toFixed(3)}_${c.point.y.toFixed(3)}_${c.point.z.toFixed(3)}`;
      if (G.has(T)) {
        console.log(`跳过已处理的点位: [${c.point.x.toFixed(2)}, ${c.point.y.toFixed(2)}, ${c.point.z.toFixed(2)}]`);
        continue;
      }
      if (O.get(T) === i) {
        const z = nt(c.point, n, s), g = B - y + y * z, F = g / b * t.track.duration * 1e3 + _;
        console.log(
          `Action点: 位置[${c.point.x.toFixed(2)}, ${c.point.y.toFixed(2)}, ${c.point.z.toFixed(
            2
          )}], 距离${g.toFixed(2)}, 到达时间${F.toFixed(0)}ms`
        );
        let U = t.animationUrl;
        const q = c.actions.find((p) => p.duration > 0 && p.animationUrl !== "none"), P = q == null ? void 0 : q.subAction;
        q ? (U = q.animationUrl, q.duration > 2, console.log(`到达动作点，使用该点的动画: ${U}`)) : console.log("动作点没有有效动作，使用默认移动动画"), m({
          visible: !0,
          timeStamp: F,
          position: [c.point.x, c.point.y, c.point.z],
          quaternion: r,
          scale: o.scale,
          animation: {
            url: U,
            item: P != null && P.url ? P : void 0,
            repeat: q == null ? void 0 : q.repeat,
            duration: q == null ? void 0 : q.duration
          }
        });
        let I = F, K = 0;
        for (const p of c.actions)
          if (p.duration > 0 || p.animationUrl === "x_turn") {
            if (p.animationUrl === "x_turn") {
              p.duration = 1;
              const v = k(p.rotation);
              v && (r = D(r, v));
            }
            const C = p.animationUrl !== "none" && p.animationUrl !== "x_turn";
            m({
              visible: !0,
              timeStamp: I,
              position: [c.point.x, c.point.y, c.point.z],
              quaternion: r,
              scale: o.scale,
              animation: {
                url: C ? p.animationUrl : t.animationUrl,
                repeat: !C || (p == null ? void 0 : p.repeat),
                needRender: C,
                item: (V = p.subAction) != null && V.url ? p.subAction : void 0,
                duration: p == null ? void 0 : p.duration
              }
            }), I += p.duration * 1e3, K += p.duration * 1e3, m({
              visible: !0,
              timeStamp: I,
              position: [c.point.x, c.point.y, c.point.z],
              quaternion: r,
              scale: o.scale,
              animation: {
                url: t.animationUrl,
                repeat: t.repeat === "loop",
                item: (J = p.subAction) != null && J.url ? p.subAction : void 0
              }
            });
          }
        _ += K, K > 0 && h.push({ start: F + u, end: I + u }), G.add(T), console.log(
          `点位处理完成，已标记为已处理: [${c.point.x.toFixed(2)}, ${c.point.y.toFixed(2)}, ${c.point.z.toFixed(
            2
          )}]`
        );
      }
    }
    if (i === t.track.path.length - 2) {
      const c = M + _;
      m({
        visible: !0,
        timeStamp: c,
        position: [s.x, s.y, s.z],
        quaternion: r,
        scale: o.scale,
        animation: {
          url: t.animationUrl,
          repeat: t.repeat === "loop"
        }
      });
    }
  }
  function tt(i, n, s) {
    const y = i.x - n.x, d = i.y - n.y, M = i.z - n.z, w = s.x - n.x, Q = s.y - n.y, c = s.z - n.z, T = y * w + d * Q + M * c, z = w * w + Q * Q + c * c;
    if (z === 0)
      return Math.sqrt(y * y + d * d + M * M);
    let g = T / z;
    g < 0 ? g = 0 : g > 1 && (g = 1);
    const f = n.x + g * w, F = n.y + g * Q, U = n.z + g * c, q = i.x - f, P = i.y - F, I = i.z - U;
    return Math.sqrt(q * q + P * P + I * I);
  }
  function nt(i, n, s) {
    const y = s.x - n.x, d = s.y - n.y, M = s.z - n.z, w = y * y + d * d + M * M;
    if (w === 0)
      return 0;
    const Q = i.x - n.x, c = i.y - n.y, T = i.z - n.z, z = Q * y + c * d + T * M;
    return Math.max(0, Math.min(1, z / w));
  }
  e.sort((i, n) => i.timeStamp - n.timeStamp);
  const X = [];
  for (let i = 0; i < e.length - 1; i++) {
    const n = e[i], s = e[i + 1];
    if (Math.abs(n.position[0] - s.position[0]) + Math.abs(n.position[1] - s.position[1]) + Math.abs(n.position[2] - s.position[2]) > 1e-3) {
      const d = n.timeStamp + a;
      if (h.some(
        (f) => d > f.start - ot && d < f.end
      )) {
        console.log(`旋转帧时刻 ${d}ms 落入动作窗口，跳过插入以保护停顿动作`);
        continue;
      }
      console.log(`找到连续的不同位置关键帧: ${i} -> ${i + 1}`);
      const w = j * (a / 1e3), Q = new N.Vector3(n.position[0], n.position[1], n.position[2]), c = new N.Vector3(
        s.position[0] - n.position[0],
        s.position[1] - n.position[1],
        s.position[2] - n.position[2]
      ).normalize(), T = Q.clone().add(c.multiplyScalar(w));
      let z = at(
        { x: n.position[0], y: n.position[1], z: n.position[2] },
        { x: s.position[0], y: s.position[1], z: s.position[2] }
      );
      const g = {
        visible: !0,
        timeStamp: n.timeStamp + a,
        // 加上旋转走路的时间
        position: [T.x, T.y, T.z],
        // 使用计算后的位置
        quaternion: z,
        // 使用路径方向的quaternion
        scale: o.scale
      };
      t.animationUrl !== "none" && (g.animation = {
        url: t.animationUrl,
        repeat: t.repeat === "loop"
      }), X.push(g);
      for (let f = 0; f < e.length; f++)
        if (e[f].timeStamp > n.timeStamp + a)
          if (Math.abs(e[f].position[0] - s.position[0]) < 1e-3 && Math.abs(e[f].position[1] - s.position[1]) < 1e-3 && Math.abs(e[f].position[2] - s.position[2]) < 1e-3)
            if (f < e.length - 1) {
              const F = e[f].quaternion, U = e[f + 1].quaternion;
              if (Math.abs(F[0] - U[0]) + Math.abs(F[1] - U[1]) + Math.abs(F[2] - U[2]) + Math.abs(F[3] - U[3]) < 1e-3)
                e[f].quaternion = z.slice(), console.log(`关键帧${f}没有旋转，设置为路径方向`);
              else {
                const P = new N.Quaternion(), I = new N.Quaternion(
                  F[0],
                  F[1],
                  F[2],
                  F[3]
                ), K = new N.Quaternion(U[0], U[1], U[2], U[3]), p = I.clone();
                p.conjugate(), P.copy(K).multiply(p), e[f].quaternion = z.slice();
                const v = new N.Quaternion(
                  z[0],
                  z[1],
                  z[2],
                  z[3]
                ).clone().multiply(P);
                e[f + 1].quaternion = [v.x, v.y, v.z, v.w], z = [v.x, v.y, v.z, v.w], console.log(`关键帧${f}发生旋转，当前帧设置为路径方向，下一帧设置为路径方向+旋转角度，更新路径方向`), f++;
              }
            } else
              e[f].quaternion = z.slice(), console.log(`最后一个关键帧${f}设置为路径方向`);
          else
            break;
      console.log(`添加旋转动作帧，时间戳: ${n.timeStamp + a}ms`);
    }
  }
  e.push(...X), e.sort((i, n) => i.timeStamp - n.timeStamp);
  const Y = t.track.duration * 1e3, Z = Y + _, R = e[e.length - 1], it = e.filter(
    (i) => i.timeStamp === 0 && Math.abs(i.position[0] - o.position[0]) < 1e-3 && Math.abs(i.position[1] - o.position[1]) < 1e-3 && Math.abs(i.position[2] - o.position[2]) < 1e-3
  );
  return console.log(`动画转换完成:
     - 路径总距离: ${b.toFixed(2)} 单位
     - 基础移动时间: ${Y}ms (${t.track.duration}s)
     - 移动速度: ${j.toFixed(2)} 单位/秒
     - 动作延迟时间: ${_}ms (${(_ / 1e3).toFixed(2)}s)
     - 计算总时间: ${Z}ms (${(Z / 1e3).toFixed(2)}s)
     - 实际最后时间戳: ${R == null ? void 0 : R.timeStamp}ms (${((R == null ? void 0 : R.timeStamp) / 1e3).toFixed(2)}s)
     - 关键帧数量: ${e.length}
     - 初始位置关键帧数量: ${it.length}
     - 速度一致性: ${(((R == null ? void 0 : R.timeStamp) - _) / 1e3 / t.track.duration * 100).toFixed(1)}% (100%为完全一致)`), {
    id: t.id,
    name: t.name || "默认角色",
    type: "model",
    model: t.modelUrl,
    keyframes: e
  };
}
export {
  rt as convertMockToPlayer
};
