import { defineComponent, onMounted, ref, computed, watch } from 'vue'
import { tools } from '@tools'
import { useUserStore } from '@store/UserStore'
import { useRouter } from 'vue-router'
import { useGlobalStore } from '@store/globalStore'
import { useProducts } from '@store/Products'
import { useI18n } from 'vue-i18n'
import { toolsext } from '@store/Modules/toolsext'
import { useQuasar } from 'quasar'
import { costanti } from '@costanti'
import type { ICart, IOrder, IOrderCart, IProduct } from '@src/model/Products';
import { IShareWithUs } from '@src/model/Products'

import { shared_consts } from '@src/common/shared_vuejs'

import { CSingleCart } from '../CSingleCart'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CSelectUserActive } from '@src/components/CSelectUserActive'

export default defineComponent({
  name: 'CCart',
  props: {
    iscash: {
      type: Boolean,
      required: false,
      default: false,
    },
    idOrdersCart: {
      type: String,
      required: false,
      default: null,
    },

  },
  components: { CSingleCart, CTitleBanner, CSelectUserActive },
  setup(props) {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const productStore = useProducts()
    const $router = useRouter()
    const $q = useQuasar()
    const { t } = useI18n();

    const mycart = ref(<ICart>{})
    const myrec = ref(<any[string]>[])
    const oldrec = ref(<any[string]>[])
    const note = ref('')
    const endload = ref(false)
    const recOrderCart = ref(<IOrderCart>{})

    const search = ref('')

    const isfinishLoading = computed(() => globalStore.finishLoading)

    watch(() => isfinishLoading.value, (newval: boolean, oldval: boolean) => {
      if (isfinishLoading.value) {
        load()
      }
    })

    const statusnow = computed(() => (): number => {
      if (recOrderCart.value) {
        return recOrderCart.value.status
      }
      return 0
    })

    function mounted() {
      // Inizializza
      load()
    }

    function getOrdersCart() {
      if (props.iscash) {
        return productStore.getOrdersCartById(props.idOrdersCart)
      } else {
        return productStore.getCart()
      }

    }

    function getItemsCart() {
      const cart = getOrdersCart()
      return cart.items || null
    }

    function getNumItems(): number {
      const cart = getOrdersCart()
      if (cart.items)
        return cart.items.length || 0
      else
        return 0
    }

    function getCart(): ICart {
      return getOrdersCart()
    }

    function getNote() {
      const cart = getOrdersCart()
      return cart.note
    }

    function change_field(fieldname: string) {
      if (myrec.value[fieldname] !== oldrec.value[fieldname]) {
        myrec.value[fieldname] = oldrec.value[fieldname]

        const mydata = {
          [fieldname]: myrec.value[fieldname]
        }

        const aggiorna = fieldname !== 'status'
        tools.saveFieldToServer($q, 'carts', mycart.value._id, mydata, aggiorna)
        oldrec.value[fieldname] = myrec.value[fieldname]
      }
    }

    function myTotalPrice(): string {
      if (productStore.cart && productStore.cart.totalPrice) {
        return productStore.cart.totalPrice.toFixed(2)
      } else {
        return '0'
      }
    }

    function myTotalQty(): number {
      if (productStore.cart) {
        return productStore.cart.totalQty!
      } else {
        return 0
      }
    }

    async function load() {
      if (isfinishLoading.value) {
        console.log('Load CCART')
        mycart.value = getCart()
        myrec.value = Object.keys(mycart)
        oldrec.value = myrec.value
        note.value = mycart.value.note!

        const options = {};

        if (mycart.value) {
          recOrderCart.value = await productStore.CreateOrdersCart({ cart_id: mycart.value._id, status: 0, note: note.value })
        }

        // console.log('myrec', myrec.value)

        endload.value = true
      }
    }

    function CanBeShipped() {
      return productStore.cart.items ? productStore.cart.items.filter((rec: any) => rec.order.product.canBeShipped).length : false
    }

    function CanBeBuyOnline() {
      return productStore.cart.items ? productStore.cart.items.filter((rec: any) => rec.order.product.canBeBuyOnline).length : false
    }

    function getnumsteps() {
      let numsteps = 1

      if (CanBeShipped())
        numsteps++
      if (CanBeBuyOnline())
        numsteps++

      return numsteps
    }

    function docheckout() {

      // Può essere spedito?

      if (CanBeShipped()) {
        // mostra form di spedizione
      }

      if (CanBeBuyOnline()) {
        // mostra form di acquisto Online
      }
    }

    function completeOrder() {
      $q.dialog({
        message: t('ecomm.conferma_acq', { qty: myTotalQty() }),
        ok: {
          label: t('dialog.yes'),
          push: true
        },
        cancel: {
          label: t('dialog.cancel')
        },
        title: t('ecomm.order')
      }).onOk(async () => {
        const status = shared_consts.OrderStatus.CHECKOUT_SENT

        recOrderCart.value = await productStore.CreateOrdersCart({ cart_id: mycart.value._id, status, note: note.value })

        // statusnow.value = myordercart ? myordercart.status : 0

        if (recOrderCart.value.status === status) {
          tools.showPositiveNotif($q, t('ecomm.ord_confirmed'))
          setTimeout(() => {
            $router.push('/orderinfo')
          }, 2000)
        } else {
          tools.showNegativeNotif($q, t('ecomm.ord_not_confirmed'))
        }
        // change_field('status')
        // change_field('status')
      })
    }

    function getActualIdStorehouse(myprod: IProduct) {
      // Ottieni il negozio attualmente selezionato:
      // Se ce n'è solo 1 allora prendi quello !
      if (myprod.storehouses.length === 1) {
        return myprod.storehouses[0]._id
      } else {
        // Ottieni il negozio attualmente scelto !
        return ''
      }
    }

    function getActualGasordine(myprod: IProduct) {
      // Ottieni il negozio attualmente selezionato:
      // Se ce n'è solo 1 allora prendi quello !
      if (myprod.gasordine) {
        return myprod.gasordine._id
      } else {
        // Ottieni il gasordine attualmente scelto !
        return ''
      }
    }

    async function insertArticolo() {
      const lowerSearchText = search.value.trim();

      const myprod = productStore.getProductByCode(lowerSearchText);
      if (myprod && myprod.active) {
        const myorder: IOrder = {
          quantity: 1, quantitypreordered: 0,
          TotalPriceProduct: 0, TotalPriceProductCalc: 0, price: 0,
          idStorehouse: getActualIdStorehouse(myprod),
          idGasordine: getActualGasordine(myprod),
        }
        await productStore.addtoCartBase({ $q, t, id: myprod._id, order: myorder, addqty: true })
        search.value = ''
        load()
      }
    }

    onMounted(mounted)

    return {
      userStore,
      costanti,
      tools,
      toolsext,
      completeOrder,
      getNumItems,
      myTotalPrice,
      getItemsCart,
      getNote,
      change_field,
      note,
      statusnow,
      shared_consts,
      myTotalQty,
      recOrderCart,
      mycart,
      endload,
      search,
      insertArticolo,
      globalStore,
      isfinishLoading,
    }
  }
})
