<template>
  <div class="white h-100">
    <v-overlay :value="paymentInProgress" :opacity="0.8">
      <v-container>
        <v-row>
          <v-col cols="12" class="d-flex justify-center align-center">
            <div class="h3 white--text mt-10">
              Do not refresh or click back. Your payment is currently being
              processed.
            </div>
          </v-col>
          <v-col cols="12" class="d-flex justify-center align-center">
            <v-progress-circular
              indeterminate
              size="80"
              color="white"
              align="center"
              justify="center"
            ></v-progress-circular>
          </v-col>
        </v-row>
      </v-container>
    </v-overlay>
     
    <v-container
      v-if="cartProductsProgress || shippingInformationsInProgress"
      class="text-center"
    >
      <v-progress-circular
        class="mt-12"
        :size="80"
        color="primary"
        indeterminate
      ></v-progress-circular>
    </v-container>
    <v-container v-else>
      <v-row
        align="center"
        justify="center"
        class="py-5"
        no-gutters
        v-if="cartProductsItem.length && ( userAuth)"
      >
        <v-col cols="12">
          <v-tabs hide-slider fixed-tabs v-model="tabs" :height="35">
            <v-tab
              class="
                productpage-tab-slider
                text-uppercase
                fontsize-14
                regular-font
                ls-n008
                px-0
              "
              :href="`#shippingTab`"
              @click="changedToShippTab()"
              v-show="showShippingTab"
              >Shipping</v-tab
            >
            <v-tab
              class="
                productpage-tab-slider
                text-uppercase
                fontsize-14
                regular-font
                ls-n008
                px-0
              "
              :href="`#reviewTab`"
              :disabled="!valid"
              :class="giftCardProduct ? 'checkout-tabs' : ''"
              v-show="showReviewTab"
              >Review & Payments</v-tab
            >
          </v-tabs>
          <v-tabs-items touchless v-model="tabs">
            <v-tab-item :value="`shippingTab`" :disabled="valid">
              <v-row
                v-if="isMobileDevice && estimatedShippingMethods.length > 0"
                class="pt-3"
              >
                <v-col cols="12">
                  <v-alert text>
                    <p>
                      <strong
                        >Estimated Total : ${{
                          priceFormatter(
                            estimatedShipping.amount +
                              cartProductTotalAmt.grandTotal
                          )
                        }}</strong
                      >
                    </p>
                  </v-alert>
                </v-col>
              </v-row>
              <v-row no-gutters class="pt-3 pt-sm-6">
                <v-col cols="12" sm="7" md="8" class="pr-sm-3">
                  <v-row no-gutters>
                    <v-col
                      cols="12"
                      sm="8"
                      class="pt-sm-6"
                      v-if="!this.userAuth"
                    >
                      <p class="h3 mt-4">
                        <span class="primary--text">Checkout Method</span>
                      </p>
                      <GuestShippingAddressForm
                        @actionValid="checkGuestFormValid"
                        :hideEmail="hideEmailField"
                        @verifyAddress="verifyAddress"
                        ref="guestAddressForm"
                      />
                    </v-col>

                    <v-col cols="12" class="pt-sm-6" v-else>
                      <p class="h3 mb-2">
                        <span class="primary--text">Checkout Method</span>
                      </p>
                      <v-divider class="primary"></v-divider>
                      <div v-if="basicInfo.addresses">
                        <div v-if="basicInfo.addresses.length > 0">
                          <v-row class="mt-2 mx-1">
                            <v-col
                              cols="12"
                              sm="6"
                              md="4"
                              class="my-2 py-0 h-100"
                              v-for="(address, index) in addressesList"
                              :key="index"
                              :class="
                                userSelectedAddressIndex == index && index == 0
                                  ? 'primary-all-side-border'
                                  : userSelectedAddressIndex == index &&
                                    index > 0 &&
                                    !isMobileDevice
                                  ? 'primary-tbr-side-border'
                                  : isMobileDevice &&
                                    userSelectedAddressIndex == index
                                  ? 'primary-all-side-border'
                                  : isMobileDevice
                                  ? ''
                                  : 'primary-right-side-border'
                              "
                            >
                              <v-container fluid fill-height class="pa-0">
                                <!-- <v-row no-gutters class="d-flex"> -->
                                <v-col
                                  cols="10"
                                  sm="12"
                                  class="pa-0 mb-auto align-self-start"
                                >
                                  <BillingAddressComponent
                                    :address="address"
                                    class="pa-3"
                                  />
                                  <v-btn
                                    class="
                                      primary
                                      ma-3
                                      d-none d-sm-inline-block
                                    "
                                    tile
                                    depressed
                                    v-if="lastAddedAddressBookIndex == index"
                                    @click="editLocalAddress(address, true)"
                                    >Edit</v-btn
                                  >
                                </v-col>
                                <v-col
                                  cols="2"
                                  class="
                                    pa-0
                                    d-sm-none
                                    text-center
                                    align-self-start
                                    h-100
                                  "
                                >
                                  <v-btn
                                    icon
                                    depressed
                                    v-if="lastAddedAddressBookIndex == index"
                                    @click="editLocalAddress(address, true)"
                                  >
                                    <v-icon>mdi mdi-pencil</v-icon>
                                  </v-btn>
                                </v-col>
                                <v-col class="align-self-end pa-0">
                                  <v-btn
                                    v-if="userSelectedAddressIndex != index"
                                    class="primary mx-sm-3 float-right"
                                    :block="isMobileDevice"
                                    @click="shipHereAddress(address, index)"
                                    tile
                                    depressed
                                    >Ship Here</v-btn
                                  >
                                </v-col>
                                <!-- </v-row> -->
                              </v-container>
                            </v-col>
                            <!-- address not saved in Address book -->
                            <v-col
                              cols="12"
                              sm="6"
                              md="4"
                              class="py-0 h-100"
                              v-if="userLocalAddress"
                              :class="
                                userSelectedAddressIndex != -1
                                  ? 'primary-right-side-border'
                                  : 'primary-all-side-border pa-0'
                              "
                            >
                              <v-container fluid fill-height class="pa-0">
                                <!-- <v-row no-gutters align="end" justify="center"> -->
                                <v-col cols="10" sm="12" class="pa-0">
                                  <BillingAddressComponent
                                    :address="userLocalAddress"
                                    class="pa-3 mb-auto"
                                  />
                                  <v-btn
                                    class="
                                      primary
                                      ma-3
                                      d-none d-sm-inline-block
                                    "
                                    tile
                                    depressed
                                    @click="
                                      editLocalAddress(userLocalAddress, false)
                                    "
                                    >Edit</v-btn
                                  >
                                </v-col>
                                <v-col
                                  cols="2"
                                  class="pa-0 d-sm-none text-center h-100"
                                >
                                  <v-btn
                                    icon
                                    depressed
                                    @click="
                                      editLocalAddress(userLocalAddress, false)
                                    "
                                  >
                                    <v-icon>mdi mdi-pencil</v-icon>
                                  </v-btn>
                                </v-col>
                                <v-col class="pa-0">
                                  <v-btn
                                    v-if="userSelectedAddressIndex != -1"
                                    class="primary mx-sm-3 float-right"
                                    :block="isMobileDevice"
                                    tile
                                    depressed
                                    @click="
                                      shipHereAddress(userLocalAddress, -1)
                                    "
                                    >Ship Here</v-btn
                                  >
                                </v-col>
                              </v-container>
                              <!-- </v-row> -->
                            </v-col>
                          </v-row>
                           
                        </div>
                        <div v-else>
                          <v-row>
                            <v-col cols="12" sm="8">
                              <p class="h3 mt-4">Shipping Address</p>
                              <ShippingAddressFormComponent
                                @actionValid="checkFormValid"
                                :hideAndShowFields="hideAndShowFields"
                                @verifyAddress="verifyAddress"
                                ref="userAddressForm"
                              />
                            </v-col>
                          </v-row>
                        </div>
                      </div>
                      <div v-else class="text-center pt-3">
                        <v-progress-circular
                          :size="40"
                          color="primary"
                          indeterminate
                        ></v-progress-circular>
                      </div>
                    </v-col>
                    <v-col cols="12" class="mt-3" v-if="!addressContainPOBox">
                      <div>
                        <!--<p class="h3 mb-1">
                          <span class="primary--text">Verify Your Address</span>
                        </p>
                        <v-col class="pa-0" v-if="geoCodedAddress">
                          <VerifyAddressComponent
                            :geoCodedAddress="geoCodedAddress"
                            :geoCodedAddressFlag="geoCodedAddressFlag"
                            :validAddresses="validAddresses"
                          />
                        </v-col>
                        <v-col
                          class="pa-0 text-center"
                          v-else-if="addressInProgress"
                        >
                          <v-progress-circular
                            :size="40"
                            color="primary"
                            indeterminate
                          ></v-progress-circular>
                        </v-col>
                        <v-col class="pa-0" v-else>
                          <v-alert type="error" class="my-2" text
                            >No Address is available</v-alert
                          >
                        </v-col>-->
                        <p class="h3 mb-0">
                          <span class="primary--text">Shipping Methods</span>
                        </p>
                        <v-row no-gutters>
                          <v-col
                            cols="12"
                            v-if="inProgress"
                            class="text-center"
                          >
                            <v-progress-circular
                              :size="40"
                              color="primary"
                              indeterminate
                            ></v-progress-circular>
                          </v-col>
                          <v-col
                            cols="12"
                            v-else-if="estimatedShippingMethods.length > 0"
                          >
                            <v-radio-group
                              mandatory
                              v-model="estimatedShipping"
                            >
                              <div
                                v-for="(
                                  method, index
                                ) in estimatedShippingMethods"
                                :key="index"
                              >
                                <v-row no-gutters class="mt-0">
                                  <v-col cols="4" sm="4">
                                    <v-radio
                                      :label="method.carrierTitle"
                                      :value="method"
                                      class="black--text"
                                    ></v-radio>
                                  </v-col>
                                  <v-col cols="4" sm="6">{{
                                    method.methodTitle
                                  }}</v-col>
                                  <v-col cols="4" sm="2" class="text-right"
                                    > {{ priceFormatter(method.amount) ==0 ? 'TBD' : '$' + priceFormatter(method.amount)}}</v-col
                                  >
                                  
                                </v-row>
                              </div>
                            </v-radio-group>
                          </v-col>
                          <v-col cols="12" v-else>
                            <v-alert type="error" class="my-2" text
                              >No shipping methods is available</v-alert
                            >
                          </v-col>
                        </v-row>
                        <v-row no-gutters>
                          <v-col
                            cols="12"
                            class="d-flex justify-center justify-sm-end"
                          >
                            <router-link
                              to="#"
                              class="body ls-n009 text-decoration-none"
                            >
                              <v-btn
                                class="text-uppercase"
                                color="primary"
                                @click="next()"
                                large
                                tile
                                block
                                depressed
                                v-if="estimatedShippingMethods.length > 0"
                                >NEXT</v-btn
                              >
                            </router-link>
                          </v-col>
                        </v-row>
                      </div>
                    </v-col>
                    <v-col cols="12" class="pt-3" v-else>
                      <v-alert type="error" class="my-2" text
                        >Shipping to PO Boxes is not permitted. Please use a
                        different shipping address</v-alert
                      >
                    </v-col>
                  </v-row>
                  <v-divider class="my-3 primary"></v-divider>
                </v-col>
                <v-col
                  cols="12"
                  sm="5"
                  md="4"
                  class="d-none d-sm-block pl-3 pt-6"
                >
                  <p class="h3 mb-2">
                    <span class="primary--text">Order Summary</span>
                  </p>
                  <v-divider class="primary"></v-divider>
                  <v-col
                    align="center"
                    justify="center"
                    v-if="cartProductsProgress"
                  >
                    <v-progress-circular
                      :size="60"
                      color="primary"
                      indeterminate
                    ></v-progress-circular>
                  </v-col>
                  <v-expansion-panels
                    accordion
                    light
                    flat
                    multiple
                    v-model="cartItemPanel"
                    v-else
                  >
                    <v-expansion-panel class="transparent-background">
                      <v-expansion-panel-header class="pr-4"
                        >{{ cartProductsItem.length }} Items In
                        cart</v-expansion-panel-header
                      >
                      <v-expansion-panel-content class="checkout-expansion">
                        <div class="mb-5 checkout-expansion-maxheight">
                          <CartProductList :checkOut="chekoutFlag" />
                        </div>
                      </v-expansion-panel-content>
                    </v-expansion-panel>
                  </v-expansion-panels>
                  <v-divider class="primary"></v-divider>
                </v-col>
              </v-row>
            </v-tab-item>
            <v-tab-item :value="`reviewTab`">
              <v-row
                no-gutters
                class="pt-sm-6"
                v-if="shippingInformations || giftCardProduct"
              >
                <v-col cols="12" sm="7" md="8" class="px-3 pr-sm-3">
                  <v-row>
                    <v-col cols="12" v-if="shippingInformations">
                      <v-radio-group
                        :mandatory="false"
                        v-model="paymentMethod"
                        v-if="shippingInformations.totals.grandTotal !== 0"
                      >
                        <v-radio
                          :label="purchaseOrderPayment.title"
                          :value="purchaseOrderPayment.code"
                          class="black--text"
                        ></v-radio>
                        <div v-if="paymentMethod === 'purchaseorder'">
                          <v-checkbox
                            label="My billing and shipping address are the same"
                            v-model="sameAddress"
                            @change="resetFields()"
                            dense
                            :readonly="readOnlyCheckBox"
                            hide-details
                          ></v-checkbox>
                         <div v-if="sameAddress">
                          <v-row >
                            <v-col cols="12" class="pl-sm-10">
                              <BillingAddressComponent :address="address" />
                              <v-btn
                                class="primary my-3"
                                large
                                v-if="editBillingButton"
                                @click="editBillBook()"
                                depressed
                                tile
                                >Edit</v-btn
                              >
                            </v-col>
                          </v-row> <v-form ref="poNumberForm" v-model="valid" :lazy-validation="lazy">
                          <v-row  >
                            <v-col cols="12" align="right">
                               <v-text-field
                               v-model="poNumber"
                               type="text"
                                    dense
                                    placeholder="Purchase Order Number"
                                    outlined
                                    :rules="textRules"
                               ></v-text-field>
                            </v-col>

                            <v-col cols="12" align="right">
                              <v-btn
                                class="primary mx-3 text-uppercase"
                                @click="placeOrderFree($event)"
                                tile
                                depressed
                                >Place Order</v-btn
                              >
                            </v-col>

                            
                          </v-row>
                          </v-form>
                        </div>   
                          <v-row v-else>
                            <v-col cols="12" sm="8" v-if="this.userAuth">
                              <v-row v-if="addressLength > 0">
                                <v-col cols="12">
                                  <v-select
                                    v-model="selectedBillingAddress"
                                    dense
                                    :items="billingAddressList"
                                    outlined
                                    return-object
                                    class="billing-address-select"
                                    @change="changeBillingAddress()"
                                    item-value="id"
                                  >
                                    <template v-slot:selection="data">
                                      <div v-if="data.item.value">
                                        <span class>New Address</span>
                                      </div>
                                      <div
                                        class="
                                          d-inline-block
                                          text-truncate
                                          pt-sm-0
                                        "
                                        v-else
                                      >
                                        <span class
                                          >{{ data.item.firstname }}
                                          {{ data.item.lastname }}</span
                                        >
                                        <span
                                          class="body pl-1"
                                          v-if="data.item.streetNoOne"
                                          >{{ data.item.streetNoOne }},
                                          {{ data.item.streetNoTwo }}</span
                                        >
                                        <span class="body pl-1" v-else
                                          >{{ data.item.street[0] }} ,{{
                                            data.item.street[1]
                                          }}</span
                                        >
                                        <span class="pl-1"
                                          >{{ data.item.city }}
                                          {{ data.item.postcode }}</span
                                        >
                                      </div>
                                    </template>
                                    <template v-slot:item="data">
                                      <v-list-item-content>
                                        <v-list-item-title
                                          v-if="data.item.value"
                                        >
                                          <span class="ml-2">New Address</span>
                                        </v-list-item-title>
                                        <v-list-item-title v-else>
                                          <span class="ml-2"
                                            >{{ data.item.firstname }}
                                            {{ data.item.lastname }},</span
                                          >
                                          <span
                                            class="body"
                                            v-if="data.item.streetNoOne"
                                            >{{ data.item.streetNoOne }},
                                            {{ data.item.streetNoTwo }}</span
                                          >
                                          <span class="body" v-else
                                            >{{ data.item.street[0] }} ,{{
                                              data.item.street[1]
                                            }}</span
                                          >
                                          <span class
                                            >{{ data.item.city }},
                                            {{ data.item.postcode }}</span
                                          >
                                        </v-list-item-title>
                                      </v-list-item-content>
                                    </template>
                                  </v-select>
                                </v-col>
                                <v-col
                                  cols="12"
                                  class="d-flex justify-end pa-0"
                                  v-if="!showNewBillingForm"
                                >
                                  <v-btn
                                    class="primary ma-3 text-uppercase"
                                    @click="cancelBillingAddress"
                                    >Cancel</v-btn
                                  >
                                  <v-btn
                                    class="success ma-3 text-uppercase"
                                    @click="updateBillingAddress"
                                    >Update</v-btn
                                  >
                                </v-col>
                              </v-row>
                              <v-row v-if="showNewBillingForm">
                                <v-col cols="12">
                                  <ShippingAddressFormComponent
                                    @actionValid="checkFormValid"
                                    :hideAndShowFields="hideAndShowFields"
                                    @verifyAddress="verifyAddress"
                                    ref="billingForm"
                                  />
                                </v-col>
                                <v-col cols="12" class="py-0">
                                  <v-checkbox
                                    label="Save in Address Book"
                                    v-model="saveInBillingAddressBook"
                                    class="mt-0"
                                    dense
                                    hide-details
                                  ></v-checkbox>
                                </v-col>
                              </v-row>
                            </v-col>
                            <v-col cols="12" sm="8" v-else>
                              <GuestShippingAddressForm
                                @actionValid="checkGuestFormValid"
                                :hideHeader="true"
                                :hideEmail="hideEmailField"
                                @verifyAddress="verifyAddress"
                                ref="addressForm"
                              />
                            </v-col>
                            <v-col
                              cols="12"
                              sm="8"
                              class="d-flex justify-end pa-0"
                              v-if="showNewBillingForm"
                            >
                              <v-btn
                                class="primary ma-3 text-uppercase"
                                @click="cancelBillingAddress"
                                >Cancel</v-btn
                              >
                              <v-btn
                                class="success ma-3 text-uppercase"
                                @click="newBillingAddress"
                                >Update</v-btn
                              >
                            </v-col>
                          </v-row>
                        <!--  <v-row>
                            <CardPayment
                              @submitCardPayment="submitCardPayment"
                            />-->
                            <!-- <v-col cols="12" sm="6">
                              <v-braintree
                                :authorization="braintreeAuthKey"
                                :vaultManager="true"
                                @success="onPaymentSuccess"
                                @error="onPaymentError"
                                @load="onGatewayLoad"
                                @loadFail="onGatewayLoadFail"
                            >
                              <template v-slot:button="slotProps">
                                <v-btn @click="slotProps.submit" color="success">Place Order</v-btn>
                              </template>
                            </v-braintree>
                            </v-col>-->
                          <!--</v-row>-->
                        </div>
                        <!-- <v-divider class="my-3"></v-divider>
                      <v-radio
                        :label="shippingInformations.paymentMethods[0].title"
                        :value="shippingInformations.paymentMethods[0].code"
                        class="black--text"
                      ></v-radio>
                      <div v-if="paymentMethod === 'braintree_paypal'">
                         
                        <v-col cols="12" sm="12" class="pr-10 pt-10">
                          <v-btn
                            id="paypal-button"
                            tile
                            class="float-right text-uppercase"
                            color="primary"
                          >Continue To Paypal</v-btn>
                        </v-col>
                        </div>-->
                      </v-radio-group>
                      
                      <v-divider></v-divider>
                    </v-col>
                    <v-col cols="12" v-else>
                      <v-col cols="8" class="pl-1" v-if="!userAuth">
                        <v-form ref="emailForm" v-model="validEmail">
                          <v-col class="px-0 py-0 mb-n3">
                            <v-text-field
                              label="Email Address"
                              @input="checkEmail()"
                              @change="sendEmailId()"
                              ref="email"
                              name="email"
                              v-model="emailId"
                              :rules="emailRules"
                              outlined
                              dense
                            ></v-text-field>
                            <!-- <v-text-field
                v-show="passwordFields"
                v-model="password"
                label="Password"
                ref="password"
                name="password"
                type="password"
                outlined
                dense
                :rules="passwordFields? passwordRules:[]"
                            ></v-text-field>-->
                          </v-col>
                          <!-- <span v-show="passwordFields">You already have an account with us. Sign in or continue as guest.</span>
           <v-row  justify="center" v-if="emailCheckInProgress">
            <v-progress-circular
              :size="60"
              color="primary"
              indeterminate
              v-if="emailCheckInProgress"
            ></v-progress-circular>
          </v-row>
          <v-row class="mt-3" v-show="passwordFields" no-gutters>
            <v-col cols="4">
              <v-btn class="primary" depressed block large @click="signIn()">SIGN IN</v-btn>
            </v-col>
                          </v-row>-->
                          <span v-show="!passwordFields"
                            >You can create an account after checkout.</span
                          >
                        </v-form>
                      </v-col>
                      
                      <v-divider></v-divider>
                    </v-col>
                   <!-- <v-col cols="12" class="py-0">
                      <v-expansion-panels
                        accordion
                        light
                        flat
                        v-model="panelCode"
                      >
                        <v-expansion-panel class="transparent-background">
                          <v-expansion-panel-header active class="px-0 body"
                            >Apply Discount Code</v-expansion-panel-header
                          >
                          <v-expansion-panel-content
                            v-if="inProgressDiscountCode"
                          >
                            <v-progress-circular
                              :size="40"
                              color="primary"
                              indeterminate
                            ></v-progress-circular>
                          </v-expansion-panel-content>

                          <v-expansion-panel-content class="px-0" v-else>
                            <v-form
                              ref="discountCodeForm"
                              v-model="validDiscountCode"
                              :lazy-validation="lazy"
                            >
                              <v-row>
                                <v-col cols="7" sm="6" md="6">
                                  <v-text-field
                                    type="text"
                                    dense
                                    placeholder="Enter Discount Code"
                                    v-model="discountTextCode"
                                    outlined
                                    @blur="resetValidation"
                                    :rules="textRules"
                                  ></v-text-field>
                                </v-col>
                                <v-col cols="5" sm="6" md="6">
                                  <v-btn
                                    v-if="!discountCode"
                                    class="
                                      primary
                                      text-uppercase
                                      checkoutpage-button-height
                                    "
                                    @click="applyDiscountCode"
                                    large
                                    dense
                                    tile
                                    depressed
                                    >APPLY</v-btn
                                  >
                                  <v-btn
                                    v-if="discountCode"
                                    class="
                                      error
                                      text-uppercase
                                      checkoutpage-button-height
                                    "
                                    @click="removeDiscountCode"
                                    large
                                    dense
                                    tile
                                    depressed
                                    >CANCEL</v-btn
                                  >
                                </v-col>
                              </v-row>
                            </v-form>
                          </v-expansion-panel-content>
                        </v-expansion-panel>
                      </v-expansion-panels>
                    </v-col>-->
                    
                     
                  </v-row>
                </v-col>
                <v-col cols="12" sm="5" md="4" class="pl-3 d-none d-sm-block">
                  <p class="h3 mb-2">Order Summary</p>
                  <hr />
                  <v-expansion-panels accordion light flat>
                    <v-expansion-panel class="transparent-background">
                      <v-expansion-panel-header class="pr-4"
                        >{{ cartProductsItem.length }} Items In
                        cart</v-expansion-panel-header
                      >
                      <v-expansion-panel-content class="checkout-expansion">
                        <div class="mb-5 checkout-expansion-maxheight">
                          <CartProductList
                            :checkOut="chekoutFlag"
                            :cartItems="cartProductsItem"
                          />
                        </div>
                      </v-expansion-panel-content>
                    </v-expansion-panel>
                  </v-expansion-panels>
                  <hr />
                  <div v-if="giftCardProduct">
                    <v-row no-gutters>
                      <v-col
                        cols="12"
                        class="my-3 d-flex justify-space-between"
                      >
                        <h4>Cart Subtotal</h4>
                        <span
                          >$
                          {{
                            priceFormatter(
                              this.cartProductTotalAmt.baseSubtotal
                            )
                          }}</span
                        >
                      </v-col>
                      <v-col cols="12" class="d-flex justify-space-between">
                        <h3>Estimated Total</h3>
                        <span
                          >$
                          {{
                            priceFormatter(this.cartProductTotalAmt.grandTotal)
                          }}</span
                        >
                      </v-col>
                    </v-row>
                  </div>
                  <div v-else>
                    <div v-if="shippingInformations.totals.grandTotal !== 0">
                      <v-row no-gutters v-if="inProgressDiscountCode">
                        <v-progress-circular
                          :size="40"
                          color="primary"
                          indeterminate
                        ></v-progress-circular>
                      </v-row>
                      <v-row no-gutters v-else>
                        <v-col
                          cols="12"
                          class="my-3 d-flex justify-space-between"
                        >
                          <h4>Cart Subtotal</h4>
                          <span
                            >$
                            {{
                              priceFormatter(
                                shippingInformations.totals.subtotal
                              )
                            }}</span
                          >
                        </v-col>
                        <v-col
                          cols="12"
                          class="my-3 d-flex justify-space-between"
                          v-if="shippingInformations.totals.couponCode"
                        >
                          <span
                            >Discount ({{
                              shippingInformations.totals.couponCode
                            }})
                            {{ shippingInformations.totals.couponCode }}</span
                          >
                          <span
                            >-${{
                              priceFormatter(
                                shippingInformations.totals.baseDiscountAmount
                                  .toString()
                                  .substring(1)
                              )
                            }}</span
                          >
                        </v-col>
                        <v-col cols="12" class="d-flex justify-space-between">
                          <span>Shipping</span>
                          <span
                            >$
                            {{
                              priceFormatter(
                                shippingInformations.totals.shippingAmount
                              )
                            }}</span
                          >
                        </v-col>
                        <v-col
                          cols="12"
                          class="d-flex justify-space-between"
                          v-for="(types, index) in shippingInformations.totals
                            .totalSegments"
                          :key="index"
                        >
                          <span v-if="types.code === 'shipping'">{{
                            types.title
                          }}</span>
                        </v-col>
                        <v-col cols="12" class="d-flex justify-space-between">
                          <span>Estimated Tax</span>
                          <span
                            >$
                            {{
                              priceFormatter(
                                shippingInformations.totals.taxAmount
                              )
                            }}</span
                          >
                        </v-col>
                        
                        <v-col cols="12" class="d-flex justify-space-between">
                          <h3>Estimated Total</h3>
                          <span
                            >$
                            {{
                              priceFormatter(
                                shippingInformations.totals.baseGrandTotal
                              )
                            }}</span
                          >
                        </v-col>
                      </v-row>

                      <v-row class="mt-4">
                        <v-col class="d-flex justify-space-between pb-0">
                          <span class="display-1">Ship To:</span>
                          <v-btn
                            icon
                            @click="(tabs = 'shippingTab'), (valid = false)"
                          >
                            <v-icon>mdi mdi-pencil</v-icon>
                          </v-btn>
                        </v-col>
                        <v-col cols="12">
                          <v-divider></v-divider>
                        </v-col>
                        <v-col
                          cols="12"
                          v-if="
                            shippingInformations &&
                            shippingInformations.extensionAttributes
                          "
                        >
                          <p class="mb-2 body">
                            {{
                              shippingInformations.extensionAttributes
                                .originalAddress.firstname
                            }}
                            {{
                              shippingInformations.extensionAttributes
                                .originalAddress.lastname
                            }}
                          </p>
                          <p class="mb-2 body">
                            {{
                              shippingInformations.extensionAttributes.originalAddress.street.toString()
                            }}
                          </p>
                          <p class="mb-2 body">
                            {{
                              shippingInformations.extensionAttributes
                                .originalAddress.city
                            }},
                            <span
                              v-if="
                                shippingInformations.extensionAttributes
                                  .originalAddress.region
                              "
                              >{{
                                shippingInformations.extensionAttributes
                                  .originalAddress.region
                              }}</span
                            >
                            {{
                              shippingInformations.extensionAttributes
                                .originalAddress.postcode
                            }}
                          </p>
                          <p class="mb-2 body">
                            <span
                              v-if="
                                shippingInformations.extensionAttributes
                                  .originalAddress.countryId
                              "
                              >{{
                                shippingInformations.extensionAttributes
                                  .originalAddress.countryId
                              }}</span
                            >
                          </p>
                        </v-col>
                      </v-row>
                      <v-row class="mt-4">
                        <v-col class="d-flex justify-space-between pb-0">
                          <span class="display-1">Shipping Method:</span>
                          <v-btn
                            icon
                            @click="(tabs = 'shippingTab'), (valid = false)"
                          >
                            <v-icon>mdi mdi-pencil</v-icon>
                          </v-btn>
                        </v-col>
                        <v-col cols="12">
                          <v-divider></v-divider>
                        </v-col>
                        <div
                          v-for="(types, index) in shippingInformations.totals
                            .totalSegments"
                          :key="index"
                        >
                          <v-col
                            cols="12"
                            class="pb-0"
                            v-if="types.code === 'shipping'"
                            >{{ types.title }}</v-col
                          >
                        </div>
                      </v-row>
                    </div>
                  </div>
                </v-col>
              </v-row>
              <v-row no-gutters v-else>
                <v-container fill-height fluid>
                  <v-row align="center" justify="center">
                    <v-progress-circular
                      :size="60"
                      color="primary"
                      indeterminate
                    ></v-progress-circular>
                  </v-row>
                </v-container>
              </v-row>
            </v-tab-item>
          </v-tabs-items>
        </v-col>
      </v-row>
      <v-col v-else>
        <v-alert class="alert-box-outline" type="error" text dense
          >You have no items in your shopping cart.</v-alert
        >
        <p>
          Click
          <span
            class="
              mr-1
              text-decoration-none
              fontcolor-black-light
              fontsize-16
              guest-shipping-address-login
            "
          >
            <span @click="goToShopping()" class="cursor-pointer"
              >here</span
            > </span
          >to continue shopping.
        </p>
      </v-col>
      <v-dialog v-model="showAddressDialog" persistent flat width="600">
        <v-card flat>
          <v-card-title class="d-flex justify-space-between">
            <p class="h3 mb-0">Shipping Address</p>
            <v-btn @click="cancelUpdateAddress()" icon>
              <v-icon>mdi-window-close</v-icon>
            </v-btn>
          </v-card-title>
          <v-divider></v-divider>
          <v-card-text class="pt-3 overflow-x-hidden">
            <v-row no-gutters>
              <v-col cols="12">
                <ShippingAddressFormComponent
                  @actionValid="checkFormValid"
                  :hideAndShowFields="hideAndShowFields"
                  @verifyAddress="verifyAddress"
                  ref="dialogShippingAddressForm"
                />
              </v-col>
              <v-col cols="12" class="py-0">
                <v-checkbox
                  label="Save in Address Book"
                  v-model="saveInAddressBook"
                  class="mt-0"
                  dense
                  hide-details
                ></v-checkbox>
              </v-col>
            </v-row>
          </v-card-text>
          <v-card-actions class="d-flex justify-end">
            <v-btn
              class="primary ma-2"
              tile
              depressed
              @click="cancelUpdateAddress()"
              >Cancel</v-btn
            >
            <v-btn
              class="success ma-2"
              tile
              depressed
              @click="saveUserAddress()"
              >Save Address</v-btn
            >
          </v-card-actions>
        </v-card>
      </v-dialog>
      <SnackbarComponent :snackbar="snackbar"></SnackbarComponent>
    </v-container>
  </div>
