import { defineStore } from 'pinia'
import { useDataStore } from '@/stores/dataStore'
import { usePiyangoStore } from '../stores/piyangoStore'
import { usePiyangoDocumentStore } from '../stores/piyangoDocumentStore'
import { usePiyangoDocumentValidationStore } from '../validation/piyangoDocumentValidationStore'

export const usePiyangoDocumentService = defineStore('piyangoDocumentService', () => {
  const dataStore = useDataStore()
  const piyangoStore = usePiyangoStore()
  const piyangoDocumentStore = usePiyangoDocumentStore()
  const piyangoDocumentValidationStore = usePiyangoDocumentValidationStore()

  const GetDocumentList = async () => {
    piyangoDocumentStore.piyangoDocumentsList.splice(
      0,
      piyangoDocumentStore.piyangoDocumentsList.length
    )

    let dt = await dataStore.dataGet('Dokuman/Cekilis/' + piyangoStore.selectedLottery,{
      params: {
        pageSize: 50
      }
    })
    
    if (dt !== 'errorfalse') {
      piyangoDocumentStore.piyangoDocumentsList.splice(
        0,
        piyangoDocumentStore.piyangoDocumentsList.length,
        ...dt.data
      )      
    }
    setTimeout(() => {
      piyangoDocumentStore.loaded = true
    }, 30)
  }

  const SaveDocument = async () => {
    if (piyangoDocumentValidationStore.FormCheck()) {
      const formData = new FormData()
      formData.append('dosya', piyangoDocumentStore.piyangoDocumentForm.dosya)
      formData.append('dokumanAdi', piyangoDocumentStore.piyangoDocumentForm.dokumanAdi)
      formData.append('cekilisId', String(piyangoStore.selectedLottery))
      let dt: any

      if (!piyangoDocumentStore.isUpdate) {
        dt = await dataStore.dataPost('Dokuman/', {
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      } else {
        dt = await dataStore.dataPut(
          'Dokuman/' + piyangoDocumentStore.piyangoDocumentForm.id,
          {
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' }
          }
        )
      }
      if (dt !== 'errorfalse') {
        await GetDocumentList()
        piyangoDocumentStore.documentPanel = false
        piyangoDocumentStore.isUpdate = false
      }
    } else {
      piyangoDocumentValidationStore.isFormValid = true
    }
  }
  return { GetDocumentList, SaveDocument }
})
