<template>
  <div class="form-part">
    <div class="form-part-title">
      <h4>Piyango Resimleri</h4>
    </div>
    <div class="form-part-content">
      <template v-for="(file, i) in fileList">
        <file-list-item
          :data="file"
          @click="EditImage"
          onlyPreview
          :filePath="file.resimYolu" />
      </template>
      <div
        class="form-item form-item-picture clickable"
        @click="AddNewImage"
        v-if="!usersStore.isPanelUser">
        <div class="image-c">
          <i class="ico-c">
            <svg>
              <use href="@/assets/images/icons.svg#plus"></use>
            </svg>
          </i>
        </div>
      </div>
      <div v-if="usersStore.isPanelUser && fileList.length === 0" class="form-inner-comment">
        Eklenmiş resim bulunamadı.
      </div>
    </div>
  </div>
  <panel-wrapper
    v-if="picturePanel"
    v-model="picturePanel"
    :panel-title="isUpdate ? 'Piyango Resmi Düzenle/Değiştir' : 'Piyango Resmi Ekle'">
    <template #panelContent>
      <panel-piyango-pictures />
    </template>
    <template #footerButton>
      <div class="button-c button-save" @click="FileUpload">
        {{ isUpdate ? 'Kaydet' : 'Ekle' }}
      </div>
    </template>
  </panel-wrapper>
</template>
<script setup lang="ts">
  import { ref, onBeforeMount } from 'vue'
  import PanelPiyangoPictures from '../panel/PanelPiyangoPictures.vue'
  import PanelWrapper from '@/components/PanelWrapper.vue'

  import { useDataStore } from '@/stores/dataStore'
  const dataStore = useDataStore()
  import { useGlobalStore } from '@/stores/globalStore'
  const globalStore = useGlobalStore()
  import { useValidationStore } from '@/stores/validationStore'
  const validationStore = useValidationStore()
  import { useUsersStore } from '@/stores/usersStore'
  const usersStore = useUsersStore()
  import { usePiyangoStore } from '../../stores/piyangoStore'
  const piyangoStore = usePiyangoStore()

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

  interface IFileList {
    [key: string]: any
  }

  const fileList = ref<IFileList[]>([] as IFileList[])

  const AddNewImage = () => {
    dataStore.panelData = {
      cekilisId: piyangoStore.selectedLottery,
      isKapak: false
    }
    picturePanel.value = true
  }
  const EditImage = (d: object) => {
    dataStore.panelData = d
    picturePanel.value = true
    isUpdate.value = true
  }

  const GetData = async () => {
    let dt = await dataStore.dataGet('CekilisResim/Cekilis/' + piyangoStore.selectedLottery)
    if (dt !== 'errorfalse') fileList.value.splice(0, fileList.value.length, ...dt.data)
  }

  const FormCheck = (): boolean => {
    if (dataStore.panelData.file === undefined || dataStore.panelData.file === null) {
      validationStore.panelInvalidText.file = 'Bir dosya seçmelisiniz'
      isFormValid.value = false
    } else delete validationStore.panelInvalidText.file

    if (!validationStore.checkEmpty(dataStore.panelData.file)) {
      let fileType: string = globalStore.FileType(dataStore.panelData.file.name)
      if (!globalStore.imageFormats.includes(fileType.toLowerCase())) {
        validationStore.panelInvalidText.file = `Sadece Resim dosyası yükleyebilirsiniz. Lütfen ${globalStore.imageFormats} formatındaki dosyaları yükleyin`
        isFormValid.value = false
      }
    }

    return isFormValid.value
  }

  const FileUpload = async () => {
    if (FormCheck()) {
      const formData = new FormData()
      formData.append('file', dataStore.panelData.file)
      formData.append('isKapak', dataStore.panelData.isKapak)
      formData.append('cekilisId', String(piyangoStore.selectedLottery))
      let dt: any

      if (!isUpdate.value) {
        dt = await dataStore.dataPost('CekilisResim/', {
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      } else {
        dt = await dataStore.dataPut('CekilisResim/' + dataStore.panelData.id, {
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      }
      if (dt !== 'errorfalse') {
        await GetData()
        picturePanel.value = false
        isUpdate.value = false
      }
    }
  }
  onBeforeMount(async () => {
    await GetData()
  })
</script>
