const BASE_URL = "https://api.shelingxingqiu.com/api/shoot";

function request(method, url, data = {}) {
  const token = uni.getStorageSync("token");
  return new Promise((resolve, reject) => {
    uni.request({
      url: `${BASE_URL}${url}`,
      method,
      header: {
        Authorization: `Bearer ${token || ""}`,
      },
      data,
      success: (res) => {
        if (res.data) {
          const { code, data, message } = res.data;
          if (code === 0) resolve(data);
          else {
            if (message.indexOf("登录身份已失效") !== -1) {
              uni.removeStorageSync("token");
            }
            if (url.indexOf("/user/room") !== -1 && method === "GET") {
              resolve({});
              return;
            }
            if (message === "ERROR_BATTLE_GAMING") {
              resolve({});
              return;
            }
            if (message === "ERROR_ORDER_UNPAY") {
              uni.showToast({
                title: "当前有未支付订单",
                icon: "none",
              });
              resolve({});
              return;
            }
            uni.showToast({
              title: message,
              icon: "none",
            });
          }
        }
      },
      fail: (err) => {
        reject(err);
        uni.showToast({
          title: "接口调用失败",
          icon: "none",
        });
      },
    });
  });
}

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

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

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

export const loginAPI = async (nickName, avatarData, code) => {
  const result = await request("POST", "/index/code", {
    appName: "shoot",
    appId: "wxa8f5989dcd45cc23",
    nickName,
    avatarData,
    code,
  });
  uni.setStorageSync("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) => {
  return request("POST", "/user/practice/create", {
    arrows,
  });
};

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,
  });
  const {
    battleStats = {},
    playerStats = {},
    goldenRoundRecords = [],
  } = result;
  const data = {
    mode: battleStats.mode,
    gameMode: battleStats.gameMode,
  };
  if (battleStats && battleStats.mode === 1) {
    data.winner = battleStats.winner;
    data.roundsData = {};
    data.redPlayers = {};
    data.bluePlayers = {};
    data.goldenRound =
      goldenRoundRecords && goldenRoundRecords.length
        ? goldenRoundRecords[0]
        : null;
    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;
      }
      roundRecords.forEach((round) => {
        data.roundsData[round.roundNumber] = {
          ...data.roundsData[round.roundNumber],
          [round.playerId]: round.arrowHistory,
        };
      });
    });
  }
  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 () => {
  const result = await request("GET", "/user/join/battle");
  return result.currentGame || {};
};
