<template>
  <div>
    <!--<v-col class="mt-12" align="center" v-if="cartProductsProgress">
      <v-progress-circular :size="60" color="primary" indeterminate></v-progress-circular>
    </v-col>-->
    <v-col v-if="cartItems">
     
      <v-card
        elevation="0"
        class="mb-4"
        color="white"
        tile
        v-for="(product, index) in cartItems.slice().reverse()"
        v-bind:key="index"
      >
        <v-row class="mx-1 mt-4">
          <v-col cols="4">
            <div v-if="product.customAttributes.isPersonalize == 1">
              <div v-if="product.personalizeDetails">
                <div v-if="checkThumbnails(product.personalizeDetails)">
                  <div
                    v-for="(item, itemIndex) in JSON.parse(
                      product.personalizeDetails
                    )"
                    :key="itemIndex"
                  >
                    <!-- <p v-if="item.partModified" class="fontsize-14 mb-0 black--text">{{item.name}}</p> -->
                    <v-img
                      v-if="item.partModified && itemIndex < 1"
                      v-bind:src="
                        item.thumbnailUrl
                          ? item.thumbnailUrl
                          : product.customAttributes.thumbnail
                      "
                      class="mb-3"
                      :alt="product.name"
                      :title="product.name"
                    ></v-img>
                  </div>
                </div>
                <div v-else>
                  <v-img
                    v-bind:src="
                      imageBasePathUrl + product.customAttributes.thumbnail
                    "
                    class="mb-3"
                    :alt="product.name"
                    :title="product.name"
                  ></v-img>
                </div>
              </div>
              <div v-else>
                <v-img
                  v-bind:src="imageBasePathUrl + product.customAttributes.image"
                  :alt="product.name"
                  :title="product.name"
                ></v-img>
              </div>
            </div>
            <div v-else>
              <v-img
                v-bind:src="imageBasePathUrl + product.customAttributes.image"
                :alt="product.name"
                :title="product.name"
              ></v-img>
            </div>
          </v-col>
          <v-col cols="8" v-show="!cartProductPage">
            <v-row>
              <v-col class="py-0 ma-0">
                <p
                  class="fontsize-14 text-black mb-6 float-left"                  
                >
                  {{ product.name }}
                </p>
              </v-col>
            </v-row>
            <v-expansion-panels
              class="pa-0 mt-n3"
              flat
              v-show="
                product.productType == 'configurable' ||
                product.productType == 'giftcard'
              "
            >
              <v-expansion-panel class="pa-0 ma-0" v-if="product.productOption">
                <v-expansion-panel-title class="pa-0 ma-0"
                  >See Details</v-expansion-panel-title
                >
                <v-expansion-panel-text
                  v-if="product.productType == 'giftcard'"
                  class="cartproductlist-expansion"
                >
                  <p
                    class="font-weight-bold fontsize-14 black--text float-left cursor-pointer mb-1"
                  >
                    Gift Card Sender
                  </p>
                  <br />
                  <p
                    v-if="product.productOption.infoBuyRequest"
                    class="fontsize-14 black--text float-left cursor-pointer"
                  >
                    {{
                      product.productOption.infoBuyRequest.giftcardSenderName
                    }}
                    <br />
                    {{
                      product.productOption.infoBuyRequest.giftcardSenderEmail
                    }}
                  </p>
                  <br />
                  <p
                    class="font-weight-bold fontsize-14 black--text float-left cursor-pointer mb-1"
                  >
                    Gift Card Recipient
                  </p>
                  <br />
                  <p
                    v-if="product.productOption.infoBuyRequest"
                    class="fontsize-14 black--text float-left cursor-pointer"
                  >
                    {{
                      product.productOption.infoBuyRequest.giftcardRecipientName
                    }}
                    <br />
                    {{
                      product.productOption.infoBuyRequest
                        .giftcardRecipientEmail
                    }}
                  </p>
                </v-expansion-panel-text>
                <v-expansion-panel-text
                  v-else
                  class="cartproductlist-expansion"
                >
                  <p
                    class="font-weight-bold fontsize-14 black--text text-left cursor-pointer mb-1"
                  >
                    Letter
                  </p>
                  <p
                    v-if="product.productOption.attributesInfo.length > 0"
                    class="fontsize-14 black--text cursor-pointer"
                  >
                    {{ product.productOption.attributesInfo[0].value }}
                  </p>
                </v-expansion-panel-text>
              </v-expansion-panel>
            </v-expansion-panels>
            <p class="fontsize-14 mb-6">${{ priceFormatter(product.price) }}</p>

            <div v-if="pageName() != 'CheckoutPage'">
              <v-row
                v-if="product.customAttributes.isPersonalize == 1"
                align="center"
              >
                <v-col cols="auto" class="pr-1 pt-0">
                  <p class="fontsize-14 mb-0 pb-7">Qty.</p>
                </v-col>
                <v-col class="pl-0 pt-0">
                  <v-hover v-slot:default="{ isHovering }">
                    <v-select
                      :items="
                        qtyPriceOptions(
                          product.customAttributes.qtyPrice,
                          product.qty,
                          index
                        )
                      "
                      class="word-break fontsize-16 line-height-21 ls-n009 font-weight-400 cartproductlist-select-button select-change-icon"
                      density="compact"
                      attach
                      flat
                      solo
                      variant="outlined"
                      :class="isHovering ? 'text-primary' : 'text-black'"
                      item-title="price"
                      item-value="qty"
                      single-line
                      @change="
                        updateToCart(
                          product.name,
                          product.sku,
                          product.itemId,
                          index,
                          product.price,
                          product.personalizeDetails,
                          product.productOption,
                          product.customAttributes.letter,
                          product.productType,
                          product.customAttributes.isPersonalize,
                          product.customAttributes.builderVersion,
                          product.ccid,
                          product.parentSku
                        )
                      "
                      v-model="selectedQty[index]"
                      ref="selectedCartQty1"
                      background-color="transparent"
                      append-icon="mdi-plus"
                    >
                      <template v-slot:selection="data">
                        <span class="pl-1 fontsize-14">{{
                          data.item.qty
                        }}</span>
                      </template>
                      <template v-slot:item="data">
                        <template>
                          <v-list-item-content>
                            <v-list-item-title class="text-uppercase">{{
                              data.item.qty
                            }}</v-list-item-title>
                          </v-list-item-content>
                        </template>
                      </template>
                    </v-select>
                  </v-hover>
                </v-col>
              </v-row>
              <v-row align="center" v-else>
                <v-col cols="auto" class="pr-1 py-0">
                  <p class="fontsize-14 mb-0 pb-7">Qty.</p>
                </v-col>
                <v-col class="pl-0 py-0">
                  <v-hover v-slot:default="{ hover }">
                    <v-select
                      :items="
                        numberOptions(
                          product.customAttributes.baMinSalesQty,
                          product.customAttributes.baQtyIncrements,
                          product.qty,
                          index
                        )
                      "
                      class="word-break fontsize-16 line-height-21 ls-n009 font-weight-400 cartproductlist-select-button select-change-icon"
                      dense
                      attach
                      flat
                      solo
                      outlined
                      :class="hover ? 'primary--text' : 'black--text'"
                      single-line
                      @change="
                        updateToCart(
                          product.name,
                          product.sku,
                          product.itemId,
                          index,
                          product.price,
                          product.personalizeDetails,
                          product.productOption,
                          product.customAttributes.letter,
                          product.productType,
                          product.customAttributes.isPersonalize,
                          product.customAttributes.builderVersion,
                          product.ccid,
                          product.parentSku
                        )
                      "
                      v-model="selectedQty[index]"
                      ref="selectedCartQty2"
                      background-color="transparent"
                      append-icon="mdi-plus"
                    ></v-select>
                  </v-hover>
                </v-col>
              </v-row>
            </div>
            <div v-else>
              <v-row>
                <v-col cols="auto" class="py-0 pr-0 mb-4">
                  <p class="fontsize-14 mb-1">Qty.</p>
                </v-col>
                <v-col cols="auto" class="py-0 pl-2 mb-4">
                  <p class="fontsize-14 text-black">{{ product.qty }}</p>
                </v-col>
              </v-row>
            </div>
          </v-col>
          <!---------------------------cart page--------------------------------------------->
          <v-col cols="8" class="py-0" v-show="cartProductPage">
            <v-row class="my-3">
              <v-col cols="12" sm="6" md="5" lg="6">
                <v-row>
                  <p
                    class=" mt-4
                      mb-6
                      fontsize-14
                      text-black
                      float-left
                      cursor-pointer"                    
                  >
                   {{ product.name }}
                  </p>
                </v-row>
                <v-row>
                  <p
                    class="fontsize-14  mb-6 text-uppercase"
                    v-show="cartProductPage"
                  >
                    Sku {{ product.sku }}
                  </p>
                </v-row>
                <v-row>
                  <p
                    class=" fontsize-14  mb-6 text-uppercase"
                    v-show="cartProductPage"
                  >
                    UPC {{ product.customAttributes.upc }}
                  </p>
                </v-row>
                <v-row>
                  <p class="fontsize-14">
                    ${{ priceFormatter(product.price) }}
                  </p>
                </v-row>
              </v-col>
              <v-col cols="12" sm="6" md="7" lg="6">
                <v-row align="center">
                  <v-col cols="8" sm="8" md="9" lg="7" class="pb-0">
                    <v-row
                      v-if="product.customAttributes.isPersonalize == 1"
                      align="center"
                      class="mt-n2"
                    >
                      <v-col cols="auto" class="pr-1 py-0">
                        <p class="fontsize-14 mb-0 pb-10">Qty.</p>
                      </v-col>
                      <v-col class="pl-0 pt-0">
                        <v-hover v-slot="{ isHovering, props }">
                         <v-select
                             :items="
                              qtyPriceOptions(
                                product.customAttributes.qtyPrice,
                                product.qty,
                                index
                              )
                            "
                            class="fontsize-16
                              line-height-21
                              ls-n009
                              font-weight-400 
                              cartproductlist-select-button 
                              "
      
                            variant="outlined"
                            density="compact"
                            v-bind="props"
                            attach
                            :class="isHovering ? 'text-primary' : 'text-black'"
                              v-model="selectedQty[index]"
                            @update:modelValue="
                              updateToCart(
                                product.name,
                                product.sku,
                                product.itemId,
                                index,
                                product.price,
                                product.personalizeDetails,
                                product.productOption,
                                product.customAttributes.letter,
                                product.productType,
                                product.customAttributes.isPersonalize,
                                product.customAttributes.builderVersion,
                                product.ccid,
                                product.parentSku
                              )
                            "
                           :model-value="selectedQty[index]"
                            ref="selectedCartQty4"
                            background-color="transparent"
                            append-inner-icon="mdi-plus"
                            item-value="qty"
                            item-title="qty"
                             item-children="qty"
                          ></v-select>
                        </v-hover>
                      </v-col>
                    </v-row>
                    <v-row align="center" class="mt-n2" v-else>
                      <v-col cols="auto" class="pr-1 py-0">
                        <p class="fontsize-14 mb-0 pb-10">Qty.</p>
                      </v-col>
                      <v-col class="pl-0 pt-0">
                        
                        <v-hover v-slot:default="{ isHovering, props }">
                          <v-select
                            :items="
                              numberOptions(
                                product.customAttributes.baMinSalesQty,
                                product.customAttributes.baQtyIncrements,
                                product.qty,
                                index
                              )
                            "
                            class="                               
                              fontsize-16
                              line-height-21
                              ls-n009
                              font-weight-400 
                              cartproductlist-select-button                         
                              "
      
                            variant="outlined"
                            density="compact"
                            v-bind="props"
                            attach
                            :class="isHovering ? 'text-primary' : 'text-black'"
                              v-model="selectedQty[index]"
                            @update:modelValue="
                              updateToCart(
                                product.name,
                                product.sku,
                                product.itemId,
                                index,
                                product.price,
                                product.personalizeDetails,
                                product.productOption,
                                product.customAttributes.letter,
                                product.productType,
                                product.customAttributes.isPersonalize,
                                product.customAttributes.builderVersion,
                                product.ccid,
                                product.parentSku 
                              )
                            "
                         :model-value="selectedQty[index]"
                            ref="selectedCartQty4"
                            background-color="transparent"
                            append-inner-icon="mdi-plus"
                          ></v-select>
                        </v-hover>
                      </v-col>
                    </v-row>
                  </v-col>
                  <v-col cols="4" sm="4" md="3" lg="5" class="pb-0">
                    <p class="fontsize-14 float-right mb-12">
                      ${{ priceFormatter(product.rowTotal) }}
                    </p>
                  </v-col>
                </v-row>
              </v-col>
              <!-- stock and Qty ---->
              <div v-if="product.stockDetails.manageStock">
                <div v-if="!product.stockDetails.isInStock">
                  <v-alert class="word-break" type="error" tile
                    >This product is out of stock.</v-alert
                  >
                </div>
                <div v-else>
                  <v-alert
                    class="word-break"
                    type="error"
                    tile
                    v-if="
                      product.stockDetails.qty < product.qty &&
                      product.stockDetails.backorders == 0
                    "
                    >The requested qty is not available.</v-alert
                  >
                  <v-alert
                    class="word-break"
                    type="warning"
                    tile
                    v-if="
                      product.stockDetails.qty < product.qty &&
                      product.stockDetails.backorders == 2
                    "
                    >We don't have as many quantity as you requested, but we'll
                    back order the remaining {{ product.qty }}.</v-alert
                  >
                </div>
              </div>
            </v-row>
          </v-col>
           
          <!------------------------------------------------------------------------------------->
          <v-row class="ma-0 pb-4 pt-5" v-show="checkOut">
            <v-col align="right">
               
              <a
                class=" fontsize-14
                  text-black text-uppercase
                  cartproductlist-action-link
                  cursor-pointer"
                 @click.stop="
                  remove(
                    product.name,
                    product.sku,
                    product.itemId,
                    product.parentSku,
                    product
                  )
                "
                >Remove</a
              >
            </v-col>
          </v-row>
        </v-row>
        <v-row>
          <div class="hr-line" v-show="cartProductPage && cartItems.length > 1"></div> 
        </v-row>
      </v-card>
      <v-col class="text-center mb-12" v-if="isGateModulePage">
        <router-link
          class="text-decoration-none cartproductlist-link"
          to
          @click.native="gateViewEditCart()"
          >View and edit cart</router-link
        >
      </v-col>
      <v-col
        v-else
        class="text-center mb-12"
        v-show="pageName() !== 'CartProducts' && pageName() !== 'CheckoutPage'"
      >
        <v-hover v-slot:default="{ hover }">
          <router-link
            :class="hover ? 'content-link-hover-color' : 'primary--text'"
            class="text-decoration-none cartproductlist-link"
            :to="{ name: 'CartProducts' }"
            @click.native="closeDrawer()"
            >View and edit cart</router-link
          >
        </v-hover>
      </v-col>
    </v-col>
    
     <ConfirmationDialog
      :key="confirmationDialog"
      :confirmationDialog="confirmationDialog"
      :confirmationDetails="confirmation"
       @actionRemove="removeProduct"
       v-if="confirmationDialog"
    ></ConfirmationDialog>

  </div>
