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 { IBaseOrder, IOrder, IOrderCart, IProduct } from '@src/model/Products';
import { ICart, IShareWithUs } from '@src/model/Products'

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

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


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

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

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

    const search = ref('')
    const editOn = ref(false)

    const allTotalPrice = ref(<number | undefined>undefined);

    watch(allTotalPrice, (newValue: any) => {
      if (!newValue)
        recOrderCart.value.totalPrice = 0
      else
        recOrderCart.value.totalPrice = parseFloat(newValue);
    });


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

    function mounted() {
      // Inizializza
      load()

      allTotalPrice.value = recOrderCart.value.totalPrice
    }

    function getItems(): IBaseOrder[] | [] {
      return recOrderCart.value.items ?? []
    }

    function getNumItems(): number {
      const itemsord = getItems()
      if (itemsord)
        return itemsord.length || 0
      else
        return 0
    }

    function change_field(fieldname: any) {
      // console.log('myrec', recOrderCart.value)

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

      const aggiorna = false
      tools.saveFieldToServer($q, 'orderscarts', recOrderCart.value._id, mydata, aggiorna)
    }

    function myTotalPrice(): string {
      if (recOrderCart.value) {
        return recOrderCart.value.totalPrice.toFixed(2)
      } else {
        return '0'
      }
    }

    function myTotalPriceCalc(): string {
      if (recOrderCart.value) {
        return recOrderCart.value.totalPriceCalc ? recOrderCart.value.totalPriceCalc.toFixed(2) : ''
      } else {
        return '0'
      }
    }

    function myTotalQty(): number {
      if (recOrderCart.value) {
        return recOrderCart.value.totalQty
      } else {
        return 0
      }
    }

    function load() {
      endload.value = false
      recOrderCart.value = productStore.getOrdersCartById(props.idOrdersCart)
      if (recOrderCart.value) {
        oldrec.value = recOrderCart.value
        myrec.value.note = recOrderCart.value.note!
        myrec.value.note_per_gestore = recOrderCart.value.note_per_gestore!
        myrec.value.note_per_admin = recOrderCart.value.note_per_admin!
      }
      allTotalPrice.value = recOrderCart.value.totalPrice
      endload.value = true
    }

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

    function CanBeBuyOnline() {
      return recOrderCart.value.items ? recOrderCart.value.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 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()
      }
    }

    async function updateOrdersCart(paramstoupdate: any) {
      await productStore.updateOrdersCartById(props.idOrdersCart, paramstoupdate)

    }

    function ordersUpdated() {
      console.log('ordersUpdated')
      load()
    }

    function changeTotalPrice() {


      change_field('totalPrice')
    }

    function updateTotalPrice() {
      updateOrdersCart({ totalPrice: allTotalPrice.value })
    }



    onMounted(mounted)

    return {
      userStore,
      costanti,
      tools,
      toolsext,
      getNumItems,
      myTotalPrice,
      getItems,
      change_field,
      statusnow,
      shared_consts,
      myTotalQty,
      recOrderCart,
      endload,
      search,
      insertArticolo,
      updateOrdersCart,
      ordersUpdated,
      t,
      editOn,
      allTotalPrice,
      changeTotalPrice,
      updateTotalPrice,
      myTotalPriceCalc,
      myrec,
    }
  }
})
