// @ts-nocheck
// components/cart-item/cart-item.ts
export { }
const app = getApp<IAppOption>();
Component({

    /**
     * 组件的属性列表
     */
    properties: {
        item: {},
        shoppingCart: {},
    },

    /**
     * 组件的初始数据
     */
    data: {
        totalPrice: 0,
        showStock: app.globalData.showStock

    },

    /**
     * 组件的方法列表
     */
    methods: {
        calcTotalPrice() {
            if (!this.data.shoppingCart || !this.data.shoppingCart.data) return 0;
            const total = this.data.shoppingCart.data.reduce((sum: number, item: any) => {
                return sum + item.price * item.count;
            }, 0);
            this.setData({ totalPrice: total });
        },
        handleCountChange(e: any) {
            this.setData({ item: { ...this.data.item, count: e.detail } })

            const target = this.data.shoppingCart.data.find(
                (item: any) => item.skuId == this.data.item.skuId
            )
            if (target) target.count = e.detail;
            let storage = wx.getStorageSync("shoppingCart") || [];
            storage = storage.map((cart: any) => {
                if (cart.mbuId == this.data.shoppingCart.mbuId) {
                    return this.data.shoppingCart;
                }
                return cart;
            });
            wx.setStorageSync("shoppingCart", storage);
            this.calcTotalPrice();
            this.triggerEvent('handleCountChange', {
                totalPrice: this.data.totalPrice
            })
        },
        handleDelete() {
            this.triggerEvent('delete', {
                skuId: this.data.item.skuId
            })
        }
    },
    lifetimes: {
        created: function () {

        }
    }
})