<template>
  <AdminLayout>
    <Breadcrumb current-page-text="Popup Yonetimi" />
    <div class="form-content">
      <div class="form-inner-content form-inner-content-left">
        <div class="form-part">
          <div class="form-part-title">
            <h4>
              {{ Number(route.params.menuId) === 1 ? 'Ana Menü' : 'Footer Menü' }}
            </h4>
            <div class="form-part-title-buttons">
              <div class="button-c button-save" @click="SaveMenu">Kaydet</div>
            </div>
          </div>
          <div class="form-part-content">
            <template v-if="loaded">
              <template v-if="siteManagementMenuStore.menuContentList.length > 0">
                <div class="form-inner-comment">
                  Menü öğelerini sürükle-bırak yaparak düzenleyebilirsiniz.
                </div>
                <draggable
                  class="menu-list-group"
                  :list="siteManagementMenuStore.menuContentList"
                  :group="{ name: 'menu', put: false }"
                  itemKey="id"
                  @end="ChangeMenu">
                  <template #item="{ element, index }">
                    <div class="menu-list-item">
                      <span>{{ element.title }}</span>
                      <div class="menu-list-item-buttons">
                        <button
                          @click="EditMenu(element, index)"
                          v-if="element.pageId === null">
                          Düzenle
                        </button>
                        <button
                          @click="RemoveFromMenu(element, index)"
                          class="button-alert">
                          Sil
                        </button>
                      </div>
                    </div>
                  </template>
                </draggable>
              </template>
              <template v-else>
                <div class="form-inner-comment">
                  Menüye henüz öğe eklenmemiş. Sağdaki bölümden öğe ekleyebilirsiniz.
                </div>
              </template>
            </template>
          </div>
        </div>
      </div>
      <div class="form-inner-content form-inner-content-right">
        <div class="form-part">
          <div class="form-part-title">
            <h4>Sayfalar</h4>
            <div class="form-part-title-buttons">
              <div class="button-c button-save" @click="AddMenuItem">Menü Öğesi Ekle</div>
            </div>
          </div>
          <div class="form-part-content">
            <div class="menu-list-group">
              <template v-for="(page, i) in pageList">
                <div v-if="page.show" class="menu-list-item menu-list-item-page">
                  <span>{{ page.title }}</span>
                  <div class="menu-list-item-buttons">
                    <button @click="AddToMenu(page, i)">Menüye Ekle</button>
                  </div>
                </div>
              </template>
            </div>
          </div>
        </div>
      </div>
    </div>
    <panel-wrapper
      wide
      v-if="menuItemPanel"
      v-model="menuItemPanel"
      :panel-title="isEdit ? 'Menü Öğesi Düzenle' : 'Menü Öğesi Ekle'">
      <template #panelContent>
        <panel-menu-item />
      </template>
      <template #footerButton>
        <div class="button-c button-save" @click="SaveMenuItem">
          {{ isEdit ? 'Kaydet' : 'Ekle' }}
        </div>
      </template>
    </panel-wrapper>
  </AdminLayout>
