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

const url = useRequestURL()
const router = useRouter()
const route = useRoute()

const activeSave = useActiveSave()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

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

const shipmentParam = ref({})
const window = (from) => {
  if(windowParam.value?.[from] && url.pathname.includes('windows/sales-returns-edit/')) {
    shipmentParam.value = windowParam.value?.[from] || {}
  }
  
  return shipmentParam.value
}

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  documentNo: '',
  description: '',
  isApproved: false,
  processed: false,
  isSOTrx: true,
  isPrinted: false,
  dateAcct: date.now('date'),
  movementDate: date.now('date'),
  poReference: '',
  freightAmt: 0,
  chargeAmt: 0,
  dateOrdered: date.now('date'),
  sendEMail: false,
  noPackages: 0,
  isInTransit: false,
  isInDispute: false,
  volume: 0,
  weight: 0,
  isDropShip: false,
  processedOn: 0,
  isAlternateReturnAddress: false,
  movementType: 'Customer Returns',
  movementTypeId: 'C+',
  docType: '',
  docTypeId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  user: '',
  userId: '',
  dropShipPartner: '',
  dropShipPartnerId: '',
  dropShipPartnerLocation: '',
  dropShipPartnerLocationId: '',
  dropShipUser: '',
  dropShipUserId: '',
  returnPartner: '',
  returnPartnerId: '',
  returnPartnerLocation: '',
  returnPartnerLocationId: '',
  returnUser: '',
  returnUserId: '',
  warehouse: '',
  warehouseId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  freightCostRule: '',
  freightCostRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  priorityRule: '',
  priorityRuleId: '',
  order: '',
  orderId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  salesRep: '',
  salesRepId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  rma: '',
  rmaId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/inouts/'+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 || '',
      isActive: res?.IsActive ?? true,
      documentNo: res?.DocumentNo || '',
      description: res?.Description || '',
      isApproved: res?.IsApproved ?? false,
      processed: res?.Processed ?? false,
      isSOTrx: true,
      isPrinted: res?.IsPrinted ?? false,
      dateAcct: res?.DateAcct || date.now('date'),
      movementDate: res?.MovementDate || date.now('date'),
      poReference: res?.POReference || '',
      freightAmt: res?.FreightAmt || 0,
      chargeAmt: res?.ChargeAmt || 0,
      dateOrdered: res?.DateOrdered || date.now('date'),
      sendEMail: res?.SendEMail ?? false,
      noPackages: res?.NoPackages || 0,
      isInTransit: res?.IsInTransit ?? false,
      isInDispute: res?.IsInDispute ?? false,
      volume: res?.Volume || 0,
      weight: res?.Weight || 0,
      isDropShip: res?.IsDropShip ?? false,
      processedOn: res?.ProcessedOn || 0,
      isAlternateReturnAddress: res?.IsAlternateReturnAddress ?? false,
      movementType: res?.MovementType?.identifier || 'Customer Returns',
      movementTypeId: res?.MovementType?.id || 'C+',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_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 || '',
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_ID?.id || '',
      dropShipPartner: res?.DropShip_BPartner_ID?.identifier || '',
      dropShipPartnerId: res?.DropShip_BPartner_ID?.id || '',
      dropShipPartnerLocation: res?.DropShip_Location_ID?.identifier || '',
      dropShipPartnerLocationId: res?.DropShip_Location_ID?.id || '',
      dropShipUser: res?.DropShip_User_ID?.identifier || '',
      dropShipUserId: res?.DropShip_User_ID?.id || '',
      returnPartner: res?.Return_BPartner_ID?.identifier || '',
      returnPartnerId: res?.Return_BPartner_ID?.id || '',
      returnPartnerLocation: res?.Return_Location_ID?.identifier || '',
      returnPartnerLocationId: res?.Return_Location_ID?.id || '',
      returnUser: res?.Return_User_ID?.identifier || '',
      returnUserId: res?.Return_User_ID?.id || '',
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      deliveryRule: res?.DeliveryRule?.identifier || '',
      deliveryRuleId: res?.DeliveryRule?.id || '',
      freightCostRule: res?.FreightCostRule?.identifier || '',
      freightCostRuleId: res?.FreightCostRule?.id || '',
      deliveryViaRule: res?.DeliveryViaRule?.identifier || '',
      deliveryViaRuleId: res?.DeliveryViaRule?.id || '',
      priorityRule: res?.PriorityRule?.identifier || '',
      priorityRuleId: res?.PriorityRule?.id || '',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_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 || '',
      rma: res?.M_RMA_ID?.identifier || '',
      rmaId: res?.M_RMA_ID?.id || '',
      processing: false,
      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.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.documentNo == (lastRecord.value?.DocumentNo || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isApproved == (lastRecord.value?.IsApproved ?? false) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.isSOTrx == (lastRecord.value?.IsSOTrx ?? true) &&
    form.value.isPrinted == (lastRecord.value?.IsPrinted ?? false) &&
    form.value.dateAcct == (lastRecord.value?.DateAcct || date.now('date')) &&
    form.value.movementDate == (lastRecord.value?.MovementDate || date.now('date')) &&
    form.value.poReference == (lastRecord.value?.POReference || '') &&
    form.value.freightAmt == (lastRecord.value?.FreightAmt || 0) &&
    form.value.chargeAmt == (lastRecord.value?.ChargeAmt || 0) &&
    form.value.dateOrdered == (lastRecord.value?.DateOrdered || date.now('date')) &&
    form.value.sendEMail == (lastRecord.value?.SendEMail ?? false) &&
    form.value.noPackages == (lastRecord.value?.NoPackages || 0) &&
    form.value.isInTransit == (lastRecord.value?.IsInTransit ?? false) &&
    form.value.isInDispute == (lastRecord.value?.IsInDispute ?? false) &&
    form.value.volume == (lastRecord.value?.Volume || 0) &&
    form.value.weight == (lastRecord.value?.Weight || 0) &&
    form.value.isDropShip == (lastRecord.value?.IsDropShip ?? false) &&
    form.value.processedOn == (lastRecord.value?.ProcessedOn || 0) &&
    form.value.isAlternateReturnAddress == (lastRecord.value?.IsAlternateReturnAddress ?? false) &&
    form.value.movementTypeId == (lastRecord.value?.MovementType?.id || 'C-') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.dropShipPartnerId == (lastRecord.value?.DropShip_BPartner_ID?.id || '') &&
    form.value.dropShipPartnerLocationId == (lastRecord.value?.DropShip_Location_ID?.id || '') &&
    form.value.dropShipUserId == (lastRecord.value?.DropShip_User_ID?.id || '') &&
    form.value.returnPartnerId == (lastRecord.value?.Return_BPartner_ID?.id || '') &&
    form.value.returnPartnerLocationId == (lastRecord.value?.Return_Location_ID?.id || '') &&
    form.value.returnUserId == (lastRecord.value?.Return_User_ID?.id || '') &&
    form.value.warehouseId == (lastRecord.value?.M_Warehouse_ID?.id || '') &&
    form.value.deliveryRuleId == (lastRecord.value?.DeliveryRule?.id || '') &&
    form.value.freightCostRuleId == (lastRecord.value?.FreightCostRule?.id || '') &&
    form.value.deliveryViaRuleId == (lastRecord.value?.DeliveryViaRule?.id || '') &&
    form.value.priorityRuleId == (lastRecord.value?.PriorityRule?.id || '') &&
    form.value.orderId == (lastRecord.value?.C_Order_ID?.id || '') &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || 'DR') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '') &&
    form.value.rmaId == (lastRecord.value?.M_RMA_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/sales/returns/${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(window('partners')?.path || '/sales/returns')
    let newUrl = '/sales/returns'
    if(windowParam.value?.[windowFrom.value]?.path) {
      newUrl = windowParam.value[windowFrom.value].path
    }
    router.push(newUrl)
    if(windowParam.value?.[windowFrom.value]?.path) {
      windowFrom.value = ''
      windowParam.value = {}
    }
  }
}

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/inouts/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      description: form.value.description,
      isApproved: form.value.isApproved,
      processed: form.value.processed,
      isSOTrx: form.value.isSOTrx,
      isPrinted: form.value.isPrinted,
      dateAcct: form.value.dateAcct,
      movementDate: form.value.movementDate,
      poReference: form.value.poReference,
      freightAmt: form.value.freightAmt,
      chargeAmt: form.value.chargeAmt,
      dateOrdered: form.value.dateOrdered,
      sendEMail: form.value.sendEMail,
      noPackages: form.value.noPackages,
      isInTransit: form.value.isInTransit,
      isInDispute: form.value.isInDispute,
      volume: form.value.volume,
      weight: form.value.weight,
      isDropShip: form.value.isDropShip,
      processedOn: form.value.processedOn,
      isAlternateReturnAddress: form.value.isAlternateReturnAddress,
      movementTypeId: form.value.movementTypeId,
      docTypeId: form.value.docTypeId,
      returnPartnerId: form.value.returnPartnerId,
      returnPartnerLocationId: form.value.returnPartnerLocationId,
      returnUserId: form.value.returnUserId,
      warehouseId: form.value.warehouseId,
      deliveryRuleId: form.value.deliveryRuleId,
      freightCostRuleId: form.value.freightCostRuleId,
      deliveryViaRuleId: form.value.deliveryViaRuleId,
      priorityRuleId: form.value.priorityRuleId,
      orderId: form.value.orderId,
      docStatusId: form.value.docStatusId,
      salesRepId: form.value.salesRepId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
      rmaId: form.value.rmaId,
    }
  })

  if(Number(res.status) === 200) {
    windowFrom.value = ''
    windowParam.value = {}
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      router.push('/sales/returns/'+res.id+'/view')
    } else if(saveType === 'changes' || 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
    })
    //window.scrollTo(0, 0)
  }
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '#', text: 'Sales'},
  { link: '/sales/returns', text: 'Customer Returns'},
  { link: '#', text: 'Edit Return', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'warehouse', text: 'Warehouse'},
  { value: 'shipment', text: 'Shipment'},
  { value: 'reference', text: 'Reference'},
  { value: 'status', text: 'Status'}
]))

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

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/inouts/'+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>Edit Return</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.docTypeId === '' || form.dateOrdered === '' || form.dateAcct === '' || form.returnPartnerId === '' || form.returnPartnerLocationId === '' || form.freightCostRuleId === '' || form.warehouseId === '' || form.docStatusId === 'CO' || 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.docTypeId === '' || form.dateOrdered === '' || form.dateAcct === '' || form.returnPartnerId === '' || form.returnPartnerLocationId === '' || form.freightCostRuleId === '' || form.warehouseId === '' || form.docStatusId === 'CO' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="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' && form.docStatusId !== 'VO' && form.docStatusId !== 'RE'">
            <button type="button" @click="setDocumentAction('CO')" class="button" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">Complete</button>
          </template>
          <button type="button" @click="setDocumentAction('VO')" class="button" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">Void</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 class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <SalesReturnForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div>
        <SalesReturnDetailRecord action="edit" :info="form" tab="inout_line" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="RS_InOut" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>