import { defineStore } from 'pinia'
import { useDataStore } from '@/stores/dataStore'
import { useCustomerDocumentStore } from '../stores/customerDocumentStore'
import { useCustomerDocumentValidationStore } from '../validation/customerDocumentValidationStore'
import { useUsersStore } from '@/stores/usersStore'

export const useCustomerDocumentService = defineStore('customerDocumentService', () => {
  const dataStore = useDataStore()
  const customerDocumentStore = useCustomerDocumentStore()
  const customerDocumentValidationStore = useCustomerDocumentValidationStore()
  const usersStore = useUsersStore()

  const GetDocumentList = async () => {
    customerDocumentStore.customerDocumentsList.splice(
      0,
      customerDocumentStore.customerDocumentsList.length
    )

    let dt = await dataStore.dataGet(
      'AppUserDocument/AppUserId/' + usersStore.selectedUserId(),
      {
        params: {
          pageSize: 50
        }
      }
    )
    if (dt !== 'errorfalse') {
      customerDocumentStore.customerDocumentsList.splice(
        0,
        customerDocumentStore.customerDocumentsList.length,
        ...dt
      )
    }
    setTimeout(() => {
      customerDocumentStore.loaded = true
    }, 30)
  }

  const SaveDocument = async () => {
    if (customerDocumentValidationStore.FormCheck()) {
      const formData = new FormData()
      formData.append('file', customerDocumentStore.customerDocumentForm.file)
      formData.append('title', customerDocumentStore.customerDocumentForm.title)
      formData.append('appUserId', String(usersStore.selectedUserId()))
      let dt: any

      if (!customerDocumentStore.isUpdate) {
        dt = await dataStore.dataPost('AppUserDocument/upload', {
          data: formData,
          headers: { 'Content-Type': 'multipart/form-data' }
        })
      } else {
        dt = await dataStore.dataPut(
          'AppUserDocument/' + customerDocumentStore.customerDocumentForm.id,
          {
            data: formData,
            headers: { 'Content-Type': 'multipart/form-data' }
          }
        )
      }
      if (dt !== 'errorfalse') {
        await GetDocumentList()
        customerDocumentStore.documentPanel = false
        customerDocumentStore.isUpdate = false
      }
    } else {
      customerDocumentValidationStore.isFormValid = true
    }
  }

  return { GetDocumentList, SaveDocument }
})
