import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
import { useValidationStore } from '@/stores/validationStore'
import { usePiyangoStore } from './piyangoStore'

export const usePiyangoIkramiyeStore = defineStore('piyangoIkramiyeStore', () => {
  const piyangoStore = usePiyangoStore()
  const validationStore = useValidationStore()

  const piyangoAllIkramiyeData = ref<Record<string, any>[]>([])
  const piyangoAllIkramiyeTotals = reactive<Record<string, any>>({
    asilTalihliAdedi: 0,
    toplamDeger: 0,
    yedekTalihliAdedi: 0
  })
  const piyangoAllIkramiyeParaBirimi = ref<string>('')

  const piyangoIkramiyeBaseForm = reactive<Record<string, any>>({
    cinsi: '',
    marka: '',
    model: '',
    birimFiyat: null,
    paraBirimiId: null,
    asilTalihliAdedi: null,
    yedekTalihliAdedi: piyangoStore.isLotteryForCharity ? 0 : null,
    toplamDeger: null
  })
  const piyangoIkramiyeForm = reactive<Record<string, any>>({})
  const piyangoIkramiyeSafeForm = reactive<Record<string, any>>({})
  const isUpdate = ref<boolean>(false)
  const refreshList = ref<boolean>(false)
  const ikramiyePanel = ref<boolean>(false)
  const loaded = ref<boolean>(false)
  const totalIkramiyeValue = ref<number>(0)

  const totalIkramiyeValues = reactive<Record<string, any>>({
    yedekTalihliAdedi: 'toplamyedektalihli',
    asilTalihliAdedi: 'toplamasiltalihli',
    toplamDeger: 'toplamdeger'
  })

  const ResetForm = () => {
    Object.assign(piyangoIkramiyeForm, piyangoIkramiyeBaseForm)
  }

  const CalculateToplamDeger = (e: Event) => {
    if (
      !validationStore.checkEmpty(piyangoIkramiyeForm.birimFiyat) &&
      !validationStore.checkEmpty(piyangoIkramiyeForm.asilTalihliAdedi)
    ) {
      let total =
        Number(String(piyangoIkramiyeForm.birimFiyat).replace(',', '.')) *
        piyangoIkramiyeForm.asilTalihliAdedi

      piyangoIkramiyeForm.toplamDeger = String(total.toFixed(2)).replace('.', ',')
    } else {
      piyangoIkramiyeForm.toplamDeger = 0
    }
  }

  return {
    piyangoAllIkramiyeData,
    piyangoAllIkramiyeTotals,
    piyangoAllIkramiyeParaBirimi,
    piyangoIkramiyeBaseForm,
    piyangoIkramiyeForm,
    piyangoIkramiyeSafeForm,
    isUpdate,
    refreshList,
    ikramiyePanel,
    loaded,
    totalIkramiyeValues,
    totalIkramiyeValue,
    ResetForm,
    CalculateToplamDeger
  }
})
