import { defineStore } from 'pinia';
import { ref, computed, watch } from 'vue';

export const useBetCartStore = defineStore('self_betCart', () => {
    // 1. 状态
    const selectedBets = ref(JSON.parse(localStorage.getItem('self_lottery_cart') || '[]'));
    const isOpen = ref(true); // 控制侧边栏展开/收起
    const randomTrigger = ref(0); // 用于全局触发具体页面的“机选”动作

    // 2. 监听变化，持久化到本地
    watch(selectedBets, (newVal) => {
        localStorage.setItem('self_lottery_cart', JSON.stringify(newVal));
    }, { deep: true });

    // 3. 计算属性
    const totalBets = computed(() => selectedBets.value.length);
    const totalAmount = computed(() => {
        return selectedBets.value.reduce((sum, item) => sum + (Number(item.amount) || 0), 0);
    });

    // 4. 操作方法
    const setSheetOpen = (val) => {
        isOpen.value = val;
    };

    const hasBet = (id) => selectedBets.value.some(b => b.id === id);

    const toggleBet = (betItem) => {
        const index = selectedBets.value.findIndex(b => b.id === betItem.id);
        if (index > -1) {
            selectedBets.value.splice(index, 1);
        } else {
            selectedBets.value.push(betItem);
        }
        // 选中注单时自动展开侧边栏
        if (selectedBets.value.length > 0) isOpen.value = true;
    };

    const removeBet = (id) => {
        selectedBets.value = selectedBets.value.filter(b => b.id !== id);
        if (selectedBets.value.length === 0) isOpen.value = false;
    };

    const clearBets = () => {
        selectedBets.value = [];
        isOpen.value = false;
    };

    // 触发全局机选
    const triggerRandom = () => {
        randomTrigger.value++;
    };

    return {
        selectedBets,
        isOpen,
        randomTrigger,
        totalBets,
        totalAmount,
        hasBet,
        toggleBet,
        removeBet,
        clearBets,
        setSheetOpen,
        triggerRandom
    };
});
