<template>
  <div class="form-part">
    <div class="form-part-title">
      <h4>Sayfa Görseli</h4>
    </div>
    <div class="form-part-content">
      <template v-if="file.fileUrl !== '' && file.fileUrl !== null">
        <file-list-item
          :data="file"
          @click="ReplaceImage"
          onlyPreview
          :filePath="file.fileUrl">
          <template #actionButtons  v-if="!usersStore.isPanelUser">
            <i
              class="ico-c ico-btn ico-section back-grad-alert"
              @click="DeleteImagePop(file)">
              <svg><use href="/src/assets/images/icons.svg#trash"></use></svg>
            </i>
          </template>
        </file-list-item>
      </template>
      <template v-else>
        <div class="form-item form-item-picture clickable" @click="picturePanel = true">
          <div class="image-c">
            <i class="ico-c">
              <svg>
                <use href="@/assets/images/icons.svg#plus"></use>
              </svg>
            </i>
          </div>
        </div>
      </template>
    </div>
  </div>
  <panel-wrapper
    v-if="picturePanel"
    v-model="picturePanel"
    panel-title="Profil Resmi Ekle">
    <template #panelContent>
      <panel-sayfa-picture />
    </template>
    <template #footerButton>
      <div class="button-c button-save" @click="FileUpload">Ekle</div>
    </template>
  </panel-wrapper>
</template>
<script setup lang="ts">
  import { ref, reactive, onBeforeMount } from 'vue'
  import PanelSayfaPicture from '../panel/PanelSayfaPicture.vue'
  import PanelWrapper from '@/components/PanelWrapper.vue'

  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { useValidationStore } from '@/stores/validationStore'
  const validationStore = useValidationStore()
  import { useSiteManagementPageStore } from '../../stores/siteManagementPageStore'
  const siteManagementPageStore = useSiteManagementPageStore()
  import { useDialogStore } from '@/components/global/dialogStore'
  const dialogStore = useDialogStore()
  import { useUsersStore } from '@/stores/usersStore'
  const usersStore = useUsersStore()

  const picturePanel = ref<boolean>(false)
  const isUpdate = ref<boolean>(false)

  const file = reactive<Record<string, any>>({
    title: '',
    fileUrl: ''
  })

  const ReplaceImage = (d: object) => {
    Object.assign(dataStore.panelData, d)
    isUpdate.value = true
    picturePanel.value = true
  }

  const GetData = async () => {
    let dt = await dataStore.dataGet(
      'DocumentPage/GetDocumentsByPageId/' + siteManagementPageStore.selectedPage
    )
    Object.assign(file, dt[0])
  }

  const FormCheck = (): boolean => {
    let check: any = true
    if (dataStore.panelData.file === null) {
      validationStore.panelInvalidText.file = 'Bir dosya seçmelisiniz'
      check = false
    } else delete validationStore.panelInvalidText.file
    if (check === '') check = true
    return check
  }

  const FileUpload = async () => {
    if (FormCheck()) {
      const formData = new FormData()
      formData.append('file', dataStore.panelData.file)
      formData.append('title', '-')
      formData.append('pageId', String(siteManagementPageStore.selectedPage))
      let dt: any

      if (!isUpdate.value) {
        dt = await dataStore.dataPost('DocumentPage/upload', {
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      } else {
        dt = await dataStore.dataPut('DocumentPage/' + dataStore.panelData.id, {
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      }
      if (dt !== 'errorfalse') {
        Object.assign(file, {})
        await GetData()
        picturePanel.value = false
        isUpdate.value = false
      }
    }
  }

  const DeleteImagePop = (data: Record<string, any>) => {
    dialogStore.CreateDialog({
      title: 'Resim Sil',
      id: 'deleteimage',
      content: 'Resmi silmek istediğinize emin misiniz? Bu işlem geri alınamaz.',
      closeText: 'Vazgeç',
      buttons: [
        {
          label: 'Resmi Sil',
          type: 'alert',
          function: () => DeleteImage(data.id)
        }
      ]
    })
  }

  const DeleteImage = async (id: number | string) => {
    var dt = await dataStore.dataDelete('DocumentPage/' + id)

    if (dt !== 'errorfalse') {
      dialogStore.CloseDialog('deleteimage')
      await GetData()
    }
  }

  onBeforeMount(async () => {
    await GetData()
  })
</script>
