<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const router = useRouter()
const activeSave = useActiveSave()

definePageMeta({
  middleware: ['auth', 'org']
})

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  name: '',
  value: '',
  description: '',
  help: '',
  isActive: true,
  lot: 0,
  isDisposed: false,
  isInPosession: false,
  useLifeYears: 0,
  assetDisposalDate: date.now(),
  isOwned: false,
  locationComment: '',
  isDepreciated: false,
  lifeUseUnits: 0,
  processing: false,
  guaranteeDate: date.now(),
  useLifeMonths: 0,
  assetServiceDate: date.now(),
  useUnits: 0,
  serNo: '',
  isFullyDepreciated: false,
  qty: 0,
  lastMaintenanceDate: date.now(),
  nextMaintenenceDate: date.now(),
  lastMaintenanceUnit: 0,
  nextMaintenenceUnit: 0,
  lastMaintenanceNote: '',
  assetCreateDate: date.now(),
  assetRevalDate: date.now(),
  qtyCurrent: 0,
  qtyOriginal: 0,
  processed: false,
  assetActivationDate: date.now(),
  inventoryNo: '',
  assetType: 'MFX',
  manufacturedYear: 1900,
  user: '',
  userId: '',
  product: '',
  productId: '',
  location: '',
  locationId: '',
  assetGroup: '',
  assetGroupId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  attributeSetInstance: '',
  attributeSetInstanceId: '',
  project: '',
  projectId: '',
  parentAsset: '',
  parentAssetId: '',
  assetStatus: 'New',
  assetStatusId: 'NW',
  assetAction: '',
  assetActionId: '',
  activity: '',
  activityId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    router.push('/assets/assets')
  }
}

const save = async (record) => {
  form.value = record
  
  if(form.value.name !== '' && form.value.assetGroupId !== '' && form.value.productId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/assets/assets/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      name: form.value.name,
      value: form.value.value,
      description: form.value.description,
      help: form.value.help,
      isActive: form.value.isActive,
      lot: form.value.lot,
      isDisposed: form.value.isDisposed,
      isInPosession: form.value.isInPosession,
      useLifeYears: form.value.useLifeYears,
      assetDisposalDate: form.value.assetDisposalDate,
      isOwned: form.value.isOwned,
      locationComment: form.value.locationComment,
      isDepreciated: form.value.isDepreciated,
      lifeUseUnits: form.value.lifeUseUnits,
      processing: form.value.processing,
      guaranteeDate: form.value.guaranteeDate,
      useLifeMonths: form.value.useLifeMonths,
      assetServiceDate: form.value.assetServiceDate,
      useUnits: form.value.useUnits,
      serNo: form.value.serNo,
      isFullyDepreciated: form.value.isFullyDepreciated,
      qty: form.value.qty,
      lastMaintenanceDate: form.value.lastMaintenanceDate,
      nextMaintenenceDate: form.value.nextMaintenenceDate,
      lastMaintenanceUnit: form.value.lastMaintenanceUnit,
      nextMaintenenceUnit: form.value.nextMaintenenceUnit,
      lastMaintenanceNote: form.value.lastMaintenanceNote,
      assetCreateDate: form.value.assetCreateDate,
      assetRevalDate: form.value.assetRevalDate,
      qtyCurrent: form.value.qtyCurrent,
      qtyOriginal: form.value.qtyOriginal,
      processed: form.value.processed,
      assetActivationDate: form.value.assetActivationDate,
      inventoryNo: form.value.inventoryNo,
      assetType: form.value.assetType,
      manufacturedYear: form.value.manufacturedYear,
      userId: form.value.userId,
      productId: form.value.productId,
      locationId: form.value.locationId,
      assetGroupId: form.value.assetGroupId,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      attributeSetInstanceId: form.value.attributeSetInstanceId,
      projectId: form.value.projectId,
      parentAssetId: form.value.parentAssetId,
      assetStatusId: form.value.assetStatusId,
      assetActionId: form.value.assetActionId,
      activityId: form.value.activityId,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/assets/assets/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/assets/assets/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      back()
    }
  } else {
    form.value.alert.status = res.status
    form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '/assets/assets', text: 'Assets'},
  { link: '#', text: 'Add Asset', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Asset</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.name === '' || form.assetGroupId === '' || form.productId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
      </div>
      <div>
        <div class="d-flex gap-10px">
          <button v-if="activeSave" type="button" @click="activeSave = false; back();" class="button">
            <span class="tf-icon ti ti-square-x ti-xs me-1 color-inherit"></span> Abort
          </button>
          <button type="button" @click="back" class="button">
            <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
          </button>
        </div>
      </div>
    </div>

    <div class="banner">
      <div>
        <AssetsAssetForm v-model="form" @save="save" />
      </div>
    </div>
  </NuxtLayout>
</template>