</template>
<script setup lang="ts">
  import { ref, reactive, onBeforeMount } from 'vue'
  import draggable from 'vuedraggable'
  import AdminLayout from '@/layouts/AdminLayout.vue'
  import { Breadcrumb } from '@/components/global'
  import PanelWrapper from '@/components/PanelWrapper.vue'
  import PanelMenuItem from '../components/panel/PanelMenuItem.vue'

  import { useRoute } from 'vue-router'
  const route = useRoute()
  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { useSiteManagementMenuStore } from '../stores/siteManagementMenuStore'
  const siteManagementMenuStore = useSiteManagementMenuStore()
  import { useSiteManagementPageStore } from '../stores/siteManagementPageStore'
  const siteManagementPageStore = useSiteManagementPageStore()
  import { useSiteManagementMenuValidationStore } from '../validation/siteManagementMenuValidationStore'
  const siteManagementMenuValidationStore = useSiteManagementMenuValidationStore()
  import { useSiteManagementMenuService } from '../service/siteManagementMenuService'
  const siteManagementMenuService = useSiteManagementMenuService()
  import { useSiteManagementPageService } from '../service/siteManagementPageService'
  const siteManagementPageService = useSiteManagementPageService()

  const onayIslemTipleri = ref<Record<string, any>[]>([])
  const formData = reactive<Record<string, any>>({})
  const invalidTexts = reactive<Record<string, any>>({})
  const loaded = ref<boolean>(false)

  const menuItemPanel = ref<boolean>(false)
  const isEdit = ref<boolean>(false)
  const pageList = ref<Record<string, any>[]>([])
  const editMenuIndex = ref<number | null>(null)

  const AddMenuItem = () => {
    isEdit.value = false
    Object.assign(
      siteManagementMenuStore.menuItemData,
      siteManagementMenuStore.safeMenuItemData
    )
    menuItemPanel.value = true
  }

  const EditMenu = (data: Record<string, any>, i: number) => {
    isEdit.value = true
    Object.assign(siteManagementMenuStore.menuItemData, data)
    siteManagementMenuStore.menuItemData.targetKey =
      siteManagementMenuStore.menuItemData.targetKey === '_blank' ? true : false

    editMenuIndex.value = i
    menuItemPanel.value = true
  }

  const SaveMenu = async () => {
    var dt: any
    siteManagementMenuStore.menuContentList.forEach(async (el, i) => {
      if (el.type === 'update') {
        dt = await dataStore.dataPut('Menu/' + el.id, {
          data: el
        })
      }
      if (el.type === 'new') {
        dt = await dataStore.dataPost('Menu', {
          data: el
        })
      }
    })

    siteManagementMenuStore.deleteMenuList.forEach(async (el, i) => {
      dt = await dataStore.dataDelete('Menu/' + el)
    })

    setTimeout(async () => {
      siteManagementMenuStore.deleteMenuList = []
      await GetMenuList()
    }, 50)
  }

  const ReorderMenu = () => {
    siteManagementMenuStore.menuContentList.forEach((el, i) => {
      el.sira = i + 1
      if (el.id !== undefined) el.type = 'update'
    })
  }
  const ChangeMenu = (data: Record<string, any>) => {
    ReorderMenu()
  }
  const AddToMenu = (data: Record<string, any>, i: number) => {
    let newData: Record<string, any> = {
      title: data.title,
      konumId: route.params.menuId,
      slug: data.slug,
      parentMenuId: null,
      pageId: data.id,
      isActive: true,
      type: 'new',
      targetKey: '',
      sira: siteManagementMenuStore.menuContentList.length + 1
    }
    siteManagementMenuStore.menuContentList.push(newData)
    data.show = false
  }
  
  const CheckPageList = () => {
    pageList.value.forEach((page) => {
      var show: boolean = true
      siteManagementMenuStore.menuContentList.forEach((menu) => {
        if (page.id === menu.pageId) show = false
      })
      page.show = show
    })

    setTimeout(() => {
      loaded.value = true
    }, 10)
  }

  const RemoveFromMenu = (el: Record<string, any>, i: number) => {
    siteManagementMenuStore.menuContentList.splice(i, 1)

    if (el.pageId !== null) {
      let page = pageList.value.filter((itm) => itm.id === el.pageId)[0]
      page.show = true
    }
    if (el.id !== undefined) {
      siteManagementMenuStore.deleteMenuList.push(el.id)
    }
    ReorderMenu()
  }

  const SaveMenuItem = () => {
    if (siteManagementMenuValidationStore.FormCheck()) {      
      if (!isEdit.value) {
        let newData: Record<string, any> = {
          title: siteManagementMenuStore.menuItemData.title,
          konumId: route.params.menuId,
          slug: siteManagementMenuStore.menuItemData.slug,
          parentMenuId: null,
          pageId: null,
          isActive: true,
          type: 'new',
          targetKey: siteManagementMenuStore.menuItemData.targetKey ? '_blank' : '',
          sira: siteManagementMenuStore.menuContentList.length + 1
        }
        siteManagementMenuStore.menuContentList.push(newData)
      } else {
        if (siteManagementMenuStore.menuItemData.id !== undefined)
          siteManagementMenuStore.menuItemData.type = 'update'

        siteManagementMenuStore.menuItemData.targetKey = siteManagementMenuStore
          .menuItemData.targetKey
          ? '_blank'
          : ''

        Object.assign(
          siteManagementMenuStore.menuContentList[editMenuIndex.value!],
          siteManagementMenuStore.menuItemData
        )

        isEdit.value = false
        editMenuIndex.value = null
      }
      menuItemPanel.value = false
    }else{
      siteManagementMenuValidationStore.isFormValid = true
    }
  }

  const GetMenuList = async () => {
    await siteManagementMenuService.GetMenuContentList()
    siteManagementMenuStore.menuContentList.sort((a, b) => a.sira - b.sira)

    pageList.value.splice(
      0,
      pageList.value.length,
      ...siteManagementPageStore.allPagesList
    )

    CheckPageList()
  }

  onBeforeMount(async () => {
    await siteManagementPageService.GetAllPages()
    await GetMenuList()
  })
</script>
