import { defineComponent, onMounted, ref, 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 { shared_consts } from '@src/common/shared_vuejs'
// import MixinBase from '@src/mixins/mixin-base'
import { serv_constants } from '@store/Modules/serv_constants'
import { fieldsTable } from '@store/Modules/fieldsTable'

import { CSingleCart } from '../../../components/CSingleCart'
import { CTitleBanner } from '@src/components/CTitleBanner'
import { CMyFieldDb } from '@src/components/CMyFieldDb'
import { ICart, IOrder, IOrderCart } from '@src/model'

export default defineComponent({
  name: 'gestoreordini',
  components: { CSingleCart, CTitleBanner, CMyFieldDb },
  props: {},
  setup() {
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const productStore = useProducts()
    const $router = useRouter()
    const $q = useQuasar()
    const { t } = useI18n()

    const mygestord = ref(<any[] | undefined>[])
    const myarrrec = ref(<any>{})
    const myoldrec = ref(<any>{})
    const templemail = ref('')

    const storeGasordine = ref(<any>'')

    const cosa = ref(0)
    const arrout = ref(<any[]>[])

    const initialPagination = ref({
      sortBy: 'desc',
      descending: false,
      rowsPerPage: 20,
      // rowsNumber: xx if getting data from a server
    })

    const conferma_carrello = ref(false)
    const conferma_ordine = ref(false)
    const endload = ref(false)

    const taborders = ref(shared_consts.OrderStat.IN_CORSO.value)
    const columns = ref(<any>[
      {
        name: 'name',
        required: true,
        align: 'left',
        label: 'Nome Prodotto',
        field: 'nameSurname',
        sortable: true
      },
      {
        name: 'weight',
        required: true,
        label: 'Peso',
        field: 'weight',
        sortable: true
      },
      {
        name: 'price_acquistato',
        required: true,
        label: 'Prezzo (P)',
        field: 'price_acquistato',
        sortable: true
      },
      {
        name: 'totalQuantity',
        required: true,
        label: 'Qty',
        field: 'totalQuantity',
        sortable: true
      },
      {
        name: 'totalPrice_acquistato',
        required: true,
        label: 'Totale (P)',
        field: 'totalPrice_acquistato',
        sortable: true
      },
      {
        name: 'totalPrice',
        required: true,
        label: 'Totale (C)',
        field: 'totalPrice',
        sortable: true
      },
    ])

    watch(() => cosa.value, (newval, oldval) => {

    })
    watch(() => storeGasordine.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_SELGAS, storeGasordine.value)
      updateorders()
    })

    function getCols(props: any) {
      return props.cols.filter((col: any) => col.name !== 'desc')
    }

    async function getGestoreOrd() {
      const hasGasordine: any = (cosa.value === shared_consts.PROD.TUTTI) ? undefined : (cosa.value === shared_consts.PROD.GAS)
      const ris = await productStore.getGestoreOrdini({ idGasordine: storeGasordine.value })

      return ris
    }

    async function getGestoreOrdWithTotals() {
      const orderscart = await getGestoreOrd();

      if (orderscart) {
        // Calculate totals
        const totals = {
          name: 'TOTALI',
          weight: '',
          totalQuantity: orderscart.reduce((total: number, rec: any) => total + rec.totalQuantity, 0),
          totalPrice_acquistato: orderscart.reduce((total: number, rec: any) => total + rec.totalPrice_acquistato, 0),
          totalPrice: orderscart.reduce((total: number, rec: any) => total + rec.totalPrice, 0),
        };

        const rowsWithTotals: any = [...orderscart];

        if (tools.isManager()) {
          // Combine orders and totals
          rowsWithTotals.push(totals);
        }

        return rowsWithTotals;
      } else {
        return []
      }


    }

    async function updateorders() {
      mygestord.value = await getGestoreOrd()
      if (mygestord.value) {
        for (const gestord of mygestord.value) {
          myarrrec.value[gestord._id] = Object.keys(gestord)
        }
      }

      arrout.value = await getGestoreOrdWithTotals()

    }

    async function mounted() {

      storeGasordine.value = tools.getCookie(tools.COOK_SELGAS, '')

      await userStore.newsletterload(false)
      await productStore.loadProducts(true)

      taborders.value = -1

      await updateorders()

      if (taborders.value === -1)
        taborders.value = shared_consts.OrderStat.IN_CORSO.value

      endload.value = true
    }

    function CanBeShipped() {
      return productStore.cart.items!.filter((rec) => rec.order.product!.canBeShipped).length
    }

    function CanBeBuyOnline() {
      return productStore.cart.items!.filter((rec) => rec.order.product!.canBeBuyOnline).length
    }

    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
      }
    }


    onMounted(mounted)

    return {
      userStore,
      costanti,
      tools,
      toolsext,
      shared_consts,
      globalStore,
      columns,
      taborders,
      getGestoreOrd,
      updateorders,
      getCols,
      endload,
      getGestoreOrdWithTotals,
      productStore,
      t,
      initialPagination,
      cosa,
      templemail,
      fieldsTable,
      arrout,
      storeGasordine,
    }
  }
})

