let BASE_URL = "https://api.shelingxingqiu.com/api/shoot"; // 默认正式版

try {
  const accountInfo = uni.getAccountInfoSync();
  const envVersion = accountInfo.miniProgram.envVersion;

  switch (envVersion) {
    case "develop": // 开发版
      // BASE_URL = "http://192.168.1.242:8000/api/shoot";
      BASE_URL = "https://apitest.shelingxingqiu.com/api/shoot";
      break;
    case "trial": // 体验版
      BASE_URL = "https://apitest.shelingxingqiu.com/api/shoot";
      break;
    case "release": // 正式版
      BASE_URL = "https://api.shelingxingqiu.com/api/shoot";
      break;
    default:
      // 保持默认值
      break;
  }
} catch (e) {
  console.error("获取环境信息失败，使用默认正式环境", e);
}

function request(method, url, data = {}) {
  const token = uni.getStorageSync(
    `${uni.getAccountInfoSync().miniProgram.envVersion}_token`
  );
  const header = {};
  if (token) header.Authorization = `Bearer ${token || ""}`;
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}${url}`,
      method,
      header,
      data,
      timeout: 10000,
      success: (res) => {
        if (res.data) {
          const { code, data, message } = res.data;
          if (code === 0) resolve(data);
          else if (message) {
            if (message.indexOf("登录身份已失效") !== -1) {
              uni.removeStorageSync(
                `${uni.getAccountInfoSync().miniProgram.envVersion}_token`
              );
              uni.$emit("update-user");
            }
            if (message === "ROOM_FULL") {
              resolve({ full: true });
              return;
            }
            if (message === "ERROR_ROOM_GAME_START") {
              resolve({ started: true });
              return;
            }
            if (url.indexOf("/user/room") !== -1 && method === "GET") {
              resolve({});
              return;
            }
            if (message === "ERROR_BATTLE_GAMING") {
              resolve({});
              return;
            }
            if (message === "BIND_DEVICE") {
              resolve({ binded: true });
              return;
            }
            if (message === "ERROR_ORDER_UNPAY") {
              uni.showToast({
                title: "当前有未支付订单",
                icon: "none",
              });
              resolve({});
              return;
            }
            if (message === "ROOM_EMPTY") {
              return uni.showToast({
                title: "房间已过期",
                icon: "none",
              });
            }
            uni.showToast({
              title: message,
              icon: "none",
            });
          }
          reject("");
        }
      },
      fail: (err) => {
        handleRequestError(err, url);
        reject(err);
      },
    });
  });
}

// 统一的错误处理函数
function handleRequestError(err, url) {
  console.log("请求失败:", { err, url });

  // 根据错误类型显示不同提示
  if (err.errMsg) {
    if (err.errMsg.includes("timeout")) {
      showCustomToast("请求超时，请稍后重试", "timeout");
    } else if (err.errMsg.includes("fail")) {
      // 检查网络状态
      uni.getNetworkType({
        success: (res) => {
          if (res.networkType === "none") {
            showCustomToast("网络连接已断开，请检查网络设置", "network");
          } else {
            showCustomToast("服务器连接失败，请稍后重试", "server");
          }
        },
        fail: () => {
          showCustomToast("网络异常，请检查网络连接", "unknown");
        },
      });
    } else {
      showCustomToast("请求失败，请稍后重试", "general");
    }
  } else {
    showCustomToast("网络异常，请稍后重试", "unknown");
  }
}

// 自定义提示函数
function showCustomToast(message, type) {
  const config = {
    title: message,
    icon: "none",
    duration: 3000,
  };

  // 根据错误类型可以添加不同的处理逻辑
  switch (type) {
    case "timeout":
      config.duration = 4000; // 超时提示显示更久
      break;
    case "network":
      config.duration = 5000; // 网络问题提示显示更久
      break;
    default:
      break;
  }

  uni.showToast(config);
}

// 获取全局配置
export const getAppConfig = () => {
  return request("GET", "/index/appConfig");
};

export const getHomeData = (seasonId) => {
  return request("GET", `/user/myHome?seasonId=${seasonId}`);
};

export const getProvinceData = () => {
  return request("GET", "/index/provinces/list");
};

export const loginAPI = async (phone, nickName, avatarData, code) => {
  const result = await request("POST", "/index/code", {
    appName: "shoot",
    appId: "wxa8f5989dcd45cc23",
    nickName,
    avatarData,
    code,
    phone,
  });
  uni.setStorageSync(
    `${uni.getAccountInfoSync().miniProgram.envVersion}_token`,
    result.token
  );
  return result;
};

export const bindDeviceAPI = (device) => {
  return request("POST", "/user/device/bindDevice", {
    device,
  });
};

export const unbindDeviceAPI = (deviceId) => {
  return request("POST", "/user/device/unbindDevice", {
    deviceId,
  });
};

export const getMyDevicesAPI = () => {
  // "/user/device/getBinding?deviceId=9ZF9oVXs"
  return request("GET", "/user/device/getBindings");
};

export const createPractiseAPI = (arrows, mode) => {
  return request("POST", "/user/practice/create", {
    arrows,
    mode,
  });
};

export const getPractiseAPI = async (id) => {
  const result = await request("GET", `/user/practice/get?id=${id}`);
  const data = { ...(result.UserPracticeRound || {}) };
  if (data.arrows) data.arrows = JSON.parse(data.arrows);
  return data;
};

export const createRoomAPI = (gameType, teamSize) => {
  return request("POST", "/user/createroom", {
    gameType,
    teamSize,
  });
};

export const getRoomAPI = (number) => {
  return request("GET", `/user/room?number=${number}`);
};

export const joinRoomAPI = (number) => {
  return request("POST", `/user/room/join`, { number });
};

export const destroyRoomAPI = (roomNumber) => {
  return request("POST", "/user/room/destroyRoom", {
    roomNumber,
  });
};

export const exitRoomAPI = (number) => {
  return request("POST", "/user/room/exitRoom", {
    number,
  });
};

export const startRoomAPI = (number) => {
  return request("POST", "/user/room/start", { number });
};

export const getPractiseResultListAPI = async (page = 1, page_size = 15) => {
  const reuslt = await request(
    "GET",
    `/user/practice/list?page=${page}&page_size=${page_size}`
  );
  return reuslt.list;
};

export const matchGameAPI = (match, gameType, teamSize) => {
  return request("POST", "/user/game/match", {
    match,
    gameType,
    teamSize,
  });
};

export const readyGameAPI = (battleId) => {
  return request("POST", "/user/game/prepare", {
    battleId,
  });
};

export const getGameAPI = async (battleId) => {
  const result = await request("POST", "/user/battle/detail", {
    id: battleId,
  });
  if (!result.battleStats) return {};
  const {
    battleStats = {},
    playerStats = {},
    goldenRoundRecords = [],
  } = result;
  const data = {
    id: battleId,
    mode: battleStats.mode, // 1.几V几 2.大乱斗
    gameMode: battleStats.gameMode, // 1.约战 2.排位
    teamSize: battleStats.teamSize,
  };
  if (battleStats && battleStats.mode === 1) {
    data.winner = battleStats.winner;
    data.roundsData = {};
    data.redPlayers = {};
    data.bluePlayers = {};
    data.mvps = [];
    data.goldenRounds =
      goldenRoundRecords && goldenRoundRecords.length ? goldenRoundRecords : [];
    playerStats.forEach((item) => {
      const { playerBattleStats = {}, roundRecords = [] } = item;
      if (playerBattleStats.team === 0) {
        data.redPlayers[playerBattleStats.playerId] = playerBattleStats;
      }
      if (playerBattleStats.team === 1) {
        data.bluePlayers[playerBattleStats.playerId] = playerBattleStats;
      }
      if (playerBattleStats.mvp) {
        data.mvps.push(playerBattleStats);
      }
      roundRecords.forEach((round) => {
        data.roundsData[round.roundNumber] = {
          ...data.roundsData[round.roundNumber],
          [round.playerId]: round.arrowHistory,
        };
      });
    });
    const totalRounds = Object.keys(data.roundsData).length;
    (goldenRoundRecords || []).forEach((item, index) => {
      item.arrowHistory.forEach((arrow) => {
        if (!data.roundsData[totalRounds + index + 1]) {
          data.roundsData[totalRounds + index + 1] = {};
        }
        if (!data.roundsData[totalRounds + index + 1][arrow.playerId]) {
          data.roundsData[totalRounds + index + 1][arrow.playerId] = [];
        }
        data.roundsData[totalRounds + index + 1][arrow.playerId].push(arrow);
      });
    });

    data.mvps.sort((a, b) => b.totalRings - a.totalRings);
  }
  if (battleStats && battleStats.mode === 2) {
    data.players = [];
    playerStats.forEach((item) => {
      data.players.push({
        ...item.playerBattleStats,
        arrowHistory: item.roundRecords[0].arrowHistory,
      });
    });
    data.players = data.players.sort((a, b) => b.totalScore - a.totalScore);
  }
  // console.log("game result:", result);
  // console.log("format data:", data);
  return data;
};

export const simulShootAPI = (device_id, x, y) => {
  const data = {
    device_id,
  };
  if (x !== undefined && y !== undefined) {
    data.x = x;
    data.y = y;
  }
  return request("POST", "/index/arrow", data);
};

export const getBattleListAPI = async (page, battleType) => {
  const data = [];
  const result = await request("POST", "/user/battle/details/list", {
    page,
    battleType,
    modeType: 0,
  });
  (result.Battles || []).forEach((item) => {
    let name = "";
    if (item.battleStats.mode === 1) {
      name = `${item.playerStats.length / 2}V${item.playerStats.length / 2}`;
    }
    if (item.battleStats.mode === 2) {
      name = `${item.playerStats.length}人大乱斗`;
    }
    data.push({
      name,
      battleId: item.battleStats.battleId,
      mode: item.battleStats.mode,
      createdAt: item.battleStats.createdAt,
      gameEndAt: item.battleStats.gameEndAt,
      winner: item.battleStats.winner,
      players: item.playerStats
        .map((p) => p.playerBattleStats)
        .sort((a, b) => b.totalScore - a.totalScore),
      redPlayers: item.playerStats
        .filter((p) => p.playerBattleStats.team === 0)
        .map((p) => p.playerBattleStats),
      bluePlayers: item.playerStats
        .filter((p) => p.playerBattleStats.team === 1)
        .map((p) => p.playerBattleStats),
    });
  });
  return data;
};

export const getRankListAPI = () => {
  return request("GET", "/index/ranklist");
};

export const createOrderAPI = (vipId) => {
  return request("POST", "/user/order/create", {
    vipId,
    quanity: 1,
    tradeType: "mini",
    payType: "wxpay",
  });
};

export const payOrderAPI = (id) => {
  return request("POST", "/user/order/pay", {
    id,
    tradeType: "mini",
    payType: "wxpay",
  });
};

export const getOrderListAPI = async (page) => {
  const reuslt = await request("GET", `/user/order/list?page=${page}`);
  return reuslt.items || [];
};

export const cancelOrderListAPI = async (id) => {
  return request("POST", "/user/order/cancelOrder", { id });
};

export const isGamingAPI = async () => {
  const result = await request("GET", "/user/isGaming");
  return result.gaming || false;
};

export const getCurrentGameAPI = async () => {
  uni.$emit("update-header-loading", true);
  const result = await request("GET", "/user/join/battle");
  return result.currentGame || {};
};

export const getPointBookConfigAPI = async () => {
  return request("GET", "/user/score/sheet/option");
};

export const savePointBookAPI = async (
  bowType,
  distance,
  targetType,
  groups,
  arrows,
  data = []
) => {
  return request("POST", "/user/score/sheet/report", {
    bowType,
    distance,
    targetType,
    groups,
    arrows,
    group_data: data.map((item) =>
      item.map((i) => ({
        ...i,
        ring: i.ring === "M" ? -1 : i.ring === "X" ? 0 : Number(i.ring),
      }))
    ),
  });
};

export const getPointBookListAPI = async (
  page = 1,
  bowType,
  distance,
  targetType
) => {
  let url = `/user/score/sheet/list?pageNum=${page}&pageSize=10`;
  if (bowType) url += `&bowType=${bowType}`;
  if (distance) url += `&distance=${distance}`;
  if (targetType) url += `&targetType=${targetType}`;
  const result = await request("GET", url);
  return result.list || [];
};

export const getPointBookDetailAPI = async (id) => {
  return request("GET", `/user/score/sheet/detail?id=${id}`);
};

export const getPointBookDataAPI = async () => {
  return request("GET", "/user/score/sheet/statistics");
};

export const getPractiseDataAPI = async () => {
  return request("GET", "/user/practice/statistics");
};

export const getBattleDataAPI = async () => {
  return request("GET", "/user/fight/statistics");
};

export const chooseTeamAPI = async (number, group) => {
  return request("POST", "/user/room/group", { number, group });
};

export const getVIPDescAPI = async () => {
  return request("GET", "/index/memberVipDescribe");
};

export const getPointBookStatisticsAPI = async () => {
  return request("GET", `/v2/user/score/sheet/statistics`);
};

export const donateAPI = async (amount, name, phone, organizer, advice) => {
  return request("POST", `/user/donate`, {
    amount,
    name,
    phone,
    organizer,
    advice,
  });
};

export const laserAimAPI = async () => {
  return request("POST", "/user/device/laserAim");
};

export const laserCloseAPI = async () => {
  return request("POST", "/user/device/closeAim");
};

export const getDeviceBatteryAPI = async () => {
  return request("GET", "/user/device/battery");
};

export const addNoteAPI = async (id, remark) => {
  return request("POST", "/user/score/sheet/remark", { id, remark });
};

export const removePointRecord = async (id) => {
  return request("DELETE", `/user/score/sheet/delete?id=${id}`);
};

export const getPhoneNumberAPI = (data) => {
  return request("POST", "/index/getPhone", data);
};
