import { normalizeBattleApiResult } from "@/utils/matchAdapter";

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.30: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);
}

const ADDONS_BASE_URL = BASE_URL.replace(/\/api\/shoot$/, "/api/shoot");
// 统一处理业务接口请求，包含登录态、业务错误和特定接口空响应兼容。
function request(method, url, data = {}, baseUrl = BASE_URL) {
    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: `${baseUrl}${url}`,
            method,
            header,
            data,
            timeout: 10000,
            success: (res) => {
                const acceptsEmptyResponse = [
                    "/user/hardwareBox/connectWifi",
                    "/user/device/unbindByQrcodeId",
                ].includes(url);
                if (acceptsEmptyResponse && res.statusCode === 200 && res.data && Object.keys(res.data).length === 0) {
                    resolve({});
                    return;
                }
                if (res.data) {
                    const {code, data, message} = res.data;
                    if (code === 0) resolve(data);
                    else if (message) {
                        const error = {code, data, message};
                        if (message.indexOf("登录身份已失效") !== -1) {
                            console.log('1111111111111111111,token失效')
                            uni.removeStorageSync(
                                `${uni.getAccountInfoSync().miniProgram.envVersion}_token`
                            );
                            uni.$emit("update-user");
                            reject({ type: "AUTH_INVALID", message });
                            return;
                        }
                        if (message.indexOf("已达上限") !== -1) {
                            reject(error);
                            return;
                        }
                        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 === "BIND_FAILD") {
                            uni.$emit("device-bind-invalid");
                            uni.showToast({
                                title: "设备绑定状态已失效，请重新绑定",
                                icon: "none",
                            });
                            reject({type: "DEVICE_BIND_INVALID", message});
                            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(error);
                        return;
                    }
                    reject({code, data, message});
                }
            },
            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 getDailyCountAPI = () => {
    return request("GET", "/index/dailyCount", {}, ADDONS_BASE_URL);
};

export const getHomeData = async (seasonId) => {
    const data = await request("GET", `/user/myHome?seasonId=${seasonId}`);
    if (!data?.user) return data;

    // 段位信息由 myHome 接口直接返回，统一并入用户数据供各页面展示。
    return {
        ...data,
        user: {
            ...data.user,
            rankIcon: data.rankIcon,
            rankName: data.rankName,
        },
    };
};

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 silentLoginAPI = async (code) => {
    const result = await request("POST", "/index/code", {
        appName: "shoot",
        appId: "wxa8f5989dcd45cc23",
        code,
    });
    uni.setStorageSync(
        `${uni.getAccountInfoSync().miniProgram.envVersion}_token`,
        result.token
    );
    return result;
};

export const checkUserBindAPI = async (code) => {
    return request("POST", "/index/checkBind", {
        appName: "shoot",
        appId: "wxa8f5989dcd45cc23",
        code,
    });
};

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

export const bindDeviceAPIV2 = (token) => {
    return request("POST", "/user/device/bindDevice/v2", {
        token: token,
    });
};

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

// 测试环境根据设备二维码编号解绑设备，不校验设备归属。
export const unbindDeviceByQrcodeIdAPI = (id) => {
    return request("POST", "/user/device/unbindByQrcodeId", {id});
};

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

export const createPractiseAPI = (arrows, time, target) => {
    return request("POST", "/user/practice/create", {
        shootNumber: arrows,
        shootTime: time,
        targetType: target * 20,
    });
};

export const createPractiseV2API = (trainingType, difficultyLevel) => {
    return request("POST", "/user/practice/create/v2", {
        trainingType,
        difficultyLevel,
    });
};

export const getCurrentPractiseAPI = () => {
    return request("GET", "/user/practice/current");
};

export const startPractiseAPI = (id) => {
    return request("POST", "/user/practice/begin", { id });
};

export const endPractiseAPI = (id) => {
    return request("POST", "/user/practice/stop", { id });
};

export const getPractiseAPI = async (id) => {
    return request("GET", `/user/practice/get?id=${id}`);
};

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

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, userId) => {
    return request("POST", "/user/room/exitRoom", {
        number,
        userId,
    });
};

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,
        readyTime: 15,
        targetType: 20,
    });
};

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

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 result = await request("POST", "/user/battle/details/list", {
        page,
        pageSize: 10,
        battleType,
    });
    return result.list;
};

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",
        returnUrl: "",
        remark: "",
        mockTest: false,
    });
};

export const virtualPayOrderAPI = (vipId = 0, code = "") => {
    return request("POST", "/user/virtualPay/createOrder", {
        vipId,
        code,
    });
};

