import { inject, defineComponent, PropType, ref, watch, toRef, onMounted, toRefs, computed } from 'vue'
import { useI18n } from 'vue-i18n'

import { tools } from '../../store/Modules/tools'

import { fieldsTable } from '@store/Modules/fieldsTable'

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

import type {
  ISearchList
} from 'model';
import {
  IColGridTable,
  IFilter,
  ITableRec,
  IPagination,
  IParamDialog,
  IMySkill
} from 'model'
import { lists } from '@store/Modules/lists'
import { IParamsQuery } from 'model'
import { CMyPopupEdit } from '../CMyPopupEdit'
import { CMyFriends } from '../CMyFriends'
import { CMyUser } from '../CMyUser'
import { CMyGroups } from '../CMyGroups'
import { CMyFieldDb } from '../CMyFieldDb'
import { CMyRecCard } from '../CMyRecCard'
import { CMyRecGrpCard } from '../CMyRecGrpCard'
import { CMyRecCircuitCard } from '../CMyRecCircuitCard'
import { CMySelect } from '../CMySelect'
import { CTitleBanner } from '../CTitleBanner'

import { useUserStore } from '@store/UserStore'
import { useGlobalStore } from '@store/globalStore'
import { useQuasar, exportFile } from 'quasar'
import { costanti } from '@costanti'
import translate from '@src/globalroutines/util'
import { toolsext } from '@store/Modules/toolsext'
import { CMyCardPopup } from '@src/components/CMyCardPopup'
import { CMyCardGrpPopup } from '@src/components/CMyCardGrpPopup'
import { CMyCardCircuitPopup } from '@src/components/CMyCardCircuitPopup'
import { useRouter } from 'vue-router'
import { table } from 'console'
import { globals } from 'jest.config'

