import {
  defineComponent, onMounted, PropType, ref, toRef, watch,
} from 'vue'

import { IElemText, IImgGallery, ILabelValue, IMyCard, IMyElem, IMyPage, IOperators } from '@src/model'
import { useGlobalStore } from '@store/globalStore'

import { CImgTitle } from '@/components/CImgTitle'
import { CImgPoster } from '@/components/CImgPoster'
import { CTitle } from '@/components/CTitle/index'
import { tools } from '@store/Modules/tools'
import { shared_consts } from '@/common/shared_vuejs'
import { LandingFooter } from '@/components/LandingFooter'
import { COpenStreetMap } from '@src/components/COpenStreetMap'
import { CCardCarousel } from '@src/components/CCardCarousel'
import { CMyPage } from '@src/components/CMyPage'
import { CMyPageIntro } from '@src/components/CMyPageIntro'
import { CEventsCalendar } from '@src/components/CEventsCalendar'
import { CMyEditor } from '@src/components/CMyEditor'
import { CMyFieldRec } from '@src/components/CMyFieldRec'
import { CSelectImage } from '@src/components/CSelectImage'
import { CSelectAnimation } from '@src/components/CSelectAnimation'
import { CSelectColor } from '@src/components/CSelectColor'
import { CSelectFontSize } from '@src/components/CSelectFontSize'

import MixinMetaTags from '@/mixins/mixin-metatags'
import MixinBase from '@/mixins/mixin-base'
import { useQuasar } from 'quasar'
import { useI18n } from '@/boot/i18n'
import { emitKeypressEvents } from 'readline'
import { costanti } from '@costanti'
import objectId from '@src/js/objectId'

