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

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

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

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  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: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/assets/assets/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      uid: res?.uid || '',
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      name: res?.Name || '',
      value: res?.Value || '',
      description: res?.Description || '',
      help: res?.Help || '',
      isActive: res?.IsActive ?? true,
      lot: res?.Lot || 0,
      isDisposed: res?.IsDisposed ?? false,
      isInPosession: res?.IsInPosession ?? false,
      useLifeYears: res?.UseLifeYears || 0,
      assetDisposalDate: res?.AssetDisposalDate || date.now(),
      isOwned: res?.IsOwned ?? false,
      locationComment: res?.LocationComment || '',
      isDepreciated: res?.IsDepreciated ?? false,
      lifeUseUnits: res?.LifeUseUnits || 0,
      processing: res?.Processing ?? false,
      guaranteeDate: res?.GuaranteeDate || date.now(),
      useLifeMonths: res?.UseLifeMonths || 0,
      assetServiceDate: res?.AssetServiceDate || date.now(),
      useUnits: res?.UseUnits || 0,
      serNo: res?.SerNo || '',
      isFullyDepreciated: res?.IsFullyDepreciated ?? false,
      qty: res?.Qty || 0,
      lastMaintenanceDate: res?.LastMaintenanceDate || date.now(),
      nextMaintenenceDate: res?.NextMaintenenceDate || date.now(),
      lastMaintenanceUnit: res?.LastMaintenanceUnit || 0,
      nextMaintenenceUnit: res?.NextMaintenenceUnit || 0,
      lastMaintenanceNote: res?.LastMaintenanceNote || '',
      assetCreateDate: res?.A_Asset_CreateDate || date.now(),
      assetRevalDate: res?.A_Asset_RevalDate || date.now(),
      qtyCurrent: res?.A_QTY_Current || 0,
      qtyOriginal: res?.A_QTY_Original || 0,
      processed: res?.Processed ?? false,
      assetActivationDate: res?.AssetActivationDate || date.now(),
      inventoryNo: res?.InventoryNo || '',
      assetType: res?.A_AssetType || 'MFX',
      manufacturedYear: res?.ManufacturedYear || 1900,
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_ID?.id || '',
      product: res?.M_Product_ID?.identifier || '',
      productId: res?.M_Product_ID?.id || '',
      location: res?.C_Location_ID?.identifier || '',
      locationId: res?.C_Location_ID?.id || '',
      assetGroup: res?.A_Asset_Group_ID?.identifier || '',
      assetGroupId: res?.A_Asset_Group_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      partnerLocation: res?.C_BPartner_Location_ID?.identifier || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      attributeSetInstance: res?.M_AttributeSetInstance_ID?.identifier || '',
      attributeSetInstanceId: res?.M_AttributeSetInstance_ID?.id || '',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      parentAsset: res?.A_Parent_Asset_ID?.identifier || '',
      parentAssetId: res?.A_Parent_Asset_ID?.id || '',
      assetStatus: res?.A_Asset_Status?.identifier || '',
      assetStatusId: res?.A_Asset_Status?.id || '',
      assetAction: res?.A_Asset_Action?.identifier || '',
      assetActionId: res?.A_Asset_Action?.id || '',
      activity: res?.C_Activity_ID?.identifier || '',
      activityId: res?.C_Activity_ID?.id || '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.help == (lastRecord.value?.Help || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.lot == (lastRecord.value?.Lot || 0) &&
    form.value.isDisposed == (lastRecord.value?.IsDisposed ?? false) &&
    form.value.isInPosession == (lastRecord.value?.IsInPosession ?? false) &&
    form.value.useLifeYears == (lastRecord.value?.UseLifeYears || 0) &&
    form.value.assetDisposalDate == (lastRecord.value?.AssetDisposalDate || date.now()) &&
    form.value.isOwned == (lastRecord.value?.IsOwned ?? false) &&
    form.value.locationComment == (lastRecord.value?.LocationComment || '') &&
    form.value.isDepreciated == (lastRecord.value?.IsDepreciated ?? false) &&
    form.value.lifeUseUnits == (lastRecord.value?.LifeUseUnits || 0) &&
    form.value.processing == (lastRecord.value?.Processing ?? false) &&
    form.value.guaranteeDate == (lastRecord.value?.GuaranteeDate || date.now()) &&
    form.value.useLifeMonths == (lastRecord.value?.UseLifeMonths || 0) &&
    form.value.assetServiceDate == (lastRecord.value?.AssetServiceDate || date.now()) &&
    form.value.useUnits == (lastRecord.value?.UseUnits || 0) &&
    form.value.serNo == (lastRecord.value?.SerNo || '') &&
    form.value.isFullyDepreciated == (lastRecord.value?.IsFullyDepreciated ?? false) &&
    form.value.qty == (lastRecord.value?.Qty || 0) &&
    form.value.lastMaintenanceDate == (lastRecord.value?.LastMaintenanceDate || date.now()) &&
    form.value.nextMaintenenceDate == (lastRecord.value?.NextMaintenenceDate || date.now()) &&
    form.value.lastMaintenanceUnit == (lastRecord.value?.LastMaintenanceUnit || 0) &&
    form.value.nextMaintenenceUnit == (lastRecord.value?.NextMaintenenceUnit || 0) &&
    form.value.lastMaintenanceNote == (lastRecord.value?.LastMaintenanceNote || '') &&
    form.value.assetCreateDate == (lastRecord.value?.A_Asset_CreateDate || date.now()) &&
    form.value.assetRevalDate == (lastRecord.value?.A_Asset_RevalDate || date.now()) &&
    form.value.qtyCurrent == (lastRecord.value?.A_QTY_Current || 0) &&
    form.value.qtyOriginal == (lastRecord.value?.A_QTY_Original || 0) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.assetActivationDate == (lastRecord.value?.AssetActivationDate || date.now()) &&
    form.value.inventoryNo == (lastRecord.value?.InventoryNo || '') &&
    form.value.assetType == (lastRecord.value?.A_AssetType || 'MFX') &&
    form.value.manufacturedYear == (lastRecord.value?.ManufacturedYear || 1900) &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.productId == (lastRecord.value?.M_Product_ID?.id || '') &&
    form.value.locationId == (lastRecord.value?.C_Location_ID?.id || '') &&
    form.value.assetGroupId == (lastRecord.value?.A_Asset_Group_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.attributeSetInstanceId == (lastRecord.value?.M_AttributeSetInstance_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.parentAssetId == (lastRecord.value?.A_Parent_Asset_ID?.id || '') &&
    form.value.assetStatusId == (lastRecord.value?.A_Asset_Status?.id || '') &&
    form.value.assetActionId == (lastRecord.value?.A_Asset_Action?.id || '') &&
    form.value.activityId == (lastRecord.value?.C_Activity_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/assets/assets/${route.params.id}/duplicate`)
}

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
  setNoEdit()
  if(!noEdit.value) {
    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/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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') {
      location.reload()
    } else if(saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
    } 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
    })
  }
}

const showAttachment = ref(false)

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

<template>
  <Head>
    <Title>Edit 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 === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" class="button" :class="(form.name === '' || form.assetGroupId === '' || form.productId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.assetGroupId === '' || form.productId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</button>
        </template>
      </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>
        <AttachmentModal v-model="showAttachment" target="a_asset" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>