import { createInitialStore, MOCK_LOGIN, MOCK_SHIP_ID } from "./data";

let store = createInitialStore();

function ok(data, msg = "success") {
  return { code: 200, msg, data };
}

function pageResult(list, pageNo = 1, pageSize = 10) {
  const start = (pageNo - 1) * pageSize;
  const slice = list.slice(start, start + pageSize);
  return ok({
    list: slice,
    total: String(list.length),
    pageNo,
    pageSize,
  });
}

function parseUrl(url) {
  const [path, query = ""] = url.split("?");
  const params = {};
  query.split("&").filter(Boolean).forEach((pair) => {
    const [k, v] = pair.split("=");
    params[decodeURIComponent(k)] = decodeURIComponent(v || "");
  });
  return { path, params };
}

function matchPath(pattern, path) {
  const patternParts = pattern.split("/");
  const pathParts = path.split("/");
  if (patternParts.length !== pathParts.length) return null;
  const params = {};
  for (let i = 0; i < patternParts.length; i++) {
    if (patternParts[i].startsWith(":")) {
      params[patternParts[i].slice(1)] = pathParts[i];
    } else if (patternParts[i] !== pathParts[i]) {
      return null;
    }
  }
  return params;
}

function tenantListPayload() {
  const arr = store.tenants;
  arr.list = arr;
  return ok(arr);
}

function filterUsers(params) {
  let list = [...store.users];
  if (params.username) {
    list = list.filter((u) => u.username.includes(params.username));
  }
  return list;
}

function filterRoles(params) {
  let list = [...store.roles];
  if (params.roleName) {
    list = list.filter((r) => r.roleName.includes(params.roleName));
  }
  if (params.tenantId) {
    list = list.filter((r) => String(r.tenantId) === String(params.tenantId));
  }
  return list;
}

function getShipStatus() {
  const path = store.shipNavPath;
  const idx = store.shipNavIndex % path.length;
  const pos = path[idx];
  store.shipNavIndex += 1;

  const status = { ...store.shipStatus };
  if (pos.longitude != null) {
    status.longitude = pos.longitude;
    status.latitude = pos.latitude;
    store.shipStatus.longitude = pos.longitude;
    store.shipStatus.latitude = pos.latitude;
  } else {
    status.longitude = null;
    status.latitude = null;
  }
  status.feedWeight = 40 + Math.floor(Math.random() * 20);
  status.speed = (1.5 + Math.random() * 2).toFixed(1);
  status.power = 60 + Math.floor(Math.random() * 35);
  return ok(status);
}

export function resetMockStore() {
  store = createInitialStore();
}

export function handleMockRequest(config) {
  const method = (config.method || "get").toLowerCase();
  let url = config.url || "";
  if (url.startsWith("http")) {
    try {
      url = new URL(url).pathname;
    } catch {
      /* keep url */
    }
  }
  const { path, params: queryParams } = parseUrl(url);
  const body = config.data
    ? typeof config.data === "string"
      ? JSON.parse(config.data)
      : config.data
    : {};

  // ---------- 登录 ----------
  if (method === "post" && path === "/users/login/web") {
    return ok({
      username: body.username || MOCK_LOGIN.username,
      userId: MOCK_LOGIN.userId,
      tenantId: MOCK_LOGIN.tenantId,
      token: MOCK_LOGIN.token,
    });
  }

  // ---------- 用户管理 ----------
  if (method === "get" && path === "/users/user-manage/page") {
    const pageNo = Number(queryParams.pageNo) || 1;
    const pageSize = Number(queryParams.pageSize) || 10;
    return pageResult(filterUsers(queryParams), pageNo, pageSize);
  }

  const userById = matchPath("/users/user-manage/:id", path);
  if (method === "get" && userById) {
    const user = store.users.find((u) => String(u.id) === userById.id);
    return user ? ok(user) : ok(null, "用户不存在");
  }
  if (method === "post" && path === "/users/user-manage") {
    const id = store.nextId.user++;
    const tenant = store.tenants.find((t) => t.id === body.tenantId);
    store.users.push({
      id,
      username: body.username,
      phone: body.phone,
      tenantId: body.tenantId,
      tenantName: tenant ? tenant.name : "",
      status: 1,
      usertype: body.usertype,
      createTime: new Date().toISOString().slice(0, 19).replace("T", " "),
      roleVos: [],
    });
    return ok(null, "新增成功");
  }
  if (method === "put" && path === "/users/user-manage") {
    const user = store.users.find((u) => String(u.id) === String(body.id));
    if (user) {
      if (body.username) user.username = body.username;
      if (body.phone) user.phone = body.phone;
    }
    return ok({ code: 200 }, "修改成功");
  }
  if (method === "patch" && path === "/users/user-manage/patch") {
    const user = store.users.find((u) => String(u.id) === String(body.userId));
    if (user && body.roleIds && body.roleIds.length) {
      const role = store.roles.find((r) => String(r.id) === String(body.roleIds[0]));
      if (role) user.roleVos = [{ id: role.id, roleName: role.roleName }];
    }
    return ok(null, "分配成功");
  }
  if (method === "delete" && userById) {
    store.users = store.users.filter((u) => String(u.id) !== userById.id);
    return ok(null, "删除成功");
  }

  // ---------- 角色管理 ----------
  if (method === "get" && path === "/users/role-manage/page") {
    const pageNo = Number(queryParams.pageNo) || 1;
    const pageSize = Number(queryParams.pageSize) || 10;
    return pageResult(filterRoles(queryParams), pageNo, pageSize);
  }
  if (method === "get" && path === "/users/role-manage/list") {
    const tenantId = queryParams.tenantId;
    const list = tenantId
      ? store.roles.filter((r) => String(r.tenantId) === String(tenantId))
      : store.roles;
    return ok(list);
  }

  const roleById = matchPath("/users/role-manage/:id", path);
  if (method === "get" && roleById) {
    const role = store.roles.find((r) => String(r.id) === roleById.id);
    return role ? ok(role) : ok(null);
  }
  if (method === "post" && path === "/users/role-manage") {
    const id = store.nextId.role++;
    const tenant = store.tenants.find((t) => t.id === body.tenantId);
    store.roles.push({
      id,
      roleName: body.roleName,
      comment: body.comment,
      tenantId: body.tenantId,
      tenantName: tenant ? tenant.name : "",
      createTime: new Date().toISOString().slice(0, 19).replace("T", " "),
      createBy: "admin",
      updateBy: "admin",
      updateTime: new Date().toISOString().slice(0, 19).replace("T", " "),
    });
    return ok(null, "新增成功");
  }
  if (method === "put" && path === "/users/role-manage") {
    const role = store.roles.find((r) => String(r.id) === String(body.id));
    if (role) {
      role.roleName = body.roleName || role.roleName;
      role.comment = body.comment || role.comment;
      role.updateTime = new Date().toISOString().slice(0, 19).replace("T", " ");
    }
    return ok(null, "修改成功");
  }
  if (method === "delete" && roleById) {
    store.roles = store.roles.filter((r) => String(r.id) !== roleById.id);
    return ok(null, "删除成功");
  }

  // ---------- 权限管理 ----------
  if (method === "get" && path === "/users/permission-manage/list") {
    return ok(store.permissions);
  }
  const permById = matchPath("/users/permission-manage/:id", path);
  if (method === "get" && permById) {
    const p = store.permissions.find((x) => String(x.id) === permById.id);
    return p ? ok(p) : ok(null);
  }
  if (method === "post" && path === "/users/permission-manage") {
    store.permissions.push({
      id: store.nextId.permission++,
      name: body.name,
      path: body.path,
      comment: body.comment,
    });
    return ok(null, "新增成功");
  }
  if (method === "put" && path === "/users/permission-manage") {
    const p = store.permissions.find((x) => String(x.id) === String(body.id));
    if (p) Object.assign(p, body);
    return ok(null, "修改成功");
  }
  if (method === "delete" && permById) {
    store.permissions = store.permissions.filter(
      (x) => String(x.id) !== permById.id
    );
    return ok(null, "删除成功");
  }

  // ---------- 租户管理 ----------
  if (method === "get" && path === "/users/tenant-manage/list") {
    return tenantListPayload();
  }
  if (method === "get" && path === "/users/tenant-manage") {
    const pageNo = Number(queryParams.pageNo) || 1;
    const pageSize = Number(queryParams.pageSize) || 10;
    return pageResult(store.tenants, pageNo, pageSize);
  }
  const tenantById = matchPath("/users/tenant-manage/:id", path);
  if (method === "get" && tenantById) {
    const t = store.tenants.find((x) => String(x.id) === tenantById.id);
    return t ? ok(t) : ok(null);
  }
  if (method === "post" && path === "/users/tenant-manage") {
    store.tenants.push({
      id: store.nextId.tenant++,
      name: body.name,
      tenantType: body.tenantType,
    });
    return ok(null, "新增成功");
  }
  if (method === "put" && path === "/users/tenant-manage") {
    const t = store.tenants.find((x) => String(x.id) === String(body.id));
    if (t) {
      t.name = body.name || t.name;
      t.tenantType = body.tenantType ?? t.tenantType;
    }
    return ok(null, "修改成功");
  }
  if (method === "delete" && path === "/users/tenant-manage") {
    const ids = Array.isArray(body) ? body : body.ids || [body.id];
    store.tenants = store.tenants.filter(
      (t) => !ids.map(String).includes(String(t.id))
    );
    return ok(null, "删除成功");
  }

  // ---------- 设备 ----------
  if (method === "post" && path === "/users/android/manage") {
    return ok({ deviceId: body.id || MOCK_SHIP_ID }, "设备注册成功");
  }

  // ---------- 投食船 v2 ----------
  if (method === "get" && path.startsWith("/feeding-ship-v2/device/status/")) {
    return getShipStatus();
  }
  if (method === "post" && path === "/feeding-ship-v2/feeding/mode") {
    return ok(null, "投食模式已设置");
  }
  if (method === "post" && path === "/feeding-ship-v2/feeding/medicine/") {
    return ok(null, "撒药模式已切换");
  }
  if (method === "post" && path === "/feeding-ship-v2/navigation/points-mode/") {
    return ok(null, "多点导航模式已开启");
  }
  if (method === "post" && path === "/feeding-ship-v2/navigation/execute/") {
    store.shipNavIndex = 0;
    return ok(null, "路线已下发");
  }
  if (method === "get" && path === "/feeding-ship-v2/error-message/page") {
    const pageNo = Number(queryParams.pageNo) || 1;
    const pageSize = Number(queryParams.pageSize) || 10;
    return pageResult(store.errorMessages, pageNo, pageSize);
  }
  if (method === "get" && path === "/feeding-ship-v2/route-history/page") {
    const pageNo = Number(queryParams.pageNo) || 1;
    const pageSize = Number(queryParams.pageSize) || 10;
    const list = store.routeHistories.map(({ route, ...rest }) => rest);
    return pageResult(list, pageNo, pageSize);
  }
  const routeById = matchPath("/feeding-ship-v2/route-history/:id", path);
  if (method === "get" && routeById) {
    const r = store.routeHistories.find((x) => String(x.id) === routeById.id);
    return r ? ok({ route: r.route, routeName: r.routeName }) : ok(null);
  }
  if (method === "post" && path === "/feeding-ship-v2/route-history") {
    store.routeHistories.push({
      id: store.nextId.route++,
      routeName: body.routeName,
      routeType: body.routeType ?? 1,
      shipId: body.shipId || MOCK_SHIP_ID,
      createTime: new Date().toISOString().slice(0, 19).replace("T", " "),
      route: body.routePoints || [],
    });
    return ok(null, "路线保存成功");
  }
  if (method === "put" && path === "/feeding-ship-v2/route-history/") {
    const r = store.routeHistories.find((x) => String(x.id) === String(body.id));
    if (r) Object.assign(r, body);
    return ok(null, "更新成功");
  }
  if (method === "delete" && routeById) {
    store.routeHistories = store.routeHistories.filter(
      (x) => String(x.id) !== routeById.id
    );
    return ok(null, "删除成功");
  }
  if (method === "get" && path.startsWith("/feeding-ship-v2/personal-center/feeding")) {
    return ok({
      totalWeight: 12580,
      todayWeight: 540,
      records: [
        { time: "2025-05-26 08:30:00", weight: "1200" },
        { time: "2025-05-26 10:15:00", weight: "800" },
        { time: "2025-05-25 16:20:00", weight: "1500" },
      ],
    });
  }
  if (method === "post" && path === "/feeding-ship-v2/feedback") {
    store.feedbackList.push({
      id: store.feedbackList.length + 1,
      ...body,
      createTime: new Date().toISOString().slice(0, 19).replace("T", " "),
    });
    return ok(null, "反馈提交成功");
  }
  if (method === "get" && path === "/feeding-ship-v2/fault-warranty/page") {
    const pageNo = Number(queryParams.pageNo) || 1;
    const pageSize = Number(queryParams.pageSize) || 10;
    return pageResult(store.faultWarranties, pageNo, pageSize);
  }
  const faultById = matchPath("/feeding-ship-v2/fault-warranty/:id", path);
  if (method === "delete" && faultById) {
    store.faultWarranties = store.faultWarranties.filter(
      (x) => String(x.id) !== faultById.id
    );
    return ok(null, "删除成功");
  }
  if (method === "put" && path === "/feeding-ship-v2/fault-warranty/") {
    const f = store.faultWarranties.find((x) => String(x.id) === String(body.id));
    if (f) f.status = body.status;
    return ok(null, "状态已更新");
  }

  console.warn("[Mock] 未匹配的接口:", method.toUpperCase(), path);
  return ok({});
}