export const getOrderDetailAPI = (orderId) => {
    return request("GET", `/user/order/detail?orderId=${encodeURIComponent(orderId)}`);
};

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 getUserGameState = () => {
    return request("GET", "/user/state");
};

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 getPersonalTrainingAPI = async () => {
    return request("GET", "/personal/training");
};

export const getTrainingDifficultyListAPI = async (type) => {
    const query = type ? `?type=${encodeURIComponent(type)}` : "";
    return request("GET", `/training/difficulty/list${query}`);
};

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 aimRenewAPI = () => {
    const token = uni.getStorageSync(
        `${uni.getAccountInfoSync().miniProgram.envVersion}_token`
    );
    const header = {};
    if (token) header.Authorization = `Bearer ${token}`;

    uni.request({
        url: `${BASE_URL}/user/device/aimRenew`,
        method: "POST",
        header,
        data: {},
        timeout: 10000,
        success: () => {},
        fail: () => {},
    });
};

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

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

// 设备连接指定 WiFi，只下发 WiFi 凭证，不触发 OTA 升级。
export const connectDeviceWifiAPI = async (ssid, password) => {
    return request("POST", "/user/hardwareBox/connectWifi", {ssid, password});
};

// 获取硬件盒子版本信息，用于判断当前设备是否需要 OTA 升级。
export const getHardwareBoxVersionAPI = async () => {
    return request("GET", "/user/hardwareBox/version");
};

// 发送硬件盒子 OTA 更新指令，服务端会返回后续轮询使用的任务 ID。
export const sendHardwareBoxUpdateAPI = async (data) => {
    return request("POST", "/user/hardwareBox/sendUpdate", data);
};

// 根据任务 ID 获取硬件盒子 OTA 更新状态。
export const getHardwareBoxTaskStatusAPI = async (taskId) => {
    return request("GET", `/user/hardwareBox/taskStatus?taskId=${taskId}`);
};

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);
};

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

export const getPointBookRankListAPI = (page = 1) => {
    return request(
        "GET",
        `/user/score/sheet/week/shoot/rank/list?pageNum=${page}&pageSize=100`
    );
};

export const clickLikeAPI = (userId, ifLike) => {
    return request("POST", "/user/score/sheet/week/shoot/rank/like", {
        userId,
        ifLike,
    });
};

export const getMyLikeList = (page = 1, pageSize = 10) => {
    return request(
        "GET",
        `/user/score/sheet/week/shoot/rank/like/list?pageNum=${page}&pageSize=${pageSize}`
    );
};

export const getReadyAPI = (roomId) => {
    return request("POST", `/user/room/ready`, {
        roomId,
    });
};

export const getBattleAPI = async (battleId) => {
    const result = await request("POST", "/user/match/info", {
        id: battleId,
    });
    return normalizeBattleApiResult(result);
};

export const kickPlayerAPI = (number, userId) => {
    return request("POST", "/user/room/kicking", {
        number,
        userId,
    });
};

// 获取赛季列表
export const getSeasonList = () => {
    return request("GET", "/index/season/list");
};

// 获取赛季统计
export const getSeasonStats = (seasonId) => {
    const data = {};
    if (seasonId !== undefined && seasonId !== null) data.seasonId = seasonId;
    return request("GET", "/index/season/stats", data);
};

//获取积分榜
export const getScoreRankList = (seasonId, page, perPage) => {
    return request("GET", "/index/score/rank/list", {
		seasonId,
		page,
		perPage
	});
};

// 获取10环排行榜
export const getTenRingRankList = (seasonId, page, perPage) => {
    return request("GET", "/index/tenRing/rank/list", {
		seasonId,
		page,
		perPage
	});
};

// 获取MVP排行榜
export const getMvpRankList = (seasonId, page, perPage) => {
    return request("GET", "/index/mvp/rank/list", {
		seasonId,
		page,
		perPage
	});
};

// 获取我的积分排名
export const getMyScoreRank = (seasonId) => {
    const data = {};
    if (seasonId !== undefined && seasonId !== null) data.seasonId = seasonId;
    return request("GET", "/index/myScoreRank", data);
};

// 获取我的MVP排名
export const getMyMvpRank = (seasonId) => {
    const data = {};
    if (seasonId !== undefined && seasonId !== null) data.seasonId = seasonId;
    return request("GET", "/index/myMvpRank", data);
};

// 获取我的10环排名
export const getMyTenRingRank = (seasonId) => {
    const data = {};
    if (seasonId !== undefined && seasonId !== null) data.seasonId = seasonId;
    return request("GET", "/index/myTenRingRank", data);
};
