import { defineStore } from "pinia";
import _ from "lodash";
import taxTypeEnum from "../enums/modules/taxTypeEnum";

export const usePosCartStore = defineStore("posCart", {
    persist: true,
    state: () => ({
        lists: [],
        subtotal: 0,
        discount: 0,
        totalTax: 0,
        deliveryDays: 0,
        deliveryDates: [],
        mealTypes: [],
    }),
    actions: {
        fetchLists: function (payload) {
            return new Promise((resolve) => {
                if (payload.length > 0) {
                    let isNew = false;
                    let newChecker = [];
                    let variationAndExtraChecker = [];
                    _.forEach(payload, (pay) => {
                        if (this.lists.length === 0) {
                            isNew = true;
                        } else {
                            isNew = true;
                            _.forEach(this.lists, (list, listKey) => {
                                if (list.item_id === pay.item_id) {

                                    if (this.lists[listKey].item_variations.variations !== "undefined") {
                                        if (Object.keys(this.lists[listKey].item_variations.variations).length !== 0) {
                                            _.forEach(this.lists[listKey].item_variations.variations, (variationId, variationKey) => {
                                                if (pay.item_variations.variations[variationKey] !== "undefined" && pay.item_variations.variations[variationKey] === variationId) {
                                                    variationAndExtraChecker.push(true);
                                                } else {
                                                    variationAndExtraChecker.push(false);
                                                }
                                            });
                                        }
                                    }

                                    if (variationAndExtraChecker.includes(false)) {
                                        newChecker.push(false);
                                    } else {
                                        newChecker.push(true);
                                        this.lists[listKey].quantity += pay.quantity;
                                    }
                                    variationAndExtraChecker = [];
                                } else {
                                    newChecker.push(false);
                                }
                            });

                            _.forEach(newChecker, (check) => {
                                if (check) {
                                    isNew = false;
                                }
                            });
                            newChecker = [];
                        }

                        if (isNew) {
                            this.lists.push({
                                item_category: pay.item_category,
                                discount: pay.discount,
                                image: pay.image,
                                instruction: pay.instruction,
                                item_id: pay.item_id,
                                item_variation_total: pay.item_variation_total,
                                item_variations: pay.item_variations,
                                name: pay.name,
                                currency_price: pay.currency_price,
                                convert_price: pay.convert_price,
                                quantity: pay.quantity,
                                taxes: pay.taxes,
                                total_tax: 0,
                                total: 0,
                            });
                            isNew = false;
                        }
                    });
                }
                this.fetchSubtotal();
                this.taxCalculation();
                resolve(true);
            });
        },
        fetchSubtotal: function () {
            if (this.lists.length > 0) {
                let subtotal = 0;
                _.forEach(this.lists, (list, listKey) => {
                    this.lists[listKey].total = ((list.convert_price + list.item_variation_total) * list.quantity);
                    subtotal += this.lists[listKey].total;
                });
                this.subtotal = subtotal;
            } else {
                this.subtotal = 0;
            }
            this.updateMealTypes();
        },
        quantity: function (payload) {
            if (payload.status === "increment") {
                this.lists[payload.id].quantity++;
            } else if (payload.status === "decrement") {
                if (this.lists[payload.id].quantity === 1) {
                    this.lists.splice(payload.id, 1);
                } else {
                    this.lists[payload.id].quantity--;
                }
            } else {
                this.lists[payload.id].quantity = payload.status;
            }
            this.fetchSubtotal();
            this.taxCalculation();
            this.discount = 0;
        },
        deleteCartItem: function (payload) {
            if (payload.status === "decrement") {
                this.lists.splice(payload.id, 1);
            }
            this.fetchSubtotal();
            this.taxCalculation();
        },
        taxCalculation: function () {
            let totalTax = 0;
            _.forEach(this.lists, (list, listKey) => {
                if (list.taxes.length > 0) {
                    let taxes = [];
                    let total_tax = 0;
                    _.forEach(list.taxes, (tax, taxKey) => {
                        if (tax.tax_rate > 0) {
                            let taxPrice = 0;
                            if (tax.type === taxTypeEnum.PERCENTAGE) {
                                taxPrice = (((list.convert_price + list.item_variation_total) / 100) * parseFloat(tax.tax_rate));
                            } else {
                                taxPrice = tax.tax_rate;
                            }
                            total_tax += taxPrice;
                            taxes.push({
                                id: tax.id,
                                name: tax.name,
                                code: tax.code,
                                type: tax.type,
                                tax_rate: parseFloat(tax.tax_rate),
                                tax_amount: parseFloat(taxPrice)
                            })
                        }
                    });
                    this.lists[listKey].taxes = taxes;
                    this.lists[listKey].total_tax = (total_tax * this.lists[listKey].quantity);
                }
                totalTax += this.lists[listKey].total_tax;
            });
            this.totalTax = totalTax;
        },
        updateDeliveryDays: function (payload) {
            this.deliveryDays = payload;
        },
        updateDeliveryDates: function (payload) {
            this.deliveryDates = payload;
        },
        updateMealTypes: function () {
            if (this.lists.length > 0) {
                let map = new Map();
                this.lists.forEach(list => {
                    let cat = list.item_category;
                    if (cat && !map.has(cat.id)) {
                        map.set(cat.id, { id: cat.id, name: cat.name });
                    }
                });
                this.mealTypes = Array.from(map.values());
            } else {
                this.mealTypes = [];
            }
        },
        updatedDiscount: function (payload) {
            this.discount = payload;
        },
        resetCart: function () {
            this.lists = [];
            this.subtotal = 0;
            this.discount = 0;
            this.deliveryDays = 0;
            this.totalTax = 0;
            this.deliveryDates = [];
            this.mealTypes = [];
        },
    },
});
