import { defineStore } from 'pinia'
import { useDataStore } from '@/stores/dataStore'
import { useCustomerIrtibatStore } from '../stores/customerIrtibatStore'
import { useCustomerIrtibatValidationStore } from '../validation/customerIrtibatValidationStore'
import { useUsersStore } from '@/stores/usersStore'

export const useCustomerIrtibatService = defineStore('customerIrtibatService', () => {
  const dataStore = useDataStore()
  const customerIrtibatStore = useCustomerIrtibatStore()
  const customerIrtibatValidationStore = useCustomerIrtibatValidationStore()
  const usersStore = useUsersStore()

  const GetAllIrtibatList = async (id?: number | string) => {
    let userId = id || usersStore.selectedUserId()
    let data: Record<string, any> | any = await dataStore.dataGet(
      'AppUserContactPerson/GetContactPersonAppUserId/' + userId + '?pageNumber=0'
    )

    if (data !== 'errorfalse') {
      customerIrtibatStore.customerAllIrtibatList = data.data
    }
    setTimeout(() => {
      customerIrtibatStore.loaded = true
    }, 30)
  }

  const GetIrtibat = async (id?: number | string) => {
    customerIrtibatStore.loaded = false
    let userId = id || usersStore.selectedUserId()
    let dt = await dataStore.dataGet(
      'AppUserContactPerson/GetContactPersonAppUserId/' + userId
    )
    if (dt !== 'errorfalse') {
      if (dt.data.length === 0) customerIrtibatStore.isNew = true

      if (customerIrtibatStore.isNew) {
          customerIrtibatStore.ResetForm()
      } else {
        Object.assign(customerIrtibatStore.customerIrtibatForm, dt.data[0])
        customerIrtibatStore.SetSafeIrtibatData()
      }
    }

    setTimeout(() => {
      customerIrtibatStore.loaded = true
    }, 30)
  }

  const SaveIrtibat = async () => {
    if (customerIrtibatValidationStore.FormCheck()) {
      var res: any

      if (customerIrtibatStore.isNew) {
        res = await dataStore.dataPost('AppUserContactPerson', {
          data: customerIrtibatStore.customerIrtibatForm
        })
      } else {
        res = await dataStore.dataPut(
          'AppUserContactPerson/' + customerIrtibatStore.customerIrtibatForm.id,
          {
            data: customerIrtibatStore.customerIrtibatForm
          }
        )
      }

      if (res !== 'errorfalse') {
        customerIrtibatStore.isNew = false
        customerIrtibatValidationStore.formChanged = false
        customerIrtibatStore.refreshList = true
        customerIrtibatStore.irtibatPanel = false
      }
    } else {
      customerIrtibatValidationStore.isFormValid = true
    }
  }

  return { GetAllIrtibatList, GetIrtibat, SaveIrtibat }
})
