<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: '',
  documentNo: '',
  movementDate: date.now('date'),
  approvalAmt: 0,
  description: '',
  isActive: true,
  isApproved: false,
  warehouse: '',
  warehouseId: '',
  docType: '',
  docTypeId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  docStatus: '',
  docStatusId: '',
  processed: false,
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/materials/stock-takes/'+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 || '',
      documentNo: res?.DocumentNo || '',
      movementDate: res?.MovementDate || '',
      approvalAmt: res?.ApprovalAmt || 0,
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      isApproved: res?.IsApproved ?? false,
      processed: res?.Processed ?? false,
      processing: res?.Processing ?? false,
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      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.documentNo == (lastRecord.value?.DocumentNo || '') &&
    form.value.movementDate == (lastRecord.value?.MovementDate || '') &&
    form.value.approvalAmt == (lastRecord.value?.ApprovalAmt || 0) &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.isApproved == (lastRecord.value?.IsApproved ?? false) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.processing == (lastRecord.value?.Processing ?? false) &&
    form.value.warehouseId == (lastRecord.value?.M_Warehouse_ID?.id || '') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '') &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || 'DR')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/materials/stock-takes/${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('/materials/stock-takes')
  }
}

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/materials/stock-takes/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      documentNo: form.value.documentNo,
      movementDate: form.value.movementDate,
      approvalAmt: form.value.approvalAmt,
      description: form.value.description,
      isActive: form.value.isActive,
      isApproved: form.value.isApproved,
      warehouseId: form.value.warehouseId,
      docTypeId: form.value.docTypeId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
      docStatusId: form.value.docStatusId,
      processed: form.value.processed,
      processing: form.value.processing,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/materials/stock-takes/'+res.id+'/view')
    } else if(saveType === 'changes') {
      location.reload()
    } else if(saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      // location.reload()
    } 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: '#', text: 'Materials'},
  { link: '/materials/stock-takes', text: 'Stock Takes'},
  { link: '#', text: 'Add Stock Take', active: true}
]))

const tab = ref(route.query?.tab || 'inventory')
const tabs = computed(() => ([
  { value: 'inventory', text: 'Physical Inventory'},
  { value: 'reference', text: 'Reference'},
  { value: 'status', text: 'Status'}
]))

const openOtherTab = () => {
  if(tab.value === 'inventory') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'status'
  }
}

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/materials/stock-takes/'+route.params.id+'/document-action', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      documentAction: docAction
    }
  })
  if(res) {
    toast({
      message: 'Document has been successfully set to '+docAction+' status.',
      type: 'is-success',
      duration: 2000
    })
    back()
  } else {
    toast({
      message: 'Document failed to set to '+docAction+' status.',
      type: 'is-danger',
      duration: 2000
    })
  }
}
</script>

<template>
  <Head>
    <Title>Add Stock Take</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.warehouseId === '' || form.movementDate === '' || form.docTypeId === '' || 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.warehouseId === '' || form.movementDate === '' || form.docTypeId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.warehouseId === '' || form.movementDate === '' || form.docTypeId === '' || 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 v-if="form.docStatusId !== 'CO'">
            <button type="button" @click="setDocumentAction('CO')" class="button" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">Complete</button>
            <button type="button" @click="setDocumentAction('VO')" class="button" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">Void</button>
          </template>

        </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 class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div class="editwrapper">
        <MaterialsStockTakeForm v-model="form" v-model:tab="tab" @save="save"/>
      </div>
      <div>
        <MaterialsStockTakeDetailRecord action="edit" :info="form" tab="count_line" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="M_Inventory" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>