import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useDataStore } from '@/stores/dataStore'
import { useIzinBedelOraniStore } from '../store/izinBedelOraniStore'
import { useIzinBedelOraniValidationStore } from '../validation/izinBedelOraniValidationStore'

export const useIzinBedelOraniService = defineStore('izinBedelOraniService', () => {
  const dataStore = useDataStore()
  const izinBedelOraniStore = useIzinBedelOraniStore()
  const izinBedelOraniValidationStore = useIzinBedelOraniValidationStore()

  const loaded = ref<boolean>(false)

  const SaveIzinBedelOrani = async (panelData: Record<string, any>, isUpdate: boolean = false) => {
    if (izinBedelOraniValidationStore.FormCheck(panelData)) {
      var res: any

      if (!isUpdate) {
        res = await dataStore.dataPost('IzinBedelOrani', {
          data: {
            adi: panelData.ad,
            oran: panelData.oran,
            aciklama: panelData.aciklama,
            aktif: panelData.aktif
          }
        })
      } else {
        res = await dataStore.dataPut('IzinBedelOrani/' + panelData.id, {
          data: {
            id: panelData.id,
            adi: panelData.ad,
            oran: panelData.oran,
            aciklama: panelData.aciklama,
            aktif: panelData.aktif
          }
        })
      }

      if (res !== 'errorfalse') {
        return true
      }
    }
    return false
  }

  const DeleteIzinBedelOrani = async (id: number | string) => {
    var res = await dataStore.dataDelete('IzinBedelOrani/' + id)
    return res !== 'errorfalse'
  }

  const GetIzinBedelOraniList = async () => {
    var res = await dataStore.dataGet('IzinBedelOrani')
    if (res !== 'errorfalse') {
      izinBedelOraniStore.izinBedelOraniList = res
      return res
    }
    return []
  }

  const GetIzinBedelOraniById = async (id: number | string) => {
    var res = await dataStore.dataGet('IzinBedelOrani/' + id)
    if (res !== 'errorfalse') {
      return res
    }
    return null
  }

  const GetAktifIzinBedelOraniList = async () => {
    var res = await dataStore.dataGet('IzinBedelOrani/Aktif')
    if (res !== 'errorfalse') {
      izinBedelOraniStore.aktifIzinBedelOraniList = res
      return res
    }
    return []
  }

  const UpdateIzinBedelOraniStatus = async (id: number | string, aktif: boolean) => {
    var res = await dataStore.dataPut('IzinBedelOrani/' + id + '/Status', {
      data: {
        Aktif: aktif
      }
    })
    return res !== 'errorfalse'
  }

  const LoadData = async () => {
    await GetIzinBedelOraniList()
    await GetAktifIzinBedelOraniList()
    loaded.value = true
  }

  return {
    loaded,
    SaveIzinBedelOrani,
    DeleteIzinBedelOrani,
    GetIzinBedelOraniList,
    GetIzinBedelOraniById,
    GetAktifIzinBedelOraniList,
    UpdateIzinBedelOraniStatus,
    LoadData
  }
})
