import { defineStore } from 'pinia'
import { useDataStore } from '@/stores/dataStore'
import { usePiyangoStore } from '../stores/piyangoStore'
import { usePiyangoIkramiyeStore } from '../stores/piyangoIkramiyeStore'
import { usePiyangoIkramiyeValidationStore } from '../validation/piyangoIkramiyeValidationStore'
import { useGlobalStore } from '@/stores/globalStore'

export const usePiyangoIkramiyeService = defineStore('piyangoIkramiyeService', () => {
  const dataStore = useDataStore()
  const piyangoStore = usePiyangoStore()
  const piyangoIkramiyeStore = usePiyangoIkramiyeStore()
  const piyangoIkramiyeValidationStore = usePiyangoIkramiyeValidationStore()
  const globalStore = useGlobalStore()

  const GetAllIkramiyeler = async () => {
    let data: Record<string, any> | any = await dataStore.dataGet(
      'Ikramiye/Cekilis/' + piyangoStore.selectedLottery + '?pageNumber=0'
    )

    if (data !== 'errorfalse') {
      piyangoIkramiyeStore.piyangoAllIkramiyeTotals.yedekTalihliAdedi =
        data.toplamyedektalihli
      piyangoIkramiyeStore.piyangoAllIkramiyeTotals.asilTalihliAdedi =
        data.toplamasiltalihli
      piyangoIkramiyeStore.piyangoAllIkramiyeTotals.toplamDeger = data.toplamdeger

      if (data.data.length > 0 && data.data[0].paraBirimi !== null)
        piyangoIkramiyeStore.piyangoAllIkramiyeParaBirimi =
          data.data[0].paraBirimi.paraBirimiSembol

      piyangoIkramiyeStore.piyangoAllIkramiyeData = data.data
    }
  }

  const SaveIkramiye = async () => {
    if (piyangoIkramiyeValidationStore.FormCheck()) {
      let dt: any
      piyangoIkramiyeStore.piyangoIkramiyeForm.birimFiyat = globalStore.floatEnLocale(piyangoIkramiyeStore.piyangoIkramiyeForm.birimFiyat)
      piyangoIkramiyeStore.piyangoIkramiyeForm.toplamDeger = globalStore.floatEnLocale(piyangoIkramiyeStore.piyangoIkramiyeForm.toplamDeger)

      if (!piyangoIkramiyeStore.isUpdate) {
        piyangoIkramiyeStore.piyangoIkramiyeForm.cekilisId = piyangoStore.selectedLottery        
        dt = await dataStore.dataPost('Ikramiye', {
          data: piyangoIkramiyeStore.piyangoIkramiyeForm
        })
      } else {
        dt = await dataStore.dataPut(
          'Ikramiye/' + piyangoIkramiyeStore.piyangoIkramiyeForm.id,
          {
            data: piyangoIkramiyeStore.piyangoIkramiyeForm
          }
        )
      }
      if (dt !== 'errorfalse') {
        piyangoIkramiyeStore.refreshList = true
        piyangoIkramiyeStore.isUpdate = false
        piyangoIkramiyeStore.ikramiyePanel = false
      }
    } else {
      piyangoIkramiyeValidationStore.isFormValid = true
    }
  }

  return { GetAllIkramiyeler, SaveIkramiye }
})
