import { defineStore } from 'pinia'
import { computed } from 'vue'
import { ref } from 'vue'
import { getRentingCabinetDetailApi } from '@/common/apis/cabinet/index'
import type { CabinetCellEntity, RentingCabinetDetailDTO } from '@/common/apis/cabinet/type'

export const useRentingCabinetStore = defineStore('rentingCabinet', () => {
    const rentingCabinets = ref<RentingCabinetDetailDTO[]>([])

    // 租用购物车列表
    const rentingCartItems = ref<Array<{ cabinetCell: CabinetCellEntity; quantity: number }>>([])

    const fetchRentingCabinetDetail = async (shopId: number) => {
        const res = await getRentingCabinetDetailApi(shopId);
        console.log(res)
        if (res.code === 0 && res.data) {
            rentingCabinets.value = res.data
        }
    }

    // 添加到租用购物车
    const addToRentingCart = (cabinetCell: CabinetCellEntity, quantity: number = 1): boolean => {
        if (quantity <= 0) return false
        const existingItem = rentingCartItems.value.find(item => item.cabinetCell.cellId === cabinetCell.cellId)
        if (existingItem) {
            existingItem.quantity += quantity
        } else {
            rentingCartItems.value.push({ cabinetCell, quantity })
        }
        return true
    }

    // 从购物车移除
    const removeFromRentingCart = (cellId: number, quantity: number = 1) => {
        const index = rentingCartItems.value.findIndex(item => item.cabinetCell.cellId === cellId)
        if (index !== -1) {
            if (rentingCartItems.value[index].quantity <= quantity) {
                rentingCartItems.value.splice(index, 1)
            } else {
                rentingCartItems.value[index].quantity -= quantity
            }
        }
    }

    // 计算租用总数
    const rentingCartTotalQuantity = computed(() => {
        return rentingCartItems.value.reduce((total, item) => total + item.quantity, 0)
    })

    // 计算租用总价
    const rentingCartTotalPrice = computed(() => {
        return rentingCartItems.value.reduce((sum, item) => {
            return sum + (item.cabinetCell.cellPrice || 0) * item.quantity
        }, 0)
    })

    // 清空租用购物车
    const clearRentingCart = () => {
        rentingCartItems.value = []
    }

    return {
        rentingCabinets,
        rentingCartItems,
        addToRentingCart,
        removeFromRentingCart,
        rentingCartTotalQuantity,
        rentingCartTotalPrice,
        clearRentingCart,
        fetchRentingCabinetDetail
    }
})

export function useRentingCabinetStoreOutside() {
    return useRentingCabinetStore()
}