import { defineStore } from 'pinia'

const STORAGE_KEY = 'BETTING_CART_LIST'

const getLocalOrders = () => {
    try {
        const data = localStorage.getItem(STORAGE_KEY)
        return data ? JSON.parse(data) : []
    } catch (e) {
        console.error('解析本地注单数据失败:', e)
        return []
    }
}

export const useOrderStore = defineStore('order', {
    state: () => ({
        selectOrders: getLocalOrders(),
        isOpen: true,
    }),

    getters: {
        selectedCount: (state) => state.selectOrders.length,
        totalStake: (state) => {
            return state.selectOrders.reduce((sum, item) => sum + (Number(item.stake) || 0), 0)
        },
        totalPotentialWin: (state) => {
            return state.selectOrders.reduce((sum, item) => {
                const stake = Number(item.stake) || 0;
                return sum + (stake * Number(item.odds || 0));
            }, 0);
        }
    },

    actions: {
        toggleSheet() { this.isOpen = !this.isOpen; },
        setSheetOpen(status) { this.isOpen = status; },

        addOrderItem(item) {
            const index = this.selectOrders.findIndex(o => o.uniqueKey === item.uniqueKey);
            if (index === -1) {
                const newItem = { ...item, stake: Number(item.minimum || 10), errorMsg: '' };
                this.selectOrders.push(newItem);
            } else {
                this.selectOrders[index].odds = item.odds;
                this.selectOrders[index].errorMsg = '';
            }
            this.saveToStorage();
        },

        // =======================================
        // 处理订单失败核心逻辑 (带智能重建功能)
        // =======================================
        markOrderFailure(failedData, errorMsg) {
            // 1. 尝试在现有购物车中寻找目标注单
            const targetOrder = this.selectOrders.find(o =>
                String(o.data_id) === String(failedData.data_id) &&
                String(o.marketId) === String(failedData.id) &&
                String(o.optionValue) === String(failedData.value) &&
                String(o.handicap || '') === String(failedData.handicap || '')
            );

            if (targetOrder) {
                // 场景 A：同步 HTTP 请求报错，注单还在购物车里 -> 直接挂载报错
                targetOrder.errorMsg = errorMsg;
            } else if (failedData.sport_info) {
                // 场景 B：WebSocket 异步拒单，注单已被清空 -> 提取 sport_info 强行重建注单
                const sport = failedData.sport_info;
                let marketName = '未知玩法';

                // 解析 JSON 格式的 odds 寻找玩法名称
                try {
                    const oddsArr = typeof sport.odds === 'string' ? JSON.parse(sport.odds) : (sport.odds || []);
                    const market = oddsArr.find(m => String(m.id) === String(failedData.id));
                    if (market) marketName = market.name;
                } catch (e) {
                    console.error('解析玩法名称失败', e);
                }

                // 生成与前端一致的 UniqueKey
                let uniqueKey = `${sport.id}_${failedData.id}_${failedData.value}`;
                if (failedData.handicap !== null && failedData.handicap !== undefined && failedData.handicap !== '') {
                    uniqueKey += `_${failedData.handicap}`;
                }

                // 重建标准注单结构
                const rebuiltItem = {
                    matchId: sport.id,
                    data_id: sport.data_id,
                    league: sport.league || sport.league_en,
                    homeTeam: sport.home_team || sport.home_team_en,
                    guestTeam: sport.guest_team || sport.guest_team_en,
                    betType: marketName,
                    betTypeName: failedData.value, // 后期如果需要翻译这里可以包一层翻译函数
                    handicap: failedData.handicap,
                    odds: failedData.odd,
                    score: sport.score,
                    state: sport.state,
                    status: sport.status,
                    is_roll: sport.is_roll,
                    is_locked: sport.is_locked,
                    uniqueKey: uniqueKey,
                    optionValue: failedData.value,
                    submit_value: failedData.submit_value,
                     mininum: failedData.mininum, // 新增：最低限额
                     maxinum: failedData.maxinum, // 新增：最高限额
                    marketId: failedData.id,
                    stake: failedData.amount || 20,
                    errorMsg: errorMsg, // 挂载报错原因
                     selection: {
                        submit_value: failedData.submit_value,
                        ...failedData
                    }
                };

                this.selectOrders.push(rebuiltItem);
            }

            // 强行展开侧边栏提醒用户，并持久化缓存
            this.isOpen = true;
            this.saveToStorage();
        },

        clearItemError(uniqueKey) {
            const item = this.selectOrders.find(o => o.uniqueKey === uniqueKey);
            if (item && item.errorMsg) {
                item.errorMsg = '';
                this.saveToStorage();
            }
        },

        removeOrderItem(itemOrKey) {
            const targetKey = typeof itemOrKey === 'object' ? itemOrKey.uniqueKey : itemOrKey;
            this.selectOrders = this.selectOrders.filter(o => o.uniqueKey !== targetKey);
            if (this.selectOrders.length === 0) {
                this.isOpen = false;
            }
            this.saveToStorage();
        },

        removeOrderItemByKey(key) {
            this.removeOrderItem(key);
        },

        updateStake(uniqueKey, amount) {
            const item = this.selectOrders.find(o => o.uniqueKey === uniqueKey);
            if (item) {
                item.stake = amount;
                item.errorMsg = ''; // 用户修改金额时自动清空错误提示
                this.saveToStorage();
            }
        },

        updateMatchStatus(data_id, newMatchData) {
            let changed = false;
            this.selectOrders.forEach(order => {
                if (order.data_id === data_id) {
                    if(newMatchData.state !== undefined) order.state = newMatchData.state;
                    if(newMatchData.status !== undefined) order.status = newMatchData.status;
                    if(newMatchData.is_locked !== undefined) order.is_locked = newMatchData.is_locked;
                    if(newMatchData.score !== undefined) order.score = newMatchData.score;
                    changed = true;
                }
            });
            if (changed) this.saveToStorage();
        },

        clearAllOrders() {
            this.selectOrders = [];
            this.isOpen = false;
            this.saveToStorage();
        },

        saveToStorage() {
            try {
                localStorage.setItem(STORAGE_KEY, JSON.stringify(this.selectOrders));
            } catch (e) {
                console.error('保存注单数据到本地失败:', e)
            }
        }
    }
})
