import { defineComponent, onMounted, ref, watch } from 'vue'
import { tools } from '@store/Modules/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, exportFile } 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 { CMyDialog } from '../../../components/CMyDialog'
import { COrdersCart } from '../../../components/COrdersCart'
import { CTitleBanner } from '../../../components/CTitleBanner'
import { CMyFieldDb } from '../../../components/CMyFieldDb'
import type { ISingleProductOrdered } from '@src/model'
import type { IOrderCart } from '@src/model'

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

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

    const cosa = ref(0)
    const showOrdersCart = ref(false)
    const idOrdersCartToShow = ref('')

    const arrout = ref(<any[]>[])
    const listatotali = ref(<any[]>[])

    const showWhichCode = ref(shared_consts.ShowCode.ALL)

    const showWhichCodeOptions = ref([
      {
        label: 'Tutti i codici',
        value: shared_consts.ShowCode.ALL
      },
      {
        label: 'Codice Interno',
        value: shared_consts.ShowCode.CODE
      },
      {
        label: 'Codice Produttore',
        value: shared_consts.ShowCode.INTERNAL_CODE
      }
    ])

    const check_send_email = ref(false)
    const mostra_codice = ref(false)
    const mostra_cat = ref(false)
    const mostra_solo_ordini_produttore = ref(false)

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

    const totalPagination = ref({
      sortBy: 'codice_interno',
      descending: false,
      rowsPerPage: 1000,
      // rowsNumber: xx if getting data from a server
    })

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

    const storeGasordine = ref(<any>'')

    const taborders = ref(shared_consts.OrderStat.IN_CORSO.value)
    const tabpages = ref(shared_consts.OrderPages.LISTA_TOTALI.value)
    const statusnow = ref(0)
    const arrnumstatus = ref(<any[]>[])

    const columns_listafiltrati = ref(<any>[])

    //index, code, productName, qty, singlePrice, subtotalPrice
    const columns_listaTotali = ref(<any>[
      {
        name: 'index',
        required: true,
        align: 'left',
        label: 'Indice',
        field: 'index',
        sortable: true
      },
      {
        name: 'code',
        required: true,
        align: 'left',
        label: 'Codice',
        field: 'code',
        sortable: true
      },
      {
        name: 'codice_interno',
        required: false,
        align: 'left',
        label: 'Codice Produttore',
        field: 'codice_interno',
        sortable: true,
      },
      {
        name: 'productName',
        required: true,
        align: 'left',
        label: 'Prodotto',
        field: 'productName',
        sortable: true
      },
      {
        name: 'strSubCatProds',
        required: true,
        align: 'left',
        label: 'Categoria',
        field: 'strSubCatProds',
        sortable: true
      },
      {
        name: 'qty',
        required: true,
        align: 'center',
        label: 'Qta',
        field: 'qty',
        sortable: true
      },
      {
        name: 'singlePrice',
        required: true,
        align: 'center',
        label: 'Prezzo',
        field: 'singlePrice',
        sortable: true,
      },
      {
        name: 'subtotalPrice',
        required: true,
        align: 'center',
        label: 'Totale',
        field: 'subtotalPrice',
        sortable: true
      }

    ])

    const columns = ref(<any>[
      {
        name: 'ind',
        required: true,
        align: 'left',
        label: 'Ind',
        field: 'ind',
        sortable: true
      },
      {
        name: 'apri',
        align: 'center',
        required: false,
        label: 'Apri',
        field: 'apri',
        sortable: false
      },
      {
        name: 'numorder',
        required: true,
        align: 'left',
        label: 'Ordine N.',
        field: 'numorder',
        sortable: true
      },
      {
        name: 'created_at',
        required: true,
        align: 'center',
        label: 'Effettuato il',
        field: 'created_at',
        sortable: true
      },
      {
        name: 'items',
        required: true,
        label: '',
        field: 'items',
        sortable: true
      },
      {
        name: 'totalPrice',
        required: true,
        label: 'Totale',
        field: 'totalPrice',
        sortable: true
      },
      {
        name: 'status',
        align: 'center',
        required: true,
        label: 'Stato',
        field: 'status',
        sortable: true
      }
    ])

    const columns_Admin = ref(<any>[
      {
        name: 'ind',
        required: true,
        align: 'left',
        label: 'Ind',
        field: 'ind',
        sortable: true
      },
      {
        name: 'apri',
        align: 'center',
        required: false,
        label: 'Apri',
        field: 'apri',
        sortable: false
      },
      {
        name: 'comandi',
        align: 'center',
        required: false,
        label: 'Comandi',
        field: 'comandi',
        sortable: false
      },
      {
        name: 'numorder',
        required: true,
        align: 'left',
        label: 'Ordine N.',
        field: 'numorder',
        sortable: true
      },
      {
        name: 'nameSurname',
        required: true,
        align: 'left',
        label: 'Nome',
        field: 'nameSurname',
        sortable: true
      },
      {
        name: 'created_at',
        required: true,
        align: 'center',
        label: 'Effettuato il',
        field: 'created_at',
        sortable: true
      },
      {
        name: 'items',
        required: true,
        label: 'Articoli',
        field: 'items',
        sortable: true
      },
      {
        name: 'totalPrice',
        required: true,
        label: 'Totale',
        field: 'totalPrice',
        sortable: true
      },
      {
        name: 'status',
        align: 'center',
        required: true,
        label: 'Stato',
        field: 'status',
        sortable: true
      },
    ])

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

    watch(() => taborders.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_TABORD, taborders.value.toString())
      updateorders(false)
    })
    watch(() => tabpages.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_TABPAGES, tabpages.value.toString())
      if (tabpages.value === shared_consts.OrderPages.LISTA_TOTALI.value) {
        taborders.value = -1
      }
      updateorders(true)
    })

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

    watch(() => mostra_codice.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_SHOWCODICE, mostra_codice.value ? '1' : '0')
      updateorders(true, true)
    })
    watch(() => mostra_cat.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_SHOWCAT, mostra_cat.value ? '1' : '0')
      updateorders(true, true)
    })
    watch(() => showWhichCode.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_SHOWCODE, showWhichCode.value.toString())
      updateorders(true, true)
    })

    watch(() => mostra_solo_ordini_produttore.value, (newval, oldval) => {
      tools.setCookie(tools.COOK_SHOWORDPROD, mostra_solo_ordini_produttore.value ? '1' : '0')
      updateorders(false, true)
    })

    // const { setValDb, getValDb } = MixinBase()

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

    function getOrdersCart(): IOrderCart[] | undefined {
      const hasGasordine: any = (cosa.value === shared_consts.PROD.TUTTI) ? undefined : (cosa.value === shared_consts.PROD.GAS)
      const ris = productStore.getOrdersCart(taborders.value, hasGasordine, storeGasordine.value)

      return ris
    }

    // Creami una lista di tutti i prodotti, con i totali delle quantità e il prezzo totale
    function getListProductBySumQuantity(): ISingleProductOrdered[] {
      const listproductstotal = productStore.getListProductBySumQuantity(storeGasordine.value)

      if (listproductstotal) {
        // Calculate totals
        const totals: ISingleProductOrdered = {
          index: -1,
          code: '',
          codice_interno: '',
          idProduct: '',
          subCat: '',
          strSubCatProds: '',
          productName: 'TOTALI',
          qty: listproductstotal.reduce((total: number, rec: any) => total + rec.qty, 0),
          singlePrice: 0,
          subtotalPrice: listproductstotal.reduce((total: number, rec: any) => total + rec.subtotalPrice, 0),
        };

        let rowsWithTotals: any = [...listproductstotal];

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

        // Supponendo che rowsWithTotals sia il tuo array di record
        rowsWithTotals.forEach((record: any, index: number) => {
          record.ind = index;
        });

        return rowsWithTotals;
      }

      return listproductstotal
    }

    function getTotaleOrdineByOrdId(id: string, idGasordine: string, totale: boolean): string {
      return productStore.getTotaleOrdineByOrdId(id, idGasordine, totale, mostra_solo_ordini_produttore.value, taborders.value).toFixed(2)
    }

    function getOrdersCartWithTotals(): any[] {
      const orderscart = getOrdersCart();

      if (orderscart && taborders.value > 0) {
        // Calculate totals
        const totals = {
          created_at: new Date(),
          items: null,
          user: {
            name: 'TOTALI',
            surname: '',
            email: '',
          },
          status: 0,
          // Add other properties as needed
          totalPrice: orderscart.reduce((total: number, rec: any) => total + rec.totalPrice, 0),
          totalPriceCalc: orderscart.reduce((total: number, rec: any) => total + rec.totalPriceCalc, 0),
        };

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

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

        // Supponendo che rowsWithTotals sia il tuo array di record
        rowsWithTotals.forEach((record: any, index: number) => {
          record.ind = index;
        });

        return rowsWithTotals;
      } else {
        return []
      }


    }

    function getAllOrdersCart() {
      return productStore.getOrdersAllCart(storeGasordine.value)
    }

    function updateorders(updatetab: boolean, notupdatetabsel: boolean) {

      // Rimuovi dalla lista columns_listaTotali il record "codice_interno" se mostra_codice.value = false
      columns_listafiltrati.value = columns_listaTotali.value.filter((column: any) => {
        let show = false
        if (showWhichCode.value === shared_consts.ShowCode.ALL) {
          show = true
        } else if (showWhichCode.value === shared_consts.ShowCode.CODE) {
          show = (column.name !== 'codice_interno')
        } else if (showWhichCode.value === shared_consts.ShowCode.INTERNAL_CODE) {
          show = (column.name !== 'code')
        }
        return show
      })


      if (tabpages.value === shared_consts.OrderPages.ORDINI.value) {
        arrout.value = []

        myorderscart.value = getOrdersCart()
        if (myorderscart.value) {
          for (const orderscart of myorderscart.value) {
            myarrrec.value[orderscart._id] = Object.keys(orderscart)
          }
        }

        if (updatetab) {
          const allorders = getAllOrdersCart()
          for (const status of [15, 2, 3, 4, 5, 6, 7, 8, 10]) {
            arrnumstatus.value[status] = allorders.filter((rec) => (rec.status === status)).reduce((sum, item) => sum + 1, 0)
          }

          if (!notupdatetabsel)
            selectfirstavailable()
        }

        arrout.value = getOrdersCartWithTotals()
      } else if (tabpages.value === shared_consts.OrderPages.LISTA_TOTALI.value) {
        listatotali.value = getListProductBySumQuantity()
      }
    }

    function selectfirstavailable() {

      taborders.value = -1
      Object.keys(arrnumstatus.value).forEach((stat: any) => {
        if (arrnumstatus.value[stat] > 0) {
          if (taborders.value === -1)
            taborders.value = parseInt(stat)
        }
      })
    }

    async function mounted() {

      taborders.value = tools.getCookie(tools.COOK_TABORD, shared_consts.OrderStat.IN_CORSO.value, true)
      if (tools.isManager())
        tabpages.value = tools.getCookie(tools.COOK_TABPAGES, shared_consts.OrderPages.LISTA_TOTALI.value, true)
      else
        tabpages.value = shared_consts.OrderPages.ORDINI.value

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

      mostra_codice.value = tools.getCookie(tools.COOK_SHOWCODICE, '1') === '1'
      mostra_cat.value = tools.getCookie(tools.COOK_SHOWCAT, '1') === '1'
      mostra_solo_ordini_produttore.value = tools.getCookie(tools.COOK_SHOWORDPROD, '1') === '1'
      showWhichCode.value = tools.getCookie(tools.COOK_SHOWCODE, shared_consts.ShowCode.ALL, true)

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

      updateorders(true)

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

      if (tabpages.value === -1)
        tabpages.value = shared_consts.OrderPages.LISTA_TOTALI.value


      if (tools.isManager()) {
        columns.value = [...columns_Admin.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
      }
    }

    function nextstep() {
      return 0
    }

    function clickFunz(order: IOrderCart, status: number) {

      if (status === shared_consts.OrderStatus.ORDER_CONFIRMED) {
        // Conferma Ordine
      }

      const statusStr = shared_consts.getStatusStr(status)

      $q.dialog({
        message: 'Impostare l\'ordine di ' + tools.getNomeUtenteByRecUser(order.user!) + ' n. ' + order.numorder + ' ' + statusStr + ' ?',
        ok: {
          label: t('dialog.yes'),
          push: true
        },
        cancel: {
          label: t('dialog.cancel')
        },
        title: 'Ordine'
      }).onOk(async () => {

        statusnow.value = await productStore.UpdateOrderCartStatus({ order_id: order._id, status, sendmail: check_send_email.value })

        if (statusnow.value === status) {
          order.status = statusnow.value
          updateorders(true)
          tools.showPositiveNotif($q, 'Ordine ' + statusStr)
        }

        // Se l'ordine è stato PAGATO, controllo se è stato consegnato
        if (status === shared_consts.OrderStatus.DELIVERED) {
          if (!order.pagato) {
            clickFunz(order, shared_consts.OrderStatus.PAYED)
          }
        }

        // change_field('status')
        // change_field('status')
      })
    }

    function sendMailToAll() {
      const orders = arrout.value

      let res = null
      let inviate = 0

      $q.dialog({
        message: 'Inviare la email ' + templemail.value + ' a tutti ?',
        ok: {
          label: t('dialog.yes'),
          push: true
        },
        cancel: {
          label: t('dialog.cancel')
        },
        title: 'Ordine'
      }).onOk(async () => {


        for (const ord of orders) {
          res = await productStore.sendMailToTheBuyer(ord._id, templemail.value, false)
          if (res && res.emailsend)
            inviate++
        }

        if (inviate > 0) {
          tools.showPositiveNotif($q, t('orderscart.email_sent', { inviate }))
        } else {
          tools.showNegativeNotif($q, t('orderscart.email_not_send'))
        }
      })

    }

    async function sendMailTest() {
      const orders = arrout.value

      if (orders && orders.length > 0) {
        const res = await productStore.sendMailToTheBuyer(orders[0]._id, templemail.value, true)

        if (res && res.emailsend) {
          tools.showPositiveNotif($q, t('reset.email_sent'))
        } else {
          tools.showNegativeNotif($q, t('orderscart.email_not_send'))
        }
      }

    }

    async function CambiaStatoaTutti(status: number) {

      for (const order of arrout.value) {
        statusnow.value = await productStore.UpdateOrderCartStatus({ order_id: order._id, status, sendmail: check_send_email.value })
      }

      updateorders(true)
    }

    function ConfermaOrdini() {

      let conemail = 'ed inviare le Email di Conferma'
      if (!check_send_email.value)
        conemail = 'senza inviare le Email di Conferma'

      $q.dialog({
        message: 'Confermare tutti gli Ordini ' + conemail + '?',
        ok: {
          label: t('dialog.yes'),
          push: true
        },
        cancel: {
          label: t('dialog.cancel')
        },
        title: 'Ordine'
      }).onOk(async () => {
        await CambiaStatoaTutti(shared_consts.OrderStatus.ORDER_CONFIRMED)
      })
    }

    function exportListaTotali() {
      // console.log('row', serverData.value)
      // console.log('mycolumns.value', mycolumns.value)
      // naive encoding to csv format
      const content = [columns_listafiltrati.value.map((col: any) => (col.label))].concat(
        listatotali.value.map((row: any) => columns_listafiltrati.value.map((col: any) => (
          row[col.field]
        )).join(','))
      ).join('\r\n')

      const status = exportFile(
        'lista-totali-' + productStore.getGasordineNameById(storeGasordine.value) + '_' + tools.getstrYYMMDDDate(tools.getDateNow()) + '.csv',
        content,
        'text/csv'
      )

      if (status !== true) {
        $q.notify({
          message: 'Il Browser ha negato il download del file.',
          color: 'negative',
          icon: 'warning'
        })
      }
    }

    onMounted(mounted)

    return {
      userStore,
      costanti,
      tools,
      toolsext,
      shared_consts,
      globalStore,
      columns,
      taborders,
      tabpages,
      arrnumstatus,
      clickFunz,
      getOrdersCart,
      getAllOrdersCart,
      updateorders,
      getCols,
      endload,
      getOrdersCartWithTotals,
      productStore,
      t,
      initialPagination,
      cosa,
      sendMailToAll,
      sendMailTest,
      templemail,
      fieldsTable,
      storeGasordine,
      arrout,
      check_send_email,
      ConfermaOrdini,
      mostra_codice,
      mostra_cat,
      mostra_solo_ordini_produttore,
      listatotali,
      columns_listafiltrati,
      showWhichCode,
      showWhichCodeOptions,
      getTotaleOrdineByOrdId,
      showOrdersCart,
      idOrdersCartToShow,
      exportListaTotali,
      totalPagination,
    }
  }
})