export default defineComponent({
  name: 'CMyEditElem',
  components: {
    CImgTitle, CTitle, LandingFooter, CEventsCalendar,
    CCardCarousel, COpenStreetMap, CMyPage, CMyPageIntro, CMyEditor, CMyFieldRec,
    CSelectColor, CSelectFontSize, CSelectImage, CImgPoster, CSelectAnimation
  },
  emits: ['saveElem', 'selElemClick'],
  props: {
    myelem: {
      type: Object as PropType<IMyElem>,
      required: true,
    },
    path: {
      type: String,
      required: false,
      default: '',
    },
    editOn: {
      type: Boolean,
      required: false,
      default: false,
    },
    addOn: {
      type: Boolean,
      required: false,
      default: false,
    },
  },
  setup(props, { emit }) {
    const globalStore = useGlobalStore()

    const { setmeta, getsrcbyimg } = MixinMetaTags()
    const { setValDb, getValDb } = MixinBase()


    const $q = useQuasar()
    const { t } = useI18n()

    const animare = ref(0)
    const slide = ref(0)
    const slide2 = ref(0)
    const tabCard = ref('card0')
    const tabElemsText = ref('elem0')
    const arrPages = ref([] as any[])
    const disableSave = ref(true)
    const enableEdit = ref(true)
    const elemChanged = ref(false)
    const enableAdd = ref(true)
    const tabadd = ref('tools')

    const neworder = ref(<number | undefined>0)

    const myel = toRef(props, 'myelem')
    const newtype = ref(<any>'')
    const visuadd = ref(false)

    watch(() => myel.value.order, (value, oldval) => {
      mounted()
    })

    function getArrDisciplines() {
      return globalStore.disciplines.filter((rec: any) => rec.showinhome)
    }

    function saveElem(exit?: boolean) {
      // Save Elem record
      const myelem = props.myelem
      myelem.order = neworder.value
      globalStore.saveMyElem($q, t, myelem).then((ris) => {
        if (ris) {
          // OK
          disableSave.value = true
          emit('saveElem', myelem)
          if (exit)
            elemChanged.value = false
        }
      })
    }

    function addNewElem(order?: number) {

      visuadd.value = false

      const newrec: IMyElem = {
        _id: undefined,
        type: newtype.value,
        path: props.myelem.path,
        order: order ? order : 1000,
        active: true,
        container: ''
      }

      if (newrec.type === shared_consts.ELEMTYPE.CAROUSEL_IMGS) {
        newrec.container2 = '8'
        newrec.height = 600
      } else if (newrec.type === shared_consts.ELEMTYPE.CARD) {
        newrec.class2 = 'row justify-center'
      }

      globalStore.addNewElem($q, t, newrec)

      emit('selElemClick', newrec)
    }

    function dupElem(order?: number) {

      const newrec = props.myelem

      newrec._id = undefined
      newrec.order = order ? order : newrec.order! + 10

      globalStore.addNewElem($q, t, newrec)
    }

    function delElem() {
      $q.dialog({
        message: 'Eliminare ' + props.myelem.container + ' ?',
        html: true,
        ok: {
          label: 'Elimina',
          push: true,
        },
        title: '',
        cancel: true,
        persistent: false,
      }).onOk(async () => {

        // Save Elem record
        await globalStore.delMyElem($q, t, props.myelem).then((ris) => {
          if (ris) {
            // OK
            disableSave.value = true
          }
        })
      })

    }

    function modifElem() {
      disableSave.value = false
      elemChanged.value = true
    }

    function mounted() {
      neworder.value = props.myelem.order

      arrPages.value = []
      arrPages.value.push({ label: '[Vuoto]', path: '' })
      for (const page of globalStore.mypage) {

        const rec = {
          // @ts-ignore
          label: page.title,
          // @ts-ignore
          value: page.path
        }
        arrPages.value.push(rec)
      }

      if (props.myelem)
        newtype.value = props.myelem.type
    }

    function clickOnElem() {
      if (props.editOn) {
      }
    }

    function addNewCard() {
      if (!myel.value.listcards)
        myel.value.listcards = []

      myel.value.listcards.push({ _id: objectId(), imagefile: '', alt: '', description: '' })
      modifElem()


    }

    function addNewElemText() {
      if (!myel.value.elemsText)
        myel.value.elemsText = []

      myel.value.elemsText.push({ _id: objectId(), text: '', color: '#ffffff', class: '', size: '', anim: { name: 'FadeIn', clduration: '', cldelay: '', timingtype: 'ease-in-out'}  })
      modifElem()
    }

    function getClass() {
      let mycl = ''
      if (props.myelem.align === shared_consts.ALIGNTYPE.CEHTER) {
        mycl += ' align_center'
      } else if (props.myelem.align === shared_consts.ALIGNTYPE.RIGHT) {
        mycl += ' align_right'
      } else if (props.myelem.align === shared_consts.ALIGNTYPE.LEFT) {
        mycl += ' align_left'
      }

      return mycl
    }

    function showFit() {
      if (props.myelem.type)
        return [shared_consts.ELEMTYPE.TEXT].includes(props.myelem.type)
      else
        return false
    }

    function delRecCard(id: string, myel: IMyElem) {
      //
      if (props.myelem.type === shared_consts.ELEMTYPE.CARD) {
        if (myel.listcards)
          myel.listcards = myel.listcards.filter((card: IMyCard) => card._id !== id)
      } else if (props.myelem.type === shared_consts.ELEMTYPE.IMGPOSTER) {
        if (myel.elemsText)
          myel.elemsText = myel.elemsText.filter((rec: IElemText) => rec._id !== id)
      }

    }

    function saveCard(recpass: IMyCard, myval: any) {
      if (props.myelem.type === shared_consts.ELEMTYPE.CARD) {
        if (props.myelem.listcards) {
          props.myelem.listcards.forEach((rec: IMyCard) => {
            if (recpass._id === rec._id) {
              rec.imagefile = myval
            }
          })
        }
      } else if (props.myelem.type === shared_consts.ELEMTYPE.IMGPOSTER) {
        if (props.myelem.elemsText) {
          props.myelem.elemsText.forEach((rec: IElemText) => {
            if (recpass._id === rec._id) {
              rec.text = myval
            }
          })
        }
      } else if ((props.myelem.type === shared_consts.ELEMTYPE.IMGTITLE) ||
                (props.myelem.type === shared_consts.ELEMTYPE.IMAGE)) {
        myel.value.image = myval
      }
      modifElem()
    }

    function showAnimation() {
      return (myel.value.type === shared_consts.ELEMTYPE.IMAGE)
      || (myel.value.type === shared_consts.ELEMTYPE.IMGTITLE)
      || (myel.value.type === shared_consts.ELEMTYPE.TEXT)
      || (myel.value.type === shared_consts.ELEMTYPE.CARD)
      || (myel.value.type === shared_consts.ELEMTYPE.HTML)
      || (myel.value.type === shared_consts.ELEMTYPE.CAROUSEL_IMGS)
    }

    function updateElem(myvalue: any) {
      console.log('updateElem', myvalue)
      if (myel.value.type === shared_consts.ELEMTYPE.IMGTITLE) {
        myel.value.container = myvalue
      }
      modifElem()
    }

    onMounted(mounted)

    return {
      tools,
      shared_consts,
      getArrDisciplines,
      slide,
      slide2,
      animare,
      setmeta,
      getsrcbyimg,
      saveElem,
      myel,
      disableSave,
      modifElem,
      delElem,
      addNewElem,
      newtype,
      neworder,
      elemChanged,
      enableAdd,
      clickOnElem,
      getClass,
      showFit,
      getValDb,
      dupElem,
      enableEdit,
      addNewCard,
      addNewElemText,
      arrPages,
      costanti,
      delRecCard,
      saveCard,
      updateElem,
      showAnimation,
      tabCard,
      tabElemsText,
      visuadd,
      tabadd,
    }
  },

})