</template>
<script>
//import { getAuthUser } from "@/services/auth";
/* eslint-disable */
const personlizeUrl = import.meta.env.VITE_APP_PERSONALIZE_URL;
const retailorId = import.meta.env.VITE_APP_RETAILOR_ID;
import {
  getLable,
  customAttributeValue,
  priceFormatter,
  checkPromotion,
 // googleAanalyticsEventRemoveCart
} from "@/services/util.service";
import ConfirmationDialog from "@/components/common/ConfirmationDialog.vue";
import { doFetchProductTags } from "@/services/product.service";
import { removeCookieByName} from "@/services/auth";

export default {
  name: "CartProductList",
  props: ["cartProductPage", "checkOut"],
  components: { ConfirmationDialog },
  data: () => ({
    priceFormatter: priceFormatter,
    isActive: true,
    selectedQty: [],
    selectedQtyPersonalize: "",
    retailorId: "08c43bbf-3735-4621-85f9-d71dc2cfb41b",
    itemNumber: "193C",
    quantity: "25",
    savFromKey: "Ub07GxNhS3yyoDfO",
    ccId: "766a5cef-6b51-4ab4-9f25-6446c4c8baeb",
    confirmationDialog: false,
    confirmation: {
      confirmationMessage: "",
    },
    blue: "primary",
    white: "white",
    dialog: false,
    productId: "",
    snackbar: {
      show: false,
      message: null,
      color: null,
      timeout: 0,
    },
    removeProdcutName: "",
    thumbnailAbsent: false,
    productDetails:''
  }),
  computed: {
    cartItems() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductList;
      } else {
        return this.$store.state.cartProduct.cartProductList;
      }
    },
    imageBasePathUrl() {
      return import.meta.env.VITE_APP_IMAGE_PATH_URL;
    },
    userAuth: function () {
      return this.$store.state.auth.userAuth;
    },
    
    /*productAttributes: function() {
      return this.$store.state.productOne.productAttributes;
    },*/
    productAttributes() {
      return this.$store.state.productList.attributeList.items;
    },
    isGateModulePage: function () {
      let pagePath = this.$route.path;
      let isGateModulePage = pagePath.includes("/gate/");
      if (isGateModulePage) return true;

      return false;
    },
    cartProductsProgress: function () {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductsProgress;
      } else {
        return this.$store.state.cartProduct.cartProductsProgress;
      }
    },
    fetchPriceInProgress: function () {
      return this.$store.state.productOne.fetchPriceInProgress;
    },
  },
  watch: {
    cartItems() {
     // this.calledListrakCartList();
    },
  },
  methods: {
  /*  calledListrakCartList() {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/setListrakCartList");
      }  
    },*/
    changeCheckoutFlag(flag) {
      this.$emit("stockFlag", flag);
    },
    checkThumbnails(personalizeDetails) {
      if (personalizeDetails) {
        let imgCount = 0;
        let i;
        let personalizeDetailsArray = JSON.parse(personalizeDetails);
        for (i = 0; i < personalizeDetailsArray.length; i++) {
          if (!personalizeDetailsArray[i].thumbnailUrl) imgCount++;
        }
        if (i == imgCount) return false;
        return true;
      }
      return false;
    },
    getAttribute(customAttributes, attributeCode) {
      if (this.productAttributes) {
        let newValue = this.productAttributes.filter((elements) => {
          return elements.attributeCode === attributeCode;
        });
        if (newValue.length > 0) {
          let labelValue = newValue[0].options.filter((elementNew) => {
            return elementNew.value === customAttributes;
          });
          if (labelValue.length > 0) {
            return labelValue[0].label;
          }
        }
      }
    },
    pageName() {
      return this.$route.name;
    },
    qtyPriceOptions(list, qty, index) {
      this.selectedQty[index] = Number(qty).toString();
      return JSON.parse(list);
    },
    numberOptions: function (baMinSalesQty, baQtyIncrements, qty, index) {
      if (baMinSalesQty && baQtyIncrements) {
        let minSalesQty = baMinSalesQty;
        let qtyIncrements = baQtyIncrements;
        minSalesQty = Number(minSalesQty) ? Number(minSalesQty) : 1;
        qtyIncrements = Number(qtyIncrements) ? Number(qtyIncrements) : 1;

        let nums = [];
        nums[0] = minSalesQty;
        if (qty) {
          this.selectedQty[index] = Number(qty);
        }
        for (let i = 1; i <= 98; i++) {
          minSalesQty = minSalesQty + qtyIncrements;
          nums[i] = minSalesQty;
        }
        if (nums.length > 0) return nums;
        else return "";

        // return minSalesQty + "   " + qtyIncrements;
      } else {
        return "";
      }
    },
    getCustomAttributeValue(customAttributes, attributeCode) {
      return customAttributeValue(customAttributes, attributeCode);
    },
    getCustomAttributeLable(customAttributes, attributeCode) {
      return getLable(customAttributes, attributeCode);
    },
    gateViewEditCart() {
      this.closeDrawer();
      window.open(`/cart-products`, "_self");
    },
    closeDrawer() {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/cartDrawer", false);
      } else {
        this.$store.dispatch("cartProduct/cartDrawer", false);
      }
    },
    goToProductDetails(customAttributes, productName, productType) {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/cartDrawer", false);
      } else {
        this.$store.dispatch("cartProduct/cartDrawer", false);
      }
      let pagePath = this.$route.path;
      let isGateModulePage = pagePath.includes("/gate/");

      if (isGateModulePage) {
        let productPath = customAttributes.urlKey
          ? customAttributes.urlKey
          : customAttributeValue(customAttributes, "url_key");
        window.open(`/${productPath}`, "_self");
      } else {
        if (productType == "configurable") {
          // let configuredSku = "CF13";
          this.$router
            .push({
              name: productName,
            })
            .catch((error) => {
              error;
            });
        } else {
          this.$router
            .push({
              name: productName,
            })
            .catch((error) => {
              error;
            });
        }
      }
    },
    remove(productName, sku, itemId, parentSku,product) {
     
      this.productDetails = product;
     
      this.productId = itemId;
      this.removeProdcutName = productName;
      (this.confirmationDialog = true),
        (this.confirmation = {
          confirmationMessage:
            "Are you sure you would like to remove this item from the shopping cart?",
        });
    },
    editProduct(
      productName,
      sku,
      itemId,
      index,
      isPersonalize,
      builderVersion,
      ccid,
      productType,
      parentSku
    ) {
      if (this.userAuth) {
        this.$store.dispatch("userCartProduct/cartDrawer", false);
      } else {
        this.$store.dispatch("cartProduct/cartDrawer", false);
      }
      if (isPersonalize == "1") {
        if (builderVersion == "2.0") {
          let itemCode = itemId ? itemId : "new";
          let url = `${personlizeUrl}/product/${sku}/select-part/${itemCode}/${this.cartItems[0].quoteId}/${this.selectedQty[index]}`;
          window.open(url, "_self");
        } else {
          this.$router
            .push({
              name: "CraneConnection",
              params: {
                retailorId: retailorId,
                quantity: this.selectedQty[index],
                itemNumber: sku,
                ccid: ccid,
                savItemId: itemId,
              },
            })
            .catch((error) => {
              error;
            });
        }
      } else {
        let pagePath = this.$route.path;
        let isGateModulePage = pagePath.includes("/gate/");
        if (isGateModulePage) {
          let productPath = customAttributes.urlKey
            ? customAttributes.urlKey
            : customAttributeValue(customAttributes, "url_key");
          window.open(
            `/${productPath}?qty=${this.selectedQty[index]}&itemId=${itemId}`,
            "_self"
          );
        } else {
          this.$emit("actionEditMessage");
          if (productType == "configurable") {
            this.$router
              .push({
                name: productName,
                query: {
                  qty: this.selectedQty[index],
                  itemId: itemId,
                },
              })
              .catch((error) => {
                error;
              });
          } else if (productType == "giftcard") {
            this.$router
              .push({
                name: productName,
                query: {
                  qty: this.selectedQty[index],
                  itemId: itemId,
                },
              })
              .catch((error) => {
                error;
              });
          } else {
            this.$router
              .push({
                name: productName,
                query: {
                  qty: this.selectedQty[index],
                  itemId: itemId,
                },
              })
              .catch((error) => {
                error;
              });
          }
        }
      }
    },

    async updateToCart(
      productName,
      sku,
      itemId,
      index,
      price,
      personalizeDetails,
      optionId,
      optionValue,
      productType,
      isPersonalize,
      builderVersion,
      ccid,
      parentSku
    ) {
      let vm = this;
      if (this.pageName() != "CheckoutPage") {
        if (this.userAuth) {
          if (isPersonalize == "1") {
            if (
              builderVersion == "2.0" &&
              itemId &&
              price &&
              personalizeDetails
            ) {
              const quantity = this.selectedQty[index];
              let updatedPriceData = await this.getPersonalizedPrice(
                personalizeDetails,
                quantity,
                sku
              );
              await this.updateToCartItem(
                null,
                sku,
                quantity,
                itemId,
                this.$route.name,
                updatedPriceData.subTotal,
                updatedPriceData.personalizeDetails,
                true
              );
            } else {
              try {
                const quantity = this.selectedQty[index];
                let response = await this.$store.dispatch(
                  "userCartProduct/updateToCConectionCart",
                  {
                    sku: sku,
                    qty: quantity,
                    ccid: ccid,
                  }
                );
                if (response) {
                  await this.updateToCartItem(
                    ccid,
                    sku,
                    quantity,
                    itemId,
                    this.$route.name,
                    null,
                    null,
                    true
                  );
                }
              } catch (error) {
                this.snackbar = {
                  message: error.message,
                  color: "error",
                  show: true,
                  timeout: 3000,
                };
                setTimeout(() => {
                  this.$emit("actionClose", this.snackbar);
                }, 3000);
              }
            }
          } else if (
            productType == "configurable" &&
            itemId &&
            optionId &&
            optionValue
          ) {
            let quantity = vm.selectedQty[index];
            try {
              await this.$store.dispatch(
                "userCartProduct/updateToConfiguredCart",
                {
                  ccid: null,
                  sku: parentSku,
                  qty: quantity,
                  itemId: itemId,
                  routeName: this.$route.name,
                  optionId: optionId.attributesInfo[0].optionId,
                  optionValue: optionValue,
                }
              );
              this.snackbar = {
                message: "Product Updated Successfully",
                color: "success",
                show: true,
                timeout: 3000,
              };
            } catch (error) {
              this.snackbar = {
                message: error.message,
                color: "error",
                show: true,
                timeout: 3000,
              };
            }
            setTimeout(() => {
              this.$emit("actionClose", this.snackbar);
            }, 3000);
            if (vm.$route.name == productName && vm.$route.query.qty)
              vm.$router.push({
                name: productName,
                query: { qty: quantity, itemId: itemId },
              });
          } else {
            let quantity = vm.selectedQty[index];
            await this.updateToCartItem(
              null,
              sku,
              quantity,
              itemId,
              this.$route.name,
              null,
              null,
              true
            );
            if (vm.$route.name == productName && vm.$route.query.qty)
              vm.$router.push({
                name: productName,
                query: { qty: quantity, itemId: itemId },
              });
          }
        } else {
          if (isPersonalize == "1") {
            if (
              builderVersion == "2.0" &&
              itemId &&
              price &&
              personalizeDetails
            ) {
              const quantity = this.selectedQty[index];
              let updatedPriceData = await this.getPersonalizedPrice(
                personalizeDetails,
                quantity,
                sku
              );
              await this.updateToCartItem(
                null,
                sku,
                quantity,
                itemId,
                this.$route.name,
                updatedPriceData.subTotal,
                updatedPriceData.personalizeDetails,
                false
              );
            } else {
              try {
                const quantity = this.selectedQty[index];
                let response = await this.$store.dispatch(
                  "cartProduct/updateToCConectionCart",
                  {
                    sku: sku,
                    qty: quantity,
                    ccid: ccid,
                  }
                );
                if (response) {
                  await this.updateToCartItem(
                    ccid,
                    sku,
                    quantity,
                    itemId,
                    this.$route.name,
                    null,
                    null,
                    false
                  );
                }
              } catch (err) {
                this.snackbar = {
                  message: err.message,
                  color: "error",
                  show: true,
                  timeout: 3000,
                };
                setTimeout(() => {
                  this.$emit("actionClose", this.snackbar);
                }, 3000);
              }
            }
          } else if (
            productType == "configurable" &&
            itemId &&
            optionId &&
            optionValue
          ) {
            let quantity = vm.selectedQty[index];
            try {
              await this.$store.dispatch("cartProduct/updateToConfiguredCart", {
                ccid: null,
                sku: parentSku,
                qty: quantity,
                itemId: itemId,
                routeName: this.$route.name,
                optionId: optionId.attributesInfo[0].optionId,
                optionValue: optionValue,
              });
              this.snackbar = {
                message: "Product Updated Successfully",
                color: "success",
                show: true,
                timeout: 3000,
              };
            } catch (error) {
              this.snackbar = {
                message: error.message,
                color: "error",
                show: true,
                timeout: 3000,
              };
            }
            setTimeout(() => {
              this.$emit("actionClose", this.snackbar);
            }, 3000);
            if (vm.$route.name == productName && vm.$route.query.qty)
              vm.$router.push({
                name: productName,
                query: { qty: quantity, itemId: itemId },
              });
          } else {
            let quantity = this.selectedQty[index];
            await this.updateToCartItem(
              null,
              sku,
              quantity,
              itemId,
              this.$route.name,
              null,
              null,
              false
            );
            if (this.$route.name == productName && this.$route.query.qty)
              this.$router.replace({
                name: productName,
                query: { qty: quantity, itemId: itemId },
              });
          }
        }
      }
    },
    async removeProduct(action) {
      //let token = getAuthUser();
      try {
        if (action.submit) {
          this.confirmationDialog = false;
          if (this.userAuth) {
            try {
              await this.$store.dispatch("userCartProduct/removeCartProduct", {
                productId: this.productId,
              });
             // googleAanalyticsEventRemoveCart('remove_from_cart',this.productDetails)
              removeCookieByName(this.productId);
              this.snackbar = {
                message: "Product Removed Successfully",
                color: "red",
                show: true,
                timeout: 3000,
              };
            } catch (error) {
              this.snackbar = {
                message: error.message,
                color: "error",
                show: true,
                timeout: 3000,
              };
            }
            this.$emit("actionClose", this.snackbar);
          } else {
            try {
              await this.$store.dispatch(
                "cartProduct/removeCartProduct",
                this.productId
              );
              //googleAanalyticsEventRemoveCart('remove_from_cart',this.productDetails)
              removeCookieByName(this.productId);
              this.snackbar = {
                message: "Product Removed Successfully",
                color: "red",
                show: true,
                timeout: 3000,
              };
            } catch (error) {
              this.snackbar = {
                message: error.message,
                color: "error",
                show: true,
                timeout: 3000,
              };
            }
            this.$emit("actionClose", this.snackbar);
          }
          //this.dialog = false;
          if (this.$route.name == this.removeProdcutName) {
            this.$router
              .push({
                name: this.removeProdcutName,
              })
              .catch((error) => {
                error;
              });
          }
        }
      } catch (error) {
        this.snackbar = {
          message: error.message,
          color: "error",
          show: true,
          timeout: 3000,
        };
      }
      this.confirmationDialog = false;
      this.removeProdcutName = "";
      this.confirmation = {
        confirmationMessage: "",
      };
      this.productId = "";
    },
     async getPersonalizedPrice(personalizeDetails, qty, sku) {
      try {
        let productSummaryDetails = [];
        productSummaryDetails = JSON.parse(personalizeDetails);
        let partPrice = null;
        let subTotal = 0;
        let imagelibProduct = await doFetchProductTags(sku);
        let productPartsObjects = [];
        this.isPromotionApplied = false;
        for (let i = 0; i < productSummaryDetails.length; i++) {
          let productPart = productSummaryDetails[i];
          if (productPart.partSelected) {
            productPartsObjects[i] = {};
            productPartsObjects[i].partName = productPart.name;
            productPartsObjects[i].processes = productPart.processes;
            productPartsObjects[i].linerObject = productPart.linerObject;
            productPart.orderObject.Details[0].Quantity = qty;
            productPart.orderObject.Details[0].Sublines.forEach((subline) => {
              subline.Quantity = qty;
            });
            qty;
          }
        }
        let response = await checkPromotion({
          sku: sku,
          quantity: qty,
          product: imagelibProduct ? imagelibProduct : {},
          productPartsObjects: productPartsObjects,
        });
        let priceAdjustmentType=null;
        let priceAdjustmentValue=null;
        if (response) {
          if (response.exclusiveRules.length !== response.exclusive.length)
            this.isPromotionApplied = false;
          else {
            if (response.appliedRules.length) {
              this.isPromotionApplied = true;
              let sortedPromotions = [];
              for (let i = 0; i < response.appliedRules.length; i++) {
                let promotion = response.appliedRules[i];
                if (promotion.price_adjustment == "fixed") {
                  sortedPromotions.unshift(promotion);
                } else {
                  sortedPromotions.push(promotion);
                }
              }
              //fixed is on top
              for (let r = 0; r < sortedPromotions.length; r++) {
                let sortedPromotion = sortedPromotions[r];
                if (sortedPromotion.price_adjustment == "fixed") {
                  subTotal = sortedPromotion.price_adjustment_value;
                } else if (sortedPromotion.price_adjustment == "bump_amount") {
                  subTotal += sortedPromotion.price_adjustment_value;
                }
                else if (sortedPromotion.price_adjustment == "discount_percentage") {                  
                priceAdjustmentType="discount_percentage";
                priceAdjustmentValue=sortedPromotion.price_adjustment_value;
              }
              }
              
              if (subTotal == 0&&!priceAdjustmentType) 
              this.isPromotionApplied = false;
              // if (this.isPromotionApplied)
              //   this.$snotify.success(`Promotion is applied successfully`, {
              //     position: "rightTop",
              //     showProgressBar: false,
              //   });
            } else {
              this.isPromotionApplied = false;
            }
          }
        }
       // if (!this.isPromotionApplied) {
          let pricerSubTotal = 0;
          for (let i = 0; i < productSummaryDetails.length; i++) {
            let part = productSummaryDetails[i];
            if (part.partSelected) {
              part.orderObject.Details[0].Quantity = qty;
              part.orderObject.Details[0].Sublines.forEach((subline) => {
                subline.Quantity = qty;
              });

              try {
                partPrice = await this.$store.dispatch(
                  "productOne/fetchPartPrice",
                  part.orderObject
                );
                part.partPrice =
                  partPrice.PriceResult.Total *
                  (partPrice.PriceResult.RetailMultiplier / 100);
                pricerSubTotal += part.partPrice;
              } catch (error) {
                this.$snotify.error("Error while fetching price", {
                  position: "rightTop",
                  showProgressBar: false,
                });
              }
            }
          }
       // }

      if (!this.isPromotionApplied) subTotal = pricerSubTotal;
        else if(priceAdjustmentType&&priceAdjustmentType=="discount_percentage"){
        if(Number(priceAdjustmentValue)){
        subTotal=pricerSubTotal*(1-(Number(priceAdjustmentValue)/100))
        // this.subTotal=subTotal
        }
      }
    
        return {
          subTotal: subTotal,
          personalizeDetails: JSON.stringify(productSummaryDetails),
        };
      } catch (error) {
        console.log("error", error);
      }
    },
    async updateToCartItem(
      ccid,
      sku,
      qty,
      itemId,
      routeName,
      price,
      personalizeDetails,
      isUser
    ) {
      try {
        if (isUser) {
          await this.$store.dispatch("userCartProduct/updateToCart", {
            ccid: ccid,
            sku: sku,
            qty: qty,
            itemId: itemId,
            routeName: routeName,
            price: price,
            personalizeDetails: personalizeDetails,
          });
        } else {
          await this.$store.dispatch("cartProduct/updateToCart", {
            ccid: ccid,
            sku: sku,
            qty: qty,
            itemId: itemId,
            routeName: routeName,
            price: price,
            personalizeDetails: personalizeDetails,
          });
        }
        this.snackbar = {
          message: "Product Updated Successfully",
          color: "success",
          show: true,
          timeout: 3000,
        };
      } catch (error) {
        this.snackbar = {
          message: error.message,
          color: "error",
          show: true,
          timeout: 3000,
        };
      }
      this.$emit("actionClose", this.snackbar);
    },
  },
  created() {
    //this.$store.dispatch("productOne/fetchproductDetails", this.sku);
  },
};
</script>
<style lang="scss">
.cartproductlist-select-button.v-text-field.v-text-field--enclosed:not(.v-text-field--rounded)
  > .v-input__control
  > .v-input__slot {
  padding: 0 8px !important;
  min-height: 30px !important;
  max-width: 80px !important;
}
.cartproductlist-select-button .v-input__append-inner {
  padding-bottom: 3px !important;
}
.cartproductlist-select-button .v-select__selection.v-select__selection--comma {
  margin: 0px !important;
}
.cartproductlist-select-button:hover
  .v-select__selection.v-select__selection--comma {
  color: #2850da !important;
}
.cartproductlist-select-button:hover
  .v-input__append-inner
  .v-input__icon
  .v-icon {
  color: #2850da !important;
}
.cartproductlist-expansion .v-expansion-panel-content__wrap {
  padding: 0 0px 0px !important;
}
</style>
<style src="./CartProductList.scss" lang="scss" scoped/>