import {
    doPostCartItem,
    doFetchQuote,
    doFetchCartProducts,
    doFetchTotalAmt,
    doDeleteCartProduct,
    doPutCartItem,
    doFetchCoupon,
    doApplyDiscountCode,
    doRemoveDiscountCode,
    // doFetchCartId,
    doPostGiftCartItem,
    doPutGiftCartItem,
    doPostConfiguredCartItem,
    doPutConfiguredCartItem,
    doFetchGiftMessage,
    doPutCConectionCartItem
} from '@/services/user_cart.service';
// import { getCookieByName, removeCookieByName } from '@/services/auth';
import { getField, updateField } from 'vuex-map-fields';
import humps from 'lodash-humps';
import { getAuthUser } from '@/services/auth';
//import { criteoViewBasket ,listrakCartList,listrakCartListClear} from "@/services/util.service";
/* eslint-disable no-alert, no-console ,  no-debugger */
export const userCartProduct = {
    namespaced: true,
    state: {
        cartDrawer: false,
        inProgress: false,
        fetchInProgress: false,
        cartProduct: [],
        cartProductList: [],
        productTotalAmt: [],
        productMedia: {},
        discountCode: null,
        errorMessage: null,
        cartProductsProgress: false,
        cartTotalAmtProgress: false,
        cartProductDetails: [],
        giftCartDetails: {
            // "senderName": "",
            // "senderEmail": "",
            "recipientName": "",
            "recipientEmail": "",
            "senderMessage": "",
            //"giftCardQty": "",
            "giftCardAmt": ""
        },
        autoLogoutFlag: false,

    },
    getters: {
        getField
    },
    mutations: {
        updateField,

        inProgress(state, yesOrNo) {
            state.inProgress = yesOrNo
        },
        cartProductsProgress(state, yesOrNo) {
            state.cartProductsProgress = yesOrNo
        },
        cartTotalAmtProgress(state, yesOrNo) {
            state.cartTotalAmtProgress = yesOrNo
        },
        setCartDrawer(state, yesOrNo) {
            state.cartDrawer = yesOrNo
        },
        fetchInProgress(state, yesOrNo) {
            state.fetchInProgress = yesOrNo
        },
        setCartProduct(state, product) {
            state.cartProduct = product
        },
        setCartProductList(state, list) {
            state.cartProductList = list
           // criteoViewBasket(list);
        },
        /* setCriteoViewBasket(state) {
            criteoViewBasket(state.cartProductList);
        },
       setListrakCartList(state) {
            listrakCartList(state.cartProductList);
        },
        setListrakCartListClear(){
            listrakCartListClear()
        },*/
        setCartProductDetails(state, details) {
            state.cartProductDetails = details
        },
        setProductAmt(state, amt) {
            state.productTotalAmt = amt;
        },
        setCouponCode(state, code) {
            state.discountCode = code.toString();
        },
        setErrorMessage(state, err) {
            state.errorMessage = err
        },
        setProductsMedia(state, media) {
            state.productMedia = media
        },
        setAutoLogoutFlag(state, flag) {
            state.autoLogoutFlag = flag
        },
        setGiftMessageData(state, giftMessage) {
            if (giftMessage[0].productOption) {
                state.giftCartDetails.recipientName = giftMessage[0].productOption.infoBuyRequest.giftcardRecipientName,
                    state.giftCartDetails.recipientEmail = giftMessage[0].productOption.infoBuyRequest.giftcardRecipientEmail,
                    state.giftCartDetails.senderMessage = giftMessage[0].productOption.infoBuyRequest.giftcardMessage,
                    state.giftCartDetails.giftCardAmt = (giftMessage[0].productOption.infoBuyRequest.giftcardAmount)
            }
        },
    },
    actions: {
        addToCart: async({ commit, state }, data) => {
            try {
                let result;
                commit('inProgress', true);
                if (!state.cartProductDetails.length > 0) {
                    const userQuote = await doFetchQuote();
                    localStorage.setItem("cr_userQuoteId", userQuote); //no use
                    result = await doPostCartItem(data.sku, data.qty, data.ccid, data.price, data.personalizeDetails, data.builderId?data.builderId:null, userQuote);
                } else {
                    result = await doPostCartItem(data.sku, data.qty, data.ccid, data.price, data.personalizeDetails, data.builderId?data.builderId:null, state.cartProductDetails[0].quoteId);
                }
                commit('inProgress', false);
                return result;
            } catch (err) {
                commit('inProgress', false);
                throw err;
            }
        },
        addToConfiguredCart: async({ commit, state }, data) => {
            try {
                commit('inProgress', true);
                let result;
                if (!state.cartProductDetails.length > 0) {
                    const userQuote = await doFetchQuote();
                    localStorage.setItem("cr_userQuoteId", userQuote); //no use
                    result = await doPostConfiguredCartItem(data.sku, data.qty, data.typeId, data.optionId, data.optionValue, userQuote);
                } else {
                    result = await doPostConfiguredCartItem(data.sku, data.qty, data.typeId, data.optionId, data.optionValue, state.cartProductDetails[0].quoteId);
                }
                commit('inProgress', false);
                commit('setCartDrawer', true);
                return result;
            } catch (err) {
                commit('inProgress', false);
                throw err;
            }
        },
        addToGiftCart: async({ commit, state }, data) => {
            try {
                let result;
                commit('inProgress', true);
                if (!state.cartProductDetails.length > 0) {
                    const userQuote = await doFetchQuote();
                    localStorage.setItem("cr_userQuoteId", userQuote); //no use
                    if (data.giftCartDetails) {
                        result = await doPostGiftCartItem(data.sku, data.qty, userQuote, data.senderName, data.senderEmail, data.giftCartDetails);
                    } else {
                        result = await doPostGiftCartItem(data.sku, data.qty, userQuote, data.senderName, data.senderEmail, state.giftCartDetails);
                    }
                } else {
                    if (data.giftCartDetails) {
                        result = await doPostGiftCartItem(data.sku, data.qty, state.cartProductDetails[0].quoteId, data.senderName, data.senderEmail, data.giftCartDetails);
                    } else {
                        result = await doPostGiftCartItem(data.sku, data.qty, state.cartProductDetails[0].quoteId, data.senderName, data.senderEmail, state.giftCartDetails);
                    }
                }
                commit('inProgress', false);
                commit('setCartDrawer', true);
                return result;
            } catch (err) {
                commit('inProgress', false);
                throw err;
            }
        },
        productTotalAmt: async({ commit }) => {
            commit('cartTotalAmtProgress', true);
            doFetchTotalAmt().then((productTotalAmt) => {
                    commit('cartTotalAmtProgress', false)
                    commit('setProductAmt', humps(productTotalAmt))
                })
                .catch(() => commit('cartTotalAmtProgress', false))
        },
        cartProductList: async({ commit, dispatch }) => {
            commit('setCartProductList', []);
            commit('cartProductsProgress', true);
            return doFetchQuote().then(async(quoteId) => {                 
                        let cartProductList = await doFetchCartProducts(quoteId);
                        commit('setCartProductDetails', humps(cartProductList))
                        commit('setCartProductList', humps(cartProductList))
                        commit('cartProductsProgress', false);
                        dispatch('productTotalAmt');
                    // }
                })
                .catch(() => commit('cartProductsProgress', false))
        },
        removeCartProduct: async({ commit, dispatch }, { productId }) => {
            try {
                commit('cartProductsProgress', true);
                let trueOrFalse = await doDeleteCartProduct(productId);
                if (trueOrFalse) {
                    commit('cartProductsProgress', false);
                    commit('cartTotalAmtProgress', false);
                    commit('setCartDrawer', false);
                    await dispatch('cartProductList');
                   // dispatch('setListrakCartListClear')

                }
            } catch (err) {
                commit('cartProductsProgress', false);
                throw err;
            }
        },
        updateToCart: async({ commit, dispatch, state }, data) => {
            try {
                let userQuote = state.cartProductDetails[0].quoteId;
                commit('cartProductsProgress', true);
                const cartProduct = await doPutCartItem(data.sku, data.qty, userQuote, data.itemId, data.ccid, data.price, data.personalizeDetails);
                if (cartProduct) {
                    commit('cartProductsProgress', false);
                    if (data.routeName != 'CartProducts') {
                        commit('setCartDrawer', true);
                    }
                    commit('setCartProduct', (cartProduct));
                    await dispatch('cartProductList');
                    return (cartProduct);
                }
            } catch (err) {
                await dispatch('cartProductList');
                commit('cartProductsProgress', false);
                throw err;
            }

        },
        updateToCConectionCart: async({ commit }, data) => {
            try {
                commit('cartProductsProgress', true);
                const response = await doPutCConectionCartItem(data.sku, data.qty, data.ccid);
                commit('cartProductsProgress', false);
                return (response);

            } catch (err) {
                commit('cartProductsProgress', false);
                throw err;
            }
        },
        updateToConfiguredCart: async({ commit, dispatch, state }, data) => {
            try {
                commit('cartProductsProgress', true);
                let userQuote = state.cartProductDetails[0].quoteId;
                const cartProduct = await doPutConfiguredCartItem(data.sku, data.qty, userQuote, data.itemId, data.optionId, data.optionValue);
                if (cartProduct) {
                    commit('cartProductsProgress', false);
                    if (data.routeName != 'CartProducts') {
                        commit('setCartDrawer', true);
                    }
                    commit('setCartProduct', (cartProduct));
                    dispatch('cartProductList');
                }
            } catch (err) {
                await dispatch('cartProductList');
                commit('cartProductsProgress', false);
                throw err;
            }

        },
        updateToGiftCart: async({ commit, dispatch, state }, data) => {
            try {
                commit('inProgress', true);
                data.userQuote = state.cartProductDetails[0].quoteId;
                const cartProduct = await doPutGiftCartItem(data, state.giftCartDetails);
                if (cartProduct) {
                    commit('inProgress', false);
                    if (data.routeName != 'CartProducts') {
                        commit('setCartDrawer', true);
                    }
                    commit('setCartProduct', (cartProduct));
                    dispatch('cartProductList');
                }
            } catch (err) {
                await dispatch('cartProductList');
                commit('inProgress', false);
                throw err;
            }

        },
        cartDrawer: async({ commit }, flag) => {
            commit('setCartDrawer', flag)
        },
        fetchCartCoupon: async({ commit }) => {
            commit('fetchInProgress', true);
            try {
                let coupon = await doFetchCoupon();
                if (coupon) {
                    commit('fetchInProgress', false);
                    commit('setCouponCode', coupon);
                }
            } catch (err) {
                commit('fetchInProgress', false);
                throw err;
            }
        },
        applyDiscountCode: async({ commit, dispatch }, code) => {
            commit('fetchInProgress', true);
            try {
                let coupon = await doApplyDiscountCode(code);
                commit('fetchInProgress', false);
                if (coupon) {
                    dispatch('fetchCartCoupon');
                }
            } catch (err) {
                commit('fetchInProgress', false);
                throw err;
            }
        },
        removeDiscountCode: async({ commit, dispatch }, code) => {
            commit('fetchInProgress', true);
            try {
                let coupon = await doRemoveDiscountCode(code);
                if (coupon) {
                    commit('fetchInProgress', false);
                    dispatch('fetchCartCoupon');

                }
            } catch (err) {
                commit('fetchInProgress', false);
                throw err;
            }
        },
        fetchGiftMessage: async({ commit, state }, data) => {
            try {
                commit('fetchInProgress', true);
                let userQuote = state.cartProductDetails[0].quoteId;
                const giftMessageData = await doFetchGiftMessage(userQuote, data.itemId);
                if (giftMessageData) {
                    commit('fetchInProgress', false);
                    commit('setGiftMessageData', humps(giftMessageData));
                }
            } catch (err) {
                commit('fetchInProgress', false);
                throw err;
            }
        },
        /* resetUserDetails: ({ commit }) => {
             try {
                 commit('setCartProductList', []);
                 commit('setProductAmt', {});
             } catch (err) {
                 throw err;
             }
         },*/
        checkUserToken: ({ commit, dispatch }, obj) => {
            let timeInterval = null;
            timeInterval = setInterval(() => {
                if (!getAuthUser()) {
                    console.log('setInterval', timeInterval, obj);
                    commit('setCartProductList', []);
                    commit('setProductAmt', {});
                    commit('setAutoLogoutFlag', true);
                    dispatch('auth/logout', {}, { root: true });
                    clearInterval(timeInterval);
                }
            }, 3000);
        },
        /*  setCriteoViewBasket: async({ commit ,state}) => {
            if(state.cartProductList.length > 0)
            {
                commit('setCriteoViewBasket');
            }
        },
     setListrakCartList: async({ commit ,state}) => {
            if(state.cartProductList.length > 0)
            {
                commit('setListrakCartList');
            }
        },
        setListrakCartListClear: async({ commit,state }) => {
            if(state.cartProductList.length <= 0)
            {
                commit('setListrakCartListClear');
            }
        },*/
    }
}