import { defineStore } from 'pinia'

const STORAGE_KEY = 'ExtremeSpeed28_CART_LIST'

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

export const useExtremeSpeed28CartStore = defineStore('ExtremeSpeed28Cart', {
    state: () => ({
        selectOrders: getLocalOrders(),
        isOpen: false, // 控制左侧购物车的展开/收起状态
    }),

    getters: {
        selectedCount: (state) => state.selectOrders.length,
        totalStake: (state) => {
            return state.selectOrders.reduce((sum, item) => sum + (Number(item.amount) || 0), 0)
        }
    },

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

        // 切换选中状态：如果有就删除，如果没有就添加
        toggleOrderItem(rule) {
            const index = this.selectOrders.findIndex(item => item.id === rule.id);
            if (index > -1) {
                this.selectOrders.splice(index, 1);
                if (this.selectOrders.length === 0) this.isOpen = false;
            } else {
                // 默认金额为接口下发的最小限额，如果没有则默认为20
                const defaultAmount = Number(rule.mininum) > 0 ? Number(rule.mininum) : 20;
                this.selectOrders.push({
                    ...rule,
                    uniqueKey: rule.id, // 使用规则的 id 作为唯一标识
                    amount: defaultAmount
                });
                // 添加注单时，自动展开购物车
                this.isOpen = true;
            }
            this.saveToStorage();
        },

        removeOrderItem(id) {
            this.selectOrders = this.selectOrders.filter(item => item.id !== id);
            if (this.selectOrders.length === 0) {
                this.isOpen = false;
            }
            this.saveToStorage();
        },

        updateStake(id, amount) {
            const item = this.selectOrders.find(o => o.id === id);
            if (item) {
                item.amount = amount;
                this.saveToStorage();
            }
        },

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

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