<template>
<ul>
    <li
    v-for="product in products"
    :key="product.id">
    {{ product.title }} - {{ product.price }} x {{ product.inventory }}
    <br>
    <el-input-number v-if="product.inventory" :min="1" :max="product.inventory" v-model="numbers[product.id]" />
    <el-input-number v-else :disabled="true" />
    <el-button
        :disabled="!product.inventory"
        @click="addProductToCart(product)">
        加入购物车
    </el-button>
    </li>
</ul>
</template>

<script lang="ts">
import type { product } from '../api/shop'

type Numbers = {
    [id: number]: number
}
</script>

<script setup lang="ts">
import { reactive, computed, watch } from 'vue'
import { useCart } from '../store/cart'
import { useProducts } from '../store/products'
import { ElButton } from 'element-plus'

const numbers = reactive({}) as Numbers
const products = computed(() => useProducts().all)
const addProductToCart = (product: product) => {
    numbers[product.id] = numbers !== {} && numbers[product.id] < 1 ? 1 : numbers[product.id]
    numbers[product.id] = numbers[product.id] > product.inventory ? product.inventory : numbers[product.id]

    useCart().addProductToCart(product, numbers[product.id])
    numbers[product.id] = 1
}

watch(products, (val) => {
    val.forEach((product) => {
        if (!numbers.hasOwnProperty(product.id)) {
            numbers[product.id] = 1
        }
    })
}, {
    // 添加 immediate: true 后该回调将会在侦听开始之后被立即调用
    immediate: true
})

// 加载商品列表
useProducts().getAllProducts()
</script>