export default defineComponent({
  name: 'CBarSelection',
  props: {
    ind: {
      type: Number,
      required: false,
      default: -1,
    },
    table: {
      type: String,
      required: true,
    },
    prop_search: {
      type: Boolean,
      required: false,
      default: true,
    },
    mytitle: {
      type: String,
      required: false,
      default: '',
    },
    myicon: {
      type: String,
      required: false,
      default: '',
    },
    mycolor: {
      type: String,
      required: false,
      default: '',
    },
    hint: {
      type: String,
      required: false,
      default: 'Cerca',
    },
  },
  components: {
    CMyPopupEdit, CTitleBanner, CMyFieldDb, CMySelect, CMyFriends, CMyGroups,
    CMyUser, CMyRecCard, CMyCardPopup, CMyRecGrpCard, CMyCardGrpPopup, CMyCardCircuitPopup,
    CMyRecCircuitCard
  },
  emits: ['clickButtBar'],
  setup(props, { emit }) {
    const $q = useQuasar()
    const { t } = useI18n()
    const userStore = useUserStore()
    const globalStore = useGlobalStore()
    const isfinishLoading = computed(() => globalStore.finishLoading)

    const $router = useRouter()

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

    const visupagedialog = ref(false)
    const myrecdialog = ref(null)

    const myinfscroll = ref(null)

    const serverData: any = ref([])
    const numRecLoaded = ref(0)
    const changetable = ref(false)
    const filtri = ref(false)
    const searchList = ref([] as ISearchList[])

    const actual = ''

    const tablesel = ref('')
    const iconsel = computed(() => {
      const myarr: any = tools.getoptionsMainCards(false)
      if (myarr) {
        const rec = myarr.find((rec: any) => rec.value === tablesel.value)

        if (rec) {
          return rec.icon
        }
      }
      return ''
    })
    const colorsel = computed(() => {
      const myarr: any = tools.getoptionsMainCards(false)
      if (myarr) {
        const rec = myarr.find((rec: any) => rec.value === tablesel.value)

        if (rec) {
          return rec.color
        }
      }
      return ''
    })
    const myfilter = ref('')
    const myfilterand: any = ref([])
    const rowsel: any = {}
    const dark = true
    const canEdit = ref(false)
    const optionsMainCards = ref()

    const returnedCount = 0
    const colVisib: any = ref([])
    const colExtra: any = ref([])
    const actualDate: any = ref(null as any)

    const rowclicksel = ref(null as any)
    const colclicksel = ref(null)

    const selector = inject('selector', {})
    const showfilter = ref(false)  // filtri avanzati

    const filter = ref(0)
    const filtergrp = ref(costanti.MY_GROUPS)

    const mycolumns = ref([])

    const valoriopt = computed(() => (item: any, addall: boolean, addnone: boolean) => {
      // console.log('valoriopt', item.table)
      return globalStore.getTableJoinByName(item.table, addall, addnone, item.filter)
    })

    watch(() => props.table, (newval, oldval) => {
      tablesel.value = props.table
      // console.log('CHANGE TABLESEL', tablesel.value)
    })

    watch(() => globalStore.myselector.data, (newval, oldval) => {
      const rec = searchList.value.find((myrec) => myrec.table === shared_consts.TAB_CITIES) // check if exist
      if (rec) {
        rec.value = globalStore.myselector.data
      }

    })

    const labelcombo = computed(() => (item: any) => {
      let lab = item.label
      if (item.showcount)
        lab += ' (' + valoriopt.value(item, false, false).length + ')'
      return lab
    })

    const myselector = computed({
      get: () => globalStore.myselector,
      set: val => {
        globalStore.myselector = val
      },
    })

    function refresh() {
      //
      // emit('updatesearch', )
    }

    function setProvinceByRegion(tableprov: string, tabregion: string, newval: any) {

      const recRegion = searchList.value.find((rec) => rec.table === tabregion)
      if (recRegion)
        tools.setCookie(tools.COOK_SEARCH + costanti.FILTER_SEP + props.table + costanti.FILTER_SEP + tabregion, newval)

      for (const item of searchList.value) {
        if (item.table === tableprov) {
          const valsaved = tools.getCookie(tools.COOK_SEARCH + costanti.FILTER_SEP + props.table + costanti.FILTER_SEP + item.table + costanti.FILTER_SEP + newval, costanti.FILTER_TUTTI)
          const rec = searchList.value.find((myrec) => myrec.table === tableprov) // check if exist
          let trovato = false
          let arrvalues = []
          if (rec) {
            arrvalues = valoriopt.value(rec.value, false, false)
            if (arrvalues)
              trovato = arrvalues.find((myrec: any) => myrec[myrec.key] === valsaved)
          }
          if (valsaved && trovato)
            item.value = valsaved
          else {
            if (arrvalues) {
              item.value = costanti.FILTER_TUTTI_STR
            }
          }
        } else if (item.table === shared_consts.TAB_CITIES) {
          const valsaved = tools.getCookie(tools.COOK_SEARCH + costanti.FILTER_SEP + item.table + costanti.FILTER_SEP + newval, costanti.FILTER_TUTTI)
          const rec = searchList.value.find((myrec) => myrec.table === shared_consts.TAB_CITIES) // check if exist
          let trovato = false
          let arrvalues = []
          if (rec) {
            arrvalues = valoriopt.value(rec.value, false, false)
            if (arrvalues)
              trovato = arrvalues.find((myrec: any) => myrec[myrec.key] === valsaved)
          }
          if (valsaved && trovato)
            item.value = valsaved
          else {
            if (arrvalues) {
              item.value = costanti.FILTER_TUTTI
            }
          }
        }
      }

    }

    function searchval(newval: any, table: any, tablesel: any) {
      // console.log('REFRR searchval', newval, table, 'tablesel', tablesel)

      globalStore.myselector = { table, data: newval }
      // console.log('globalStore.myselector', globalStore.myselector)
      tools.setCookie(tools.COOK_SEARCH + costanti.FILTER_SEP + props.table + costanti.FILTER_SEP + table, newval)

      if (table === toolsext.TABREGIONS) {
        setProvinceByRegion(toolsext.TABPROVINCE, table, newval)
      } else if (table === toolsext.TABGOODS) {
        const recSector = searchList.value.find((rec) => rec.table === toolsext.TABSECTORGOODS)
        if (recSector) {
          tools.setCookie(tools.COOK_SEARCH + costanti.FILTER_SEP + props.table + costanti.FILTER_SEP + recSector.value, newval)
        }
        // setCategBySector('sectorgoods', table, newval)
      }


      refresh()
    }

    function getRowsNumberCount() {

      return returnedCount
    }


    function created() {
      //

    }

    function doSearch() {
      //  console.log('REFRR - doSearch')
      refresh()
    }

    function toHome() {
      $router.push('/')
    }

    function mounted() {

      optionsMainCards.value = tools.getoptionsMainCards(false)

      tablesel.value = props.table

      // console.log(' . TABLE =', props.table)
      mycolumns.value = fieldsTable.getArrColsByTable(props.table)

      searchList.value = [
        {
          label: 'Comune',
          table: 'cities',
          key: 'idCity',
          type: costanti.FieldType.select_by_server,
          value: tools.getCookie(tools.COOK_SEARCH + 'cities', costanti.FILTER_TUTTI),
          addall: true,
          arrvalue: [],
          useinput: true,
          filter: null,
          tablesel: 'cities',
        },
      ]
    }

    function visButtRow() {
      return true
    }

    function gotoPageSel() {
      const rec = costanti.MAINCARDS.find((rec: any) => rec.table === tablesel.value)
      if (rec) {
        $router.push(rec.to)
      }
    }

    function createNewRecordDialog() {
      globalStore.addNewRecord = tablesel.value
    }

    function clickButtBar(item: any) {
      emit('clickButtBar', item)
    }

    created()
    onMounted(mounted)

    return {
      isfinishLoading,
      search,
      canEdit,
      rowclicksel,
      colVisib,
      colExtra,
      colclicksel,
      loading,
      serverData,
      myfilter,
      lists,
      myfilterand,
      tools,
      costanti,
      toolsext,
      fieldsTable,
      globalStore,
      searchList,
      searchval,
      valoriopt,
      labelcombo,
      filter,
      filtergrp,
      shared_consts,
      showfilter,
      visupagedialog,
      myrecdialog,
      actualDate,
      actual,
      numRecLoaded,
      myinfscroll,
      t,
      mycolumns,
      visButtRow,
      doSearch,
      myselector,
      optionsMainCards,
      tablesel,
      gotoPageSel,
      createNewRecordDialog,
      toHome,
      iconsel,
      filtri,
      clickButtBar,
      colorsel,
    }
  }
})
