<template>
  <div class="form-part">
    <div class="form-part-title">
      <h4>Piyango Resimleri</h4>
      <a href="/data/mpi-sablon.zip" class="button-c" target="_blank">
        Örnek Resim Şablonları
      </a>
    </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
            #actionButtons
            v-if="piyangoStore.lotteryApprove === 0 || piyangoStore.lotteryApprove === 3">
            <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>
      <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()
  import { useDialogStore } from '@/components/global/dialogStore'
  const dialogStore = useDialogStore()

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

  const fileList = ref<Record<string, any>[]>([])

  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
      }
    }
  }
  const DeleteImagePop = (data: Record<string, any>) => {
    dialogStore.CreateDialog({
      title: 'Resim Sil',
      id: 'deleteimage',
      content: 'Resimi 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('CekilisResim/' + id)

    if (dt !== 'errorfalse') {
      dialogStore.CloseDialog('deleteimage')
      await GetData()
    }
  }
  onBeforeMount(async () => {
    await GetData()
  })
</script>