</template>
<script>
/* eslint-disable */
var client = require("braintree-web/client");
const baseUrl = process.env.VUE_APP_BASE_URL;
//const paypalCheckout = require("braintree-web/paypal-checkout");
import SnackbarComponent from "@/components/common/SnackbarComponent";
import CartProductList from "@/components/retailer/cart-product/CartProductList";
import ShippingAddressFormComponent from "@/components/retailer/address/ShippingAddressFormComponent";
import GuestShippingAddressForm from "@/components/retailer/address/GuestShippingAddressForm";
import BillingAddressComponent from "@/components/retailer/address/BillingAddressComponent";
import VerifyAddressComponent from "@/components/retailer/address/VerifyAddressComponent";
import CardPayment from "@/components/retailer/payment/CardPayment";
import { createHelpers } from "vuex-map-fields";
 import { VueTelInput } from "vue-tel-input";
import {
 // googleAanalyticsPurchase,
 // googleAanalyticsCheckout,
 // checkEncodeURI,
  priceFormatter,
  fetchStates,
 // googleAanalyticsCheckoutAddShippingInfo,
 // googleAanalyticsCheckoutAddPaymentInfo,
} from "@/services/util.service";

const braintreeAuthKey = process.env.VUE_APP_BRAINTREE_AUTH_KEY;
const { mapFields } = createHelpers({
  getterType: "accountOne/getField",
  mutationType: "accountOne/updateField",
});
export default {
  name: "CheckoutPage",
  data() {
    return {
      priceFormatter: priceFormatter,
      email: "",
      panelCode: 0,
      lazy: false,
      giftCardProduct: false,
      hideEmailField: false,
      hideEmailFieldGiftCardProduct: true,
      nextButtonFlag: false,
      giftCardProductTitle: "Credit Card",
      giftCardProductCode: "braintree",
      giftCardFreeProductTitle: "No Payment Information Required",
      // giftCardPaymentMethod:"braintree",
      validLogin: false,
      passwordFields: false,
      showAlert: false,
       valid: true,
      validDiscountCode: true,
      chekoutFlag: false,
      tabs: "",
      showReviewTab: false,
      showShippingTab: false,
      geoCodedAddress: "",
      geoCodedAddressFlag: false,
      validAddresses: "",
      addressInProgress: false,
      sameAddress: true,
      paymentMethod: "",
      paymentMethodFree: true,
      freePaymentMethod: "purchaseorder",
      poNumber:'',
      cartItemPanel: [0],
      saveInAddressBook: false,
      showAddressDialog: false,
      userNewAddress: false,
      regionName: "",
      instance: null,
      selectedAddressId: null,
      estimatedShipping: "",
      selectedBillingAddress: null,
      billingAddressList: [],
      showNewBillingForm: false,
      previousAddress: "",
      readOnlyCheckBox: false,
      editBillingButton: false,
      saveInBillingAddressBook: false,
      localBillingAddress: false,
      discountTextCode: "",
      emailRules: [
        (v) => !!v || "E-mail is required",
        (v) => /.+@.+\..+/.test(v) || "E-mail must be valid",
      ],
      textRules: [(v) => !!v || "This field is required"],
      snackbar: {
        show: false,
        message: null,
        color: null,
        timeout: 0,
      },
      showStoreCredit: true,
      isPageLoader: false,
      validEmail: false,
      emailId: "",
    };
  },
  components: {
    ShippingAddressFormComponent,
    BillingAddressComponent,
    CartProductList,
    VerifyAddressComponent,
    GuestShippingAddressForm,
    CardPayment,
    SnackbarComponent,
    VueTelInput
  },
  metaInfo() {
    return {
      title: "Checkout",
      meta: [
        { name: "title", content: "Checkout" },
        { name: "keywords", content: "Magento, Varien, E-commerce" },
        { name: "viewport", content: "width=device-width, initial-scale=1" },
        { name: "robots", content: "INDEX,FOLLOW" },
        { name: "format-detection", content: "telephone=no" },
      ],
      link: [
        {
          rel: "canonical",
          href: `${
            this.canonical ? window.location.href.split("?")[0] : baseUrl
          }`,
        },
      ],
    };
  },
  watch: {
    address() {
      //this.verifyAddress();
    },
    userLocalAddress() {
      this.selectedAddressId = "";
    },
    addressesList() {
      if (this.addressesList.length > 0) {
        if (!this.userLocalAddress)
          this.selectedAddressId = this.addressesList[0].id;
        if (this.selectedAddressId != 0)
          this.$store.dispatch("accountOne/setAddress", this.addressesList[0]);
      } else {
        this.$store.dispatch("accountOne/setAddress", null);
      }
    },
    discountCode() {
      this.discountTextCode = this.discountCode;
    },
    validDiscountCode() {
      if (!this.validDiscountCode) {
        this.$refs.discountCodeForm.reset();
      }
    },
    cartProductsItem() {
      this.stockFlagHideShow();
      if (this.checkProductType() == "giftcard") {
        this.showReviewTab = true;
        this.showShippingTab = false;
        this.tabs = "reviewTab";
        this.valid = true;
        this.giftCardProduct = true;
      } else {
        this.valid = false;
        this.tabs = "shippingTab";
        this.showReviewTab = true;
        this.showShippingTab = true;
        this.giftCardProduct = false;
      }
    },
    giftCardProduct() {
      if (this.giftCardProduct && this.userAuth) {
        this.billingAddressList = this.$store.state.accountOne.addresses;
        this.selectedBillingAddress = this.billingAddressList[0];
        if (this.billingAddressList.length == 0) this.showNewBillingForm = true;
      }
    },
  },
  computed: {
    canonical: function () {
      return this.$route.meta.canonical;
    },
    
    hideAndShowFields: function () {
      //let currentName = this.$router.history.current.name;
      // if (currentName === "CheckoutPage" && this.tabs == "shippingTab") {
      //   return true;
      // } else {
      return true;
      //}
    },
    paymentInProgress: function () {
      if (this.userAuth) return this.$store.state.accountOne.paymentInProgress;
      else return this.$store.state.guestInfo.paymentInProgress;
    },
    isMobileDevice() {
      return this.$vuetify.breakpoint.xsOnly;
    },
    cartProductTotalAmt() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.productTotalAmt;
      } else {
        return this.$store.state.cartProduct.productTotalAmt;
      }
    },
    userAuth: function () {
      return this.$store.state.auth.userAuth;
    },
     
    fetchSeletedAddress: function () {
      return this.$store.state.accountOne.seletedAddress;
    },
    basicInfo: function () {
      if (this.userAuth) {
        return this.$store.state.accountOne.one;
      } else {
        return this.$store.state.guestInfo.one;
      }
    },
    addressContainPOBox: function () {
      if (this.userAuth) {
        return this.$store.state.accountOne.addressContainPOBox;
      } else {
        return this.$store.state.guestInfo.addressContainPOBox;
      }
    },
    addressesList: function () {
      return this.$store.state.accountOne.addresses;
    },
    address: function () {
      if (this.userAuth) {
        return this.$store.state.accountOne.address;
      } else {
        return this.$store.state.guestInfo.address;
      }
    },
    addressLength: function () {
      if (this.basicInfo.addresses) return this.basicInfo.addresses.length;
      return -1;
    },
    addressFields: function () {
      if (this.userAuth) {
        return this.$store.state.accountOne.address;
      } else {
        return this.$store.state.guestInfo.address;
      }
    },
    ...mapFields(["one", "allCountries", "countryAllStates"]),

    estimatedShippingMethods() {
      if (this.userAuth) {
        return this.$store.state.accountOne.estimatedShipping;
      } else {
        return this.$store.state.guestInfo.estimatedShipping;
      }
    },
    inProgress() {
      if (this.userAuth) {
        return this.$store.state.accountOne.inProgress;
      } else {
        return this.$store.state.guestInfo.inProgress;
      }
    },
    shippingInformations() {
      if (this.userAuth) {
        return this.$store.state.accountOne.shippingInformation;
      } else {
        return this.$store.state.guestInfo.shippingInformation;
      }
    },
    cartProductsItem() {
      let cartList = [];
      if (this.userAuth) {
        cartList = this.$store.state.userCartProduct.cartProductList;
       // googleAanalyticsCheckout("begin_checkout", { items: cartList });
        return cartList;
      } else {
        cartList = this.$store.state.cartProduct.cartProductList;
      //  googleAanalyticsCheckout("begin_checkout", { items: cartList });
        return cartList;
      }
    },
    /*  cartProductTotalAmt() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.productTotalAmt;
      } else {
        return this.$store.state.cartProduct.productTotalAmt;
      }
    },*/
    userLocalAddress() {
      return this.$store.state.accountOne.userLocalAddress;
    },
    userLocalAddressFlag() {
      return this.$store.state.accountOne.userLocalAddressFlag;
    },
    userSelectedAddressIndex() {
      return this.$store.state.accountOne.userSelectedAddressIndex;
    },
    userLocalBillAddress() {
      return this.$store.state.accountOne.userLocalBillAddress;
    },
    lastAddedAddressBookIndex() {
      return this.$store.state.accountOne.lastAddedAddressBookIndex;
    },
    discountCode() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.discountCode;
      } else {
        return this.$store.state.cartProduct.discountCode;
      }
    },
    inProgressDiscountCode() {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.fetchInProgress;
      } else {
        return this.$store.state.cartProduct.fetchInProgress;
      }
    },
    cartProductsProgress: function () {
      if (this.userAuth) {
        return this.$store.state.userCartProduct.cartProductsProgress;
      } else {
        return this.$store.state.cartProduct.cartProductsProgress;
      }
    },
    shippingInformationsInProgress: function () {
      if (this.userAuth) {
        return this.$store.state.accountOne.shippingInformationsInProgress;
      } else {
        return this.$store.state.guestInfo.shippingInformationsInProgress;
      }
    },
    countryAndStatesList() {
      return this.$store.state.accountOne.allCountries;
    },
     purchaseOrderPayment() {
      let paymentMethods=this.shippingInformations.paymentMethods;
      return paymentMethods.filter(method=>method.code==="purchaseorder")[0]
    },
    //  freePayment() {
    //   let paymentMethods=this.shippingInformations.paymentMethods;
    //   return paymentMethods.filter(method=>method.code==="free")[0]
    // },
  },
  methods: {
    checkProductType() {
      let array = this.cartProductsItem.filter((obj) => {
        return obj.productType == "giftcard";
      });
      if (this.cartProductsItem.length === array.length) {
        return "giftcard";
      }
      return "other";
    },
    sendEmailId() {
      this.$emit("actionValid", { valid: this.valid, email: this.email });
    },
    checkEmail() {
      this.email = this.$refs.emailForm ? this.emailId : this.email;
      this.$store
        .dispatch("guestInfo/checkEmailAvailable", this.email)
        .then((data) => {
          if (data.exist == false) {
            this.passwordFields = true;
          } else {
            this.passwordFields = false;
          }
        });
    },
    stockFlagHideShow() {
      if (this.cartProductsItem) {
        let errorCount = 0;
        let i;
        for (i = 0; i < this.cartProductsItem.length; i++) {
          if (
            (!this.cartProductsItem[i].stockDetails.isInStock ||
              this.cartProductsItem[i].stockDetails.qty <
                this.cartProductsItem[i].qty) &&
            this.cartProductsItem[i].stockDetails.manageStock &&
            this.cartProductsItem[i].stockDetails.backorders == 0
          ) {
            errorCount++;
          }
        }
        if (errorCount) {
          this.$router.push({
            name: "CartProducts",
          });
        }
      }
    },
    useStoreCredit() {
      this.$store.dispatch("storeCredit/applyStoreCredit").then(() => {
        if (this.userAuth) {
          this.$store.dispatch(
            "accountOne/setShippingInformation",
            this.estimatedShipping
          );
          if (this.giftCardProduct) {
            this.$store.dispatch("userCartProduct/productTotalAmt");
          }
        }
      });
    },
    resetValidation() {
      if (!this.validDiscountCode) {
        this.$refs.discountCodeForm.reset();
      }
    },
    goToShopping() {
      //window.open("/shop/category/stationery/1/9/position/10/e30=", "_self");
      this.$router.push({
        name: "HomePage",
      });
    },
    showTab(tab) {
      this.tabs = tab;
    },
    changedToShippTab() {
      this.valid = false;
      if (
        localStorage.getItem("cr_" + this.basicInfo.id + "_userNewShippAddress")
      ) {
        this.$store.dispatch(
          "accountOne/setLocalShippAddress",
          JSON.parse(
            localStorage.getItem(
              "cr_" + this.basicInfo.id + "_userNewShippAddress"
            )
          )
        );
      }
    },
    openDialogForEditAddress() {
      this.geoCodedAddress = "";
      this.addressInProgress = true;
      this.showAddressDialog = true;
      this.previousAddress = this.address;
      this.$store.dispatch("accountOne/setAddress", null);
      if (
        this.$refs.dialogShippingAddressForm &&
        this.cartProductsItem.items !== ""
      )
        this.$refs.dialogShippingAddressForm.$refs.shippingAddressform.resetValidation();
    },
    editLocalAddress(address, flag) {
      this.showAddressDialog = true;
      this.previousAddress = address;
      if (flag) this.$store.dispatch("accountOne/setAddress", address);
      else this.$store.dispatch("accountOne/setLocalShippAddress", address);
    },
    applyDiscountCode() {
      if (this.$refs.discountCodeForm.validate()) {
        if (this.userAuth) {
          this.$store
            .dispatch(
              "userCartProduct/applyDiscountCode",
              this.discountTextCode
            )
            .then(() => {
              this.snackbar = {
                message: "Your coupon was successfully applied",
                color: "success",
                show: true,
                timeout: 2000,
              };
              this.$store.dispatch(
                "accountOne/setShippingInformation",
                this.estimatedShipping
              );
            })
            .catch((error) => {
              this.snackbar = {
                message: error.message,
                color: "error",
                show: true,
                timeout: 2000,
              };
            });
        } 
      
      }
    },
    removeDiscountCode() {
      if (this.$refs.discountCodeForm.validate()) {
        if (this.userAuth) {
          this.$store
            .dispatch(
              "userCartProduct/removeDiscountCode",
              this.discountTextCode
            )
            .then(() => {
              this.snackbar = {
                message: "Your coupon was successfully removed",
                color: "success",
                show: true,
                timeout: 2000,
              };
              this.$store.dispatch(
                "accountOne/setShippingInformation",
                this.estimatedShipping
              );
            })
            .catch((error) => {
              this.snackbar = {
                message: error.message,
                color: "error",
                show: true,
                timeout: 2000,
              };
            });
        }
      }
    },
    continueToPaypal() {},
    resetFields() {
      if (!this.userAuth) {
        this.hideEmailField = true;
        //this.$refs.addressForm.$refs.guestShippingAddressForm.reset();
      } else {
        this.billingAddressList = [];
        this.billingAddressList = this.addressesList.filter((obj) => {
          return obj;
        });
        let newAddr = {
          text: "New Address",
          value: "New Address",
        };
        this.billingAddressList.push(newAddr);
        if (this.userSelectedAddressIndex != -1)
          this.selectedBillingAddress =
            this.billingAddressList[this.userSelectedAddressIndex];
        else this.selectedBillingAddress = this.billingAddressList[0];
        this.previousAddress = this.address;
        if (this.addressLength == 0) this.showNewBillingForm = true;
        else this.showNewBillingForm = false;
        this.billBookDesignChanges();
      }
    },
    editBillBook() {
      this.sameAddress = false;
      this.billBookDesignChanges();
    },
    billBookDesignChanges() {
      let billBookFlag = localStorage.getItem(
        "cr_" + this.basicInfo.id + "_billBookAddressFlag"
      );
      if (billBookFlag != "true") {
        if (
          localStorage.getItem(
            "cr_" + this.basicInfo.id + "_userNewBillAddress"
          )
        ) {
          let newAddress = JSON.parse(
            localStorage.getItem(
              "cr_" + this.basicInfo.id + "_userNewBillAddress"
            )
          );
          this.$store.dispatch("accountOne/setLocalBillAddress", newAddress);
          this.previousAddress = newAddress;
          this.selectedBillingAddress =
            this.billingAddressList[this.billingAddressList.length - 1];
          this.showNewBillingForm = true;
        }
      }
    },
    cancelBillingAddress() {
      this.sameAddress = true;
      if (this.previousAddress.street)
        this.$store.dispatch("accountOne/setAddress", this.previousAddress);
      else
        this.$store.dispatch(
          "accountOne/setLocalShippAddress",
          this.previousAddress
        );

      this.editBillingButton = false;
      this.readOnlyCheckBox = false;
    },
    updateBillingAddress() {
      this.$store.dispatch(
        "accountOne/setAddress",
        this.selectedBillingAddress
      );
      this.sameAddress = true;
      this.editBillingButton = true;
      this.readOnlyCheckBox = false;
    },
    changeBillingAddress() {
      if (this.selectedBillingAddress.value) {
        this.showNewBillingForm = true;
        if (this.userLocalBillAddress) {
          this.$store.dispatch(
            "accountOne/setLocalBillAddress",
            this.userLocalBillAddress
          );
          this.previousAddress = this.address;
        } else {
          this.$store.dispatch("accountOne/setAddress", null);
        }
        this.readOnlyCheckBox = true;
        localStorage.setItem(
          "cr_" + this.basicInfo.id + "_billBookAddressFlag",
          false
        );
      } else {
        this.showNewBillingForm = false;
        this.$store.dispatch(
          "accountOne/setAddress",
          this.selectedBillingAddress
        );
        this.readOnlyCheckBox = false;
        localStorage.setItem(
          "cr_" + this.basicInfo.id + "_billBookAddressFlag",
          true
        );
      }
    },
    newBillingAddress() {
      this.previousAddress = this.address;
      if (this.$refs.billingForm.$refs.shippingAddressform.validate()) {
        if (this.saveInBillingAddressBook) {
          this.$store.dispatch("accountOne/updateAddress");
          localStorage.setItem(
            "cr_" + this.basicInfo.id + "_billBookAddressFlag",
            true
          );
          //this.$store.dispatch("accountOne/setLocalBillAddress", "");
        } else {
          localStorage.setItem(
            "cr_" + this.basicInfo.id + "_billBookAddressFlag",
            false
          );
          this.$store.dispatch(
            "accountOne/setLocalBillAddress",
            this.previousAddress
          );
        }
        this.sameAddress = true;
        this.readOnlyCheckBox = false;
      }
    },
    checkFormValid(flag) {
      if (flag) return (this.nextButtonFlag = true);
    },
    checkGuestFormValid(flag) {
      if (flag)
        return (this.nextButtonFlag = true) && (this.email = flag.email);
    },
    /*shipHereAddress(addressId){
      this.selectedAddressId = addressId;
    },*/
    shipHereAddress(address, index) {
      if (index != -1) {
        this.selectedAddressId = address.id;
        this.$store.dispatch(
          "accountOne/setAddress",
          this.addressesList[index]
        );
      } else {
        this.selectedAddressId = "";
        this.$store.dispatch("accountOne/setLocalShippAddress", address);
      }
     // this.verifyAddress();
      this.$store.dispatch("accountOne/setSelectedShippAddressIndex", index);
       this.verifyAddress();
    },
    async verifyAddress() {
     let vm = this;
      try {
        if (
          vm.address.regionId &&
          vm.address.city &&
          vm.address.countryId &&
          vm.address.streetNoOne &&
          vm.address.postcode
        ) {
          vm.geoCodedAddress = "";
          this.addressInProgress = true;
          if (vm.countryAndStatesList.length == 0) {
            await vm.$store.dispatch("accountOne/fetchCountries");
          }
          let stateNameList = fetchStates(
            vm.address.countryId,
            vm.countryAndStatesList
          );
          let stateName = stateNameList.filter((obj) => {
            if (obj.value == vm.address.regionId) return obj;
          });
          stateName = stateName ? stateName[0].label : "";

        /*  let response = await vm.$store.dispatch(
            "accountOne/validateAddressCheckout",
            { address: vm.addressFields, stateName: stateName }
          );
          if (typeof response == "object") {
            if (response[0].error_message) {
              vm.geoCodedAddress = response[0].error_message;
              vm.geoCodedAddressFlag = false;
              vm.validAddresses = "";
            } else {
              vm.geoCodedAddress = "Address is geocoded.";
              vm.geoCodedAddressFlag = true;
              vm.validAddresses = response[0];
            }
          }*/
          if (vm.userAuth) {
            await vm.$store.dispatch("accountOne/setEstimatedShipping");
          }
          this.addressInProgress = false;
        }
      } catch (error) {
        this.addressInProgress = false;
        vm.snackbar = {
          message: error,
          color: "error",
          show: true,
          timeout: 3000,
        };
      }
    },
    regionDetails(regionName) {
      if (regionName[0].value) {
        this.regionName = regionName[0].label;
      }
    },
    next: function () {
      if (this.userAuth) {
        if (this.addressesList.length == 0) {
          let phoneNumber = this.$refs.userAddressForm.$refs.phoneNumber
            ? this.$refs.userAddressForm.$refs.phoneNumber.phoneObject.isValid
            : true;
          if (!phoneNumber) {
            this.$refs.userAddressForm.$refs.phoneNumber
              ? this.$refs.userAddressForm.validateNumber()
              : "";
          }
          if (
            this.$refs.userAddressForm.$refs.shippingAddressform.validate() &&
            phoneNumber
          ) {
            this.$store.dispatch(
              "accountOne/setLocalShippAddress",
              this.address
            );
            localStorage.setItem(
              "cr_" + this.basicInfo.id + "_userFirstShippAddress",
              JSON.stringify(this.address)
            );
            this.$store.dispatch(
              "accountOne/setShippingInformation",
              this.estimatedShipping
            );
            /*googleAanalyticsCheckout("checkout_progress", {
              items: this.cartProductsItem,
            });
            googleAanalyticsCheckout("set_checkout_option", {
              checkout_step: 1,
              checkout_option: "shipping method",
            });
            googleAanalyticsCheckoutAddShippingInfo(
              "add_shipping_info",
              this.cartProductsItem
            );*/
            this.valid = true;
            this.tabs = "reviewTab";
          }
        } else {
          this.$store.dispatch(
            "accountOne/setShippingInformation",
            this.estimatedShipping
          );
          /*googleAanalyticsCheckout("checkout_progress", {
            items: this.cartProductsItem,
          });
          googleAanalyticsCheckout("set_checkout_option", {
            checkout_step: 1,
            checkout_option: "shipping method",
          });
          googleAanalyticsCheckoutAddShippingInfo(
            "add_shipping_info",
            this.cartProductsItem
          );*/
          this.valid = true;
          this.tabs = "reviewTab";
        }
        this.$store.dispatch("accountOne/resetLocalShippAddressVar", null);
      } else {
        let phoneNumber = this.$refs.guestAddressForm.$refs.phoneNumber
          ? this.$refs.guestAddressForm.$refs.phoneNumber.phoneObject.isValid
          : true;
        if (!phoneNumber) {
          this.$refs.guestAddressForm.$refs.phoneNumber
            ? this.$refs.guestAddressForm.validateNumber()
            : "";
        }
        if (
          this.$refs.guestAddressForm.$refs.guestShippingAddressForm.validate() &&
          this.$refs.guestAddressForm.$refs.loginForm.validate() &&
          phoneNumber
        ) {
          /*googleAanalyticsCheckout("checkout_progress", {
            items: this.cartProductsItem,
          });
          googleAanalyticsCheckout("set_checkout_option", {
            checkout_step: 1,
            checkout_option: "shipping method",
          });
          googleAanalyticsCheckoutAddShippingInfo(
            "add_shipping_info",
            this.cartProductsItem
          );*/

          this.$store.dispatch("guestInfo/setShippingInformation", {
            method: this.estimatedShipping,
            email: this.email,
          });
          this.valid = true;
          this.tabs = "reviewTab";
        } else {
          this.snackbar = {
            message: "Please fill out all required fields",
            color: "error",
            show: true,
            timeout: 3000,
          };
          window.scrollTo(0, 0);
        }
      }
    },
    saveUserAddress() {
      let phoneNumber = this.$refs.dialogShippingAddressForm.$refs.phoneNumber
        ? this.$refs.dialogShippingAddressForm.$refs.phoneNumber.phoneObject
            .isValid
        : true;
      if (!phoneNumber) {
        this.$refs.dialogShippingAddressForm.$refs.phoneNumber
          ? this.$refs.dialogShippingAddressForm.validateNumber()
          : "";
      }
      if (
        this.$refs.dialogShippingAddressForm.$refs.shippingAddressform.validate() &&
        phoneNumber
      ) {
        this.valid = true;
        if (this.userAuth) {
          if (this.saveInAddressBook) {
            this.$store.dispatch("accountOne/updateAddress");
            this.showAddressDialog = false;
            localStorage.setItem(
              "cr_" + this.basicInfo.id + "_userNewShippAddress",
              ""
            );
            this.$store.dispatch("accountOne/setLocalShippAddress", "");
            this.$store.dispatch(
              "accountOne/setSelectedShippAddressIndex",
              this.addressesList.length - 1
            );
            this.$store.dispatch(
              "accountOne/lastAddedAddressBookIndex",
              this.addressesList.length - 1
            );
          } else {
            this.$store.dispatch("accountOne/setShippingAddress");
            this.$store.dispatch("accountOne/setSelectedShippAddressIndex", -1);
            this.$store.dispatch("accountOne/lastAddedAddressBookIndex", -1);
            this.showAddressDialog = false;
          }
          // this.showAddressDialog = false;
          this.$store.dispatch("accountOne/setLocalShippAddressFlag", true);
        }

        //else
        //this.$store.dispatch("accountOne/basicInfo", this.one);
      }
      this.addressInProgress = false;
    },
    cancelUpdateAddress() {
      this.showAddressDialog = false;
      this.addressInProgress = false;
      if (this.userLocalAddress) {
        this.$store.dispatch(
          "accountOne/setLocalShippAddress",
          this.previousAddress
        );
      } else {
        this.$store.dispatch("accountOne/setAddress", this.previousAddress);
      }
    },
    onGatewayLoad(instance) {
      this.instance = instance;
    },
    onPaymentSuccess(payload) {
      console.log(payload);
    },
    onPaymentError(error) {
      console.log(error);
    },
    onGatewayLoadFail(instance) {
      console.log("load failed", instance);
    },
    async placeOrderFree(e) {
      try {
         e.preventDefault();
      if (this.$refs.poNumberForm.validate()) {
        this.isPageLoader = true;
        if (this.userAuth) {
          try {
            let res = await this.$store.dispatch("accountOne/setOrder", {
              method: this.freePaymentMethod,
              "poNumber": this.poNumber,
            });
             await this.$store.dispatch("accountOne/setPaymentInProgress", true);

             if (res) {
              try {
                let resp = await this.$store.dispatch(
                  "meProductOne/fetchOrderProduct",
                  res
                );
                 
              
              } catch (error) {
                await this.$store.dispatch(
                  "accountOne/setPaymentInProgress",
                  false
                );
                this.isPageLoader = false;
                this.snackbar = {
                  message: error,
                  color: "error",
                  show: true,
                  timeout: 5000,
                };
              }
            }
            await this.$store.dispatch(
              "accountOne/setPaymentInProgress",
              false
            );
            this.$router.push({
              name: "OrderSuccess",
              params: { orderNumber: res },
            });
          } catch (error) {
            this.isPageLoader = false;
            this.snackbar = {
              message: error.message,
              color: "error",
              show: true,
              timeout: 5000,
            };
          }
        }
      }
       
      } catch (error) {}
    },
    async submitCardPayment(payment) {
      try {
        let vm = this;
        this.isPageLoader = true;
        if (this.userAuth) {
          if (vm.$refs.billingForm) {
            let formValid = vm.$refs.billingForm
              ? vm.$refs.billingForm.$refs.shippingAddressform.validate()
              : true;
            if (!formValid) {
              this.snackbar = {
                message: "Please enter all required fields",
                color: "error",
                show: true,
                timeout: 5000,
              };
              return;
            }
          }
          try {
            let res = await this.$store.dispatch("accountOne/setOrder", {
              method: this.paymentMethod,
              additional_data: { payment_method_nonce: payment.nonce },
            });
            await this.$store.dispatch("accountOne/setPaymentInProgress", true);
            if (res) {
              try {
                let resp = await this.$store.dispatch(
                  "meProductOne/fetchOrderProduct",
                  res
                );
                if (resp && resp.items) {
                  /*googleAanalyticsCheckout("checkout_progress", {
                    items: resp.items,
                  });
                  googleAanalyticsCheckout("set_checkout_option", {
                    checkout_step: 1,
                    checkout_option: "payment",
                  });

                  googleAanalyticsCheckoutAddPaymentInfo(
                    "add_payment_info",
                    resp
                  );
                  googleAanalyticsPurchase(resp, resp.incrementId);*/
                  let shippingAddress = [];
                  let ccid = "";
                  let webOrderNumber = resp.incrementId;
                  let magentoOrderNumber = res;
                  for (let i = 0; resp.items.length > i; i++) {
                    let obj = resp.items[i];
                    if (obj.extensionAttributes) {
                      ccid = obj.extensionAttributes.ccid;
                      if (ccid) {
                        shippingAddress =
                          resp.extensionAttributes.shippingAssignments[0]
                            .shipping.address;
                        try {
                          let response = await this.$store.dispatch(
                            "accountOne/setCCOrder",
                            {
                              orderNumber: ccid,
                              shippingAddress: shippingAddress,
                              webOrderNumber: webOrderNumber,
                              estimatedShipping: this.estimatedShipping,
                            }
                          );
                        } catch (error) {
                          console.log(error);
                        }
                      }
                      if (obj.extensionAttributes.personalizeDetails) {
                        await this.placeCraneOrder(
                          resp,
                          obj,
                          webOrderNumber,
                          magentoOrderNumber
                        );
                      }
                    }
                  }
                }
              } catch (error) {
                await this.$store.dispatch(
                  "accountOne/setPaymentInProgress",
                  false
                );
                this.isPageLoader = false;
                this.snackbar = {
                  message: error,
                  color: "error",
                  show: true,
                  timeout: 5000,
                };
              }
            }
            await this.$store.dispatch(
              "accountOne/setPaymentInProgress",
              false
            );
            this.$router.push({
              name: "OrderSuccess",
              params: { orderNumber: res },
            });
          } catch (error) {
            this.isPageLoader = false;
            this.snackbar = {
              message: error.message,
              color: "error",
              show: true,
              timeout: 5000,
            };
          }
        } else {
          if (vm.$refs.emailForm) {
            vm.email = vm.emailId;
            let valid = vm.$refs.emailForm.validate();
            let formValid = vm.$refs.addressFormGuest
              ? vm.$refs.addressFormGuest.$refs.guestShippingAddressForm.validate()
              : true;
            if (!valid || !formValid) {
              this.snackbar = {
                message: "Please enter all required fields",
                color: "error",
                show: true,
                timeout: 5000,
              };
              return;
            }
          }
          try {
            let res = await this.$store.dispatch("guestInfo/setOrder", {
              userEmail: vm.email,
              paymentMethod: {
                method: this.paymentMethod,
                additional_data: { payment_method_nonce: payment.nonce },
              },
            });
            await this.$store.dispatch("guestInfo/setPaymentInProgress", true);
            if (res) {
              try {
                let resp = await this.$store.dispatch(
                  "meProductOne/fetchOrderProduct",
                  res
                );
                if (resp && resp.items) {
                  /*googleAanalyticsCheckout("checkout_progress", {
                    items: resp.items,
                  });
                  googleAanalyticsCheckout("set_checkout_option", {
                    checkout_step: 1,
                    checkout_option: "payment",
                  });

                  googleAanalyticsCheckoutAddPaymentInfo(
                    "add_payment_info",
                    resp
                  );
                  googleAanalyticsPurchase(resp, resp.incrementId);*/
                  let shippingAddress = [];
                  let ccid = "";
                  let webOrderNumber = resp.incrementId;
                  let magentoOrderNumber = res;
                  for (let i = 0; resp.items.length > i; i++) {
                    let obj = resp.items[i];
                    if (obj.extensionAttributes) {
                      ccid = obj.extensionAttributes.ccid;
                      if (ccid) {
                        shippingAddress =
                          resp.extensionAttributes.shippingAssignments[0]
                            .shipping.address;
                        try {
                          let response = await this.$store.dispatch(
                            "accountOne/setCCOrder",
                            {
                              orderNumber: ccid,
                              shippingAddress: shippingAddress,
                              webOrderNumber: webOrderNumber,
                              estimatedShipping: this.estimatedShipping,
                            }
                          );
                        } catch (error) {
                          console.log(error);
                        }
                      }
                      if (obj.extensionAttributes.personalizeDetails) {
                        await this.placeCraneOrder(
                          resp,
                          obj,
                          webOrderNumber,
                          magentoOrderNumber
                        );
                      }
                    }
                  }
                }
              } catch (error) {
                await this.$store.dispatch(
                  "guestInfo/setPaymentInProgress",
                  false
                );
                this.isPageLoader = false;
                this.snackbar = {
                  message: error,
                  color: "error",
                  show: true,
                  timeout: 5000,
                };
              }
            }
            await this.$store.dispatch("guestInfo/setPaymentInProgress", false);
            this.$router.push({
              name: "OrderSuccess",
              params: { orderNumber: res },
            });
          } catch (error) {
            this.isPageLoader = false;
            this.snackbar = {
              message: error.message,
              color: "error",
              show: true,
              timeout: 5000,
            };
          }
        }
      } catch (error) {}
    },
    clearLocalStorageVars() {
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_userFirstShippAddress"
      );
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_userNewShippAddressFlag"
      );
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_userNewShippAddress"
      );
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_userSelectedShippAddressIndex"
      );
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_billBookAddressFlag"
      );
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_userNewBillAddress"
      );
      localStorage.removeItem(
        "cr_" + this.basicInfo.id + "_lastAddedAddressBookIndex"
      );
    },
    localStorageInitialOperation() {
      if (this.basicInfo.id) {
        if (this.addressesList.length == 0) {
          if (
            localStorage.getItem(
              "cr_" + this.basicInfo.id + "_userFirstShippAddress"
            )
          ) {
            let userFirstAddress = JSON.parse(
              localStorage.getItem(
                "cr_" + this.basicInfo.id + "_userFirstShippAddress"
              )
            );
            this.$store.dispatch(
              "accountOne/setLocalShippAddress",
              userFirstAddress
            );
          }
        } else if (this.addressesList.length > 0) {
          let flag = localStorage.getItem(
            "cr_" + this.basicInfo.id + "_userNewShippAddressFlag"
          );
          if (flag != null)
            this.$store.dispatch("accountOne/setLocalShippAddressFlag", flag);

          if (
            localStorage.getItem(
              "cr_" + this.basicInfo.id + "_userNewShippAddress"
            )
          ) {
            let tempLocalAddress = JSON.parse(
              localStorage.getItem(
                "cr_" + this.basicInfo.id + "_userNewShippAddress"
              )
            );
            this.$store.dispatch(
              "accountOne/setLocalShippAddress",
              tempLocalAddress
            );
          }

          if (
            localStorage.getItem(
              "cr_" + this.basicInfo.id + "_userSelectedShippAddressIndex"
            )
          ) {
            let index = localStorage.getItem(
              "cr_" + this.basicInfo.id + "_userSelectedShippAddressIndex"
            );
            if (index < this.addressesList.length)
              this.$store.dispatch(
                "accountOne/setSelectedShippAddressIndex",
                index
              );
            else
              this.$store.dispatch(
                "accountOne/setSelectedShippAddressIndex",
                0
              );
            //set user address to  state.address
            if (index == -1)
              this.$store.dispatch(
                "accountOne/setLocalShippAddress",
                JSON.parse(
                  localStorage.getItem(
                    "cr_" + this.basicInfo.id + "_userNewShippAddress"
                  )
                )
              );
            else
              this.$store.dispatch(
                "accountOne/setAddress",
                this.addressesList[index]
              );
          } else {
            this.$store.dispatch("accountOne/setSelectedShippAddressIndex", 0);
          }
          if (
            localStorage.getItem(
              "cr_" + this.basicInfo.id + "_lastAddedAddressBookIndex"
            )
          ) {
            let index = localStorage.getItem(
              "cr_" + this.basicInfo.id + "_lastAddedAddressBookIndex"
            );
            this.$store.dispatch("accountOne/lastAddedAddressBookIndex", index);
          } else
            this.$store.dispatch("accountOne/lastAddedAddressBookIndex", -1);
        }
      }
    },
    setDiscountTextCode() {
      if (this.userAuth) {
        this.discountTextCode = this.$store.state.userCartProduct.discountCode;
      } else {
        this.discountTextCode = this.$store.state.cartProduct.discountCode;
      }
    },
    async placeCraneOrder(resp, obj, webOrderNumber, magentoOrderNumber) {
      try {
        // let order = {};
        //  let detailArray = [];
        let shipArray = [];
        let shippingAddress = [];
        shippingAddress =
          resp.extensionAttributes.shippingAssignments[0].shipping.address;

        // let refId = Date.now().toString();
        // order.RefId = `${refId}`;
        // order.CustomerNumber = "338000";
        // order.OrderDate = `${resp.createdAt}`;
        // order.PONumber = `${webOrderNumber}`;

        let shp = {};
        shp.RefId = `${webOrderNumber}`;
        shp.Quantity = obj.qtyOrdered;
        shp.ShipToName =
          shippingAddress.firstname + " " + shippingAddress.lastname;
        shp.ShipToAddress1 = shippingAddress.street[0];
        shp.ShipToAddress2 = shippingAddress.street[1];
        shp.ShipToAddress3 = null;
        shp.ShipToCity = shippingAddress.city;
        shp.ShipToState = shippingAddress.regionCode;
        shp.ShipToPostalCode = shippingAddress.postcode;
        shp.ShipToCountry = shippingAddress.countryId;
        shp.ShipToPhoneNumber = shippingAddress.telephone;
        shp.ShipMethod =
          resp.extensionAttributes.shippingAssignments[0].shipping.method;
        shipArray.push(shp);

        let personalizeDetails = JSON.parse(
          obj.extensionAttributes.personalizeDetails
        );
        // let pdfs = await this.$store.dispatch("accountOne/fetchProductPdfs", {
        //   orderNumber: Number(magentoOrderNumber),
        //   itemId: obj.itemId,
        // });

        let pdfdoc = {
          app_id: "crane",
          organization_id: "3fa85f64-5717-4562-b3fc-2c963f66afa6",
          part_order: "1",
          product_part_id: "6158c039-8203-4b5f-8a77-13eeb467cd45",
          svg_content: "<svg></svg>",
          workflow_data: "",
          type: "final",
          tags: ["draft"],
          status: "creating",
        };
        for (let i = 0; i < personalizeDetails.length; i++) {
          let part = personalizeDetails[i];

          if (part.partSelected) {
            let partDetails = {
              name: part.name,
              sku: obj.sku,
              shipArray: shipArray,
              orderDetails: part.orderObject.Details[0],
              orientationId: part.orientationId ? part.orientationId : 1,
              elements: [],
              // currentPartSurfaceType: part.currentPartSurfaceType,
            };

            // let svgContent=null
            // if(part.currentPartSurfaceType==="alternateSurface")
            // svgContent=part.alternateSvg
            // else
            // svgContent= part.svg

            let orderPartDetails = {
              m2_order_id: `${magentoOrderNumber}`,
              m2_order_item_id: `${obj.itemId}`,
              m2_order_po_id: `${webOrderNumber}`,
              part_order: i + 1,
              product_part_id: part.id,
              svg_content: part.svg,
              alternate_svg_content: part.alternateSvg,
              workflow_data: { part: partDetails },
            };
            console.log(
              "workflow data",
              JSON.stringify(orderPartDetails.workflow_data)
            );
            let pdfdocReponse = await this.$store.dispatch("pdfDocOne/save", {
              ...pdfdoc,
              ...orderPartDetails,
            });
            console.log("post pdfdoc id ", pdfdocReponse);
            console.log("post pdfdoc successfully for order part ", part.id);
          }
        }
      } catch (error) {
        console.log("error in builder 2 order place", error);
      }
    },
  },
  mounted() {
    client.create(
      {
        authorization: braintreeAuthKey,
      },
      function (clientErr, clientInstance) {
        // Stop if there was a problem creating the client.
        // This could happen if there is a network error or if the authorization
        // is invalid.
        if (clientErr) {
          console.error("Error creating client:", clientErr);
          return;
        }

        // Create a PayPal Checkout component.
        /* paypalCheckout.create(
          {
            client: clientInstance,
          },
          function (paypalCheckoutErr, paypalCheckoutInstance) {
            // Stop if there was a problem creating PayPal Checkout.
            // This could happen if there was a network error or if it's incorrectly
            // configured.
            if (paypalCheckoutErr) {
              console.error(
                "Error creating PayPal Checkout:",
                paypalCheckoutErr
              );
              return;
            }

            // Set up PayPal with the checkout.js library
            paypal.Button.render(
              {
                env: "production", // or 'sandbox'

                payment: function () {
                  return paypalCheckoutInstance.createPayment({
                    // Your PayPal options here. For available options, see
                    // http://braintree.github.io/braintree-web/current/PayPalCheckout.html#createPayment
                  });
                },

                onAuthorize: function (data, actions) {
                  return paypalCheckoutInstance.tokenizePayment(data, function (
                    err,
                    payload
                  ) {
                    // Submit `payload.nonce` to your server.
                  });
                },

                onCancel: function (data) {
                  console.log(
                    "checkout.js payment cancelled",
                    JSON.stringify(data, 0, 2)
                  );
                },

                onError: function (err) {
                  console.error("checkout.js error", err);
                },
              },
              "#paypal-button"
            ).then(function () {
              // The PayPal button will be rendered in an html element with the id
              // `paypal-button`. This function will be called when the PayPal button
              // is set up and ready to be used.
            });
          }
        );*/
      }
    );
  },
  async created() {
    //this.$store.dispatch("accountOne/fetchStates");
    //this.$store.dispatch("accountOne/fetchCountries");
    if (this.userAuth) {
      await this.$store.dispatch("accountOne/basicInfo");
      //this.$store.dispatch("userCartProduct/cartProductList");
      //this.$store.dispatch("userCartProduct/productTotalAmt");
      this.$store.dispatch("userCartProduct/fetchCartCoupon");
      
      this.localStorageInitialOperation();
    //  this.setDiscountTextCode();

      // let checkOutTab = localStorage.getItem("cr_checkOutTab")
      // if(checkOutTab==='reviewTab') this.tabs = "reviewTab";
    } 
    this.verifyAddress();
    this.stockFlagHideShow();
    if (this.cartProductsItem) {
      if (this.checkProductType() == "giftcard") {
        this.showReviewTab = true;
        this.showShippingTab = false;
        this.tabs = "reviewTab";
        this.valid = true;
        this.giftCardProduct = true;
      } else {
        this.valid = false;
        this.tabs = "shippingTab";
        this.showReviewTab = true;
        this.showShippingTab = true;
        this.giftCardProduct = false;
      }
    }
  },
};
</script>
<style>
.checkout-tabs {
  margin: auto !important;
  padding-top: 5px;
  padding-bottom: 5px;
}
</style>
<style src="./checkout_page.scss" lang="scss" />