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

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()
const printPreview = usePrintPreview()
const printParam = usePrintParam()

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

const showDocumentAction = ref(false)
const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  warehouse: '',
  warehouseId: '',
  isActive: true,
  documentNo: '',
  poReference: '',
  description: '',
  isApproved: false,
  isCreditApproved: false,
  isDelivered: false,
  isInvoiced: false,
  isPrinted: false,
  isTransferred: false,
  dateOrdered: date.now('date'),
  datePromised: date.now('date'),
  dateAcct: date.now('date'),
  freightAmt: 0,
  totalLines: 1,
  grandTotal: 0,
  chargeAmt: 0,
  processed: false,
  isSOTrx: false,
  isDiscountPrinted: false,
  isTaxIncluded: false,
  isSelected: false,
  sendEMail: false,
  isSelfService: false,
  isDropShip: false,
  processedOn: 0,
  isPayScheduleValid: false,
  isPriviledgedRate: false,
  docStatus: '',
  docStatusId: 'DR',
  docType: '',
  docTypeId: 0,
  docTypeTarget: '',
  docTypeTargetId: '',
  salesRep: '',
  salesRepId: '',
  paymentTerm: '',
  paymentTermId: '',
  currency: '',
  currencyId: '',
  invoiceRule: '',
  invoiceRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  priorityRule: '',
  priorityRuleId: '',
  freightCostRule: '',
  freightCostRuleId: '',
  paymentRule: '',
  paymentRuleId: '',
  priceList: '',
  priceListId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  cashLine: '',
  cashLineId: '',
  billPartner: '',
  billPartnerId: '',
  billPartnerLocation: '',
  billPartnerLocationId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  shipper: '',
  shipperId: '',
  freightCategory: '',
  freightCategoryId:  '',
  user: '',
  userId:  '',
  billUser: '',
  billUserId:  '',
  promotionCode: '',
  dropShipPartner: '',
  dropShipPartnerId: '',
  dropShipPartnerLocation: '',
  dropShipPartnerLocationId: '',
  dropShipUser: '',
  dropShipUserId:  '',
  conversionType: '',
  conversionTypeId:  '',
  orderSource: '',
  orderSourceId:  '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/orders/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      uid: res?.uid ?? string.uniqid(route.params.id),
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      isActive: res?.IsActive ?? true,
      documentNo: res?.DocumentNo || '',
      poReference: res?.POReference || '',
      description: res?.Description || '',
      isApproved: res?.IsApproved ?? false,
      isCreditApproved: res?.IsCreditApproved ?? false,
      isDelivered: res?.IsDelivered ?? false,
      isInvoiced: res?.IsInvoiced ?? false,
      isPrinted: res?.IsPrinted ?? false,
      isTransferred: res?.IsTransferred ?? false,
      dateOrdered: res?.DateOrdered || date.now('date'),
      datePromised: res?.DatePromised || date.now('date'),
      dateAcct: res?.DateAcct || date.now('date'),
      freightAmt: res?.FreightAmt || 0,
      totalLines: res?.TotalLines || 0,
      grandTotal: res?.GrandTotal || 0,
      chargeAmt: res?.ChargeAmt || 0,
      processed: res?.Processed ?? false,
      isSOTrx: res?.IsSOTrx ?? false,
      isDiscountPrinted: res?.IsDiscountPrinted ?? false,
      isTaxIncluded: res?.IsTaxIncluded ?? false,
      isSelected: res?.IsSelected ?? false,
      sendEMail: res?.SendEMail ?? false,
      isSelfService: res?.IsSelfService ?? false,
      isDropShip: res?.IsDropShip ?? false,
      processedOn: res?.ProcessedOn || 0,
      isPayScheduleValid: res?.IsPayScheduleValid ?? false,
      isPriviledgedRate: res?.IsPriviledgedRate ?? false,
      docStatus: res?.DocStatus?.identifier || '',
      docStatusId: res?.DocStatus?.id || '',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      docTypeTarget: res?.C_DocTypeTarget_ID?.identifier || '',
      docTypeTargetId: res?.C_DocTypeTarget_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      paymentTerm: res?.C_PaymentTerm_ID?.identifier || '',
      paymentTermId: res?.C_PaymentTerm_ID?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      invoiceRule: res?.InvoiceRule?.identifier || '',
      invoiceRuleId: res?.InvoiceRule?.id || '',
      deliveryViaRule: res?.DeliveryViaRule?.identifier || '',
      deliveryViaRuleId: res?.DeliveryViaRule?.id || '',
      deliveryRule: res?.DeliveryRule?.identifier || '',
      deliveryRuleId: res?.DeliveryRule?.id || '',
      priorityRule: res?.PriorityRule?.identifier || '',
      priorityRuleId: res?.PriorityRule?.id || '',
      freightCostRule: res?.FreightCostRule?.identifier || '',
      freightCostRuleId: res?.FreightCostRule?.id || '',
      paymentRule: res?.PaymentRule?.identifier || '',
      paymentRuleId: res?.PaymentRule?.id || '',
      priceList: res?.M_PriceList_ID?.identifier || '',
      priceListId: res?.M_PriceList_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      partnerLocation: res?.C_BPartner_Location_ID?.identifier || res?.C_BPartner_Location_ID?.Name || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      cashLine: res?.C_CashLine_ID?.identifier || '',
      cashLineId: res?.C_CashLine_ID?.id || '',
      billPartner: res?.Bill_BPartner_ID?.identifier || '',
      billPartnerId: res?.Bill_BPartner_ID?.id || '',
      billPartnerLocation: res?.Bill_Location_ID?.identifier || '',
      billPartnerLocationId: res?.Bill_Location_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 || '',
      shipper: res?.M_Shipper_ID?.identifier || '',
      shipperId: res?.M_Shipper_ID?.id || '',
      freightCategory: res?.M_FreightCategory_ID?.identifier || '',
      freightCategoryId: res?.M_FreightCategory_ID?.id || '',
      user: res?.AD_User_ID?.identifier || '',
      userId:  res?.AD_User_ID?.id || '',
      billUser: res?.Bill_User_ID?.identifier || '',
      billUserId:  res?.Bill_User_ID?.id || '',
      promotionCode: res?.PromotionCode || '',
      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 || '',
      conversionType: res?.C_ConversionType_ID?.identifier || '',
      conversionTypeId:  res?.C_ConversionType_ID?.id || '',
      orderSource: res?.C_OrderSource_ID?.identifier || '',
      orderSourceId: res?.C_OrderSource_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.warehouseId == (lastRecord.value?.M_Warehouse_ID?.id || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.documentNo == (lastRecord.value?.DocumentNo || '') &&
    form.value.poReference == (lastRecord.value?.poReference || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isApproved == (lastRecord.value?.IsApproved ?? false) &&
    form.value.isCreditApproved == (lastRecord.value?.IsCreditApproved ?? false) &&
    form.value.isDelivered == (lastRecord.value?.IsDelivered ?? false) &&
    form.value.isInvoiced == (lastRecord.value?.IsInvoiced ?? false) &&
    form.value.isPrinted == (lastRecord.value?.IsPrinted ?? false) &&
    form.value.isTransferred == (lastRecord.value?.IsTransferred ?? false) &&
    form.value.dateOrdered == (lastRecord.value?.DateOrdered || date.now('date')) &&
    form.value.datePromised == (lastRecord.value?.DatePromised || date.now('date')) &&
    form.value.dateAcct == (lastRecord.value?.DateAcct || date.now('date')) &&
    form.value.freightAmt == (lastRecord.value?.FreightAmt || 0) &&
    form.value.totalLines == (lastRecord.value?.TotalLines || 0) &&
    form.value.grandTotal == (lastRecord.value?.GrandTotal || 0) &&
    form.value.chargeAmt == (lastRecord.value?.ChargeAmt || 0) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.isSOTrx == (lastRecord.value?.IsSOTrx ?? false) &&
    form.value.isDiscountPrinted == (lastRecord.value?.IsDiscountPrinted ?? false) &&
    form.value.isTaxIncluded == (lastRecord.value?.IsTaxIncluded ?? false) &&
    form.value.isSelected == (lastRecord.value?.IsSelected ?? false) &&
    form.value.sendEMail == (lastRecord.value?.SendEMail ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.isDropShip == (lastRecord.value?.IsDropShip ?? false) &&
    form.value.processedOn == (lastRecord.value?.ProcessedOn || 0) &&
    form.value.isPayScheduleValid == (lastRecord.value?.IsPayScheduleValid ?? false) &&
    form.value.isPriviledgedRate == (lastRecord.value?.IsPriviledgedRate ?? false) &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || '') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || '') &&
    form.value.docTypeTargetId == (lastRecord.value?.C_DocTypeTarget_ID?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.paymentTermId == (lastRecord.value?.C_PaymentTerm_ID?.id || '') &&
    form.value.currencyId == (lastRecord.value?.C_Currency_ID?.id || '') &&
    form.value.invoiceRuleId == (lastRecord.value?.InvoiceRule?.id || '') &&
    form.value.deliveryViaRuleId == (lastRecord.value?.DeliveryViaRule?.id || '') &&
    form.value.deliveryRuleId == (lastRecord.value?.DeliveryRule?.id || '') &&
    form.value.priorityRuleId == (lastRecord.value?.PriorityRule?.id || '') &&
    form.value.freightCostRuleId == (lastRecord.value?.FreightCostRule?.id || '') &&
    form.value.paymentRuleId == (lastRecord.value?.PaymentRule?.id || '') &&
    form.value.priceListId == (lastRecord.value?.M_PriceList_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.cashLineId == (lastRecord.value?.C_CashLine_ID?.id || '') &&
    form.value.billPartnerId == (lastRecord.value?.Bill_BPartner_ID?.id || '') &&
    form.value.billPartnerLocationId == (lastRecord.value?.Bill_Location_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '') &&
    form.value.shipperId == (lastRecord.value?.M_Shipper_ID?.id || '') &&
    form.value.freightCategoryId == (lastRecord.value?.M_FreightCategory_ID?.id || '') &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.billUserId == (lastRecord.value?.Bill_User_ID?.id || '') &&
    form.value.promotionCode == (lastRecord.value?.PromotionCode || '') &&
    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.conversionTypeId == (lastRecord.value?.C_ConversionType_ID?.id || '') &&
    form.value.orderSourceId == (lastRecord.value?.C_OrderSource_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/procurements/orders/${route.params.id}/duplicate`)
}
const print = () => {
  //router.push(`/procurements/orders/${route.params.id}/print`)
  printParam.value = form.value
  printPreview.value = true
}

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('/procurements/orders')
  }
}

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/orders/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      POReference: form.value.poReference,
      description: form.value.description,
      isApproved: form.value.isApproved,
      isCreditApproved: form.value.isCreditApproved,
      isDelivered: form.value.isDelivered,
      isInvoiced: form.value.isInvoiced,
      isPrinted: form.value.isPrinted,
      isTransferred: form.value.isTransferred,
      dateOrdered: form.value.dateOrdered,
      datePromised: form.value.datePromised,
      dateAcct: form.value.dateAcct,
      freightAmt: form.value.freightAmt,
      totalLines: form.value.totalLines,
      grandTotal: form.value.grandTotal,
      chargeAmt: form.value.chargeAmt,
      processed: form.value.processed,
      isSOTrx: false,
      isDiscountPrinted: form.value.isDiscountPrinted,
      isTaxIncluded: form.value.isTaxIncluded,
      isSelected: form.value.isSelected,
      sendEMail: form.value.sendEMail,
      isSelfService: form.value.isSelfService,
      isDropShip: form.value.isDropShip,
      processedOn: form.value.processedOn,
      isPayScheduleValid: form.value.isPayScheduleValid,
      isPriviledgedRate: form.value.isPriviledgedRate,
      docStatusId: form.value.docStatusId,
      docTypeId: form.value.docTypeId,
      docTypeTargetId: form.value.docTypeTargetId,
      salesRepId: form.value.salesRepId,
      paymentTermId: form.value.paymentTermId,
      currencyId: form.value.currencyId,
      invoiceRuleId: form.value.invoiceRuleId,
      deliveryViaRuleId: form.value.deliveryViaRuleId,
      deliveryRuleId: form.value.deliveryRuleId,
      priorityRuleId: form.value.priorityRuleId,
      freightCostRuleId: form.value.freightCostRuleId,
      paymentRuleId: form.value.paymentRuleId,
      warehouseId: form.value.warehouseId,
      priceListId: form.value.priceListId,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      cashLineId: form.value.cashLineId,
      billPartnerId: form.value.billPartnerId,
      billPartnerLocationId: form.value.billPartnerLocationId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
      shipperId: form.value.shipperId,
      freightCategoryId: form.value.freightCategoryId,
      userId: form.value.userId,
      billUserId: form.value.billUserId,
      dropShipPartnerId: form.value.dropShipPartnerId,
      dropShipPartnerLocationId: form.value.dropShipPartnerLocationId,
      dropShipUserId:  form.value.dropShipUserId,
      conversionTypeId:  form.value.conversionTypeId,
      orderSourceId:  form.value.orderSourceId,
      promotionCode: form.value.promotionCode,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      router.push('/procurements/orders/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
      // 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
    })
    //window.scrollTo(0, 0)
  }
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '#', text: 'Procurements'},
  { link: '/procurements/orders', text: 'Orders'},
  { link: '#', text: 'Edit Order', active: true}
]))

const tab = ref(route.query?.tab || 'order')
const tabs = computed(() => ([
  { value: 'order', text: 'Order'},
  { value: 'delivery', text: 'Delivery'},
  { value: 'invoicing', text: 'Invoicing'},
  { value: 'reference', text: 'Reference'},
  { value: 'status', text: 'Status'}
]))

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/orders/'+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 Order</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.paymentRuleId === '' || form.paymentTermId === '' || form.dateOrdered === '' || form.datePromised === '' || form.partnerId === '' || form.partnerLocationId === '' || form.warehouseId === '' || form.deliveryViaRuleId === '' || form.priorityRuleId === '' || form.priceListId === '' || form.currencyId === '' || form.salesRepId === '' || form.docStatusId === 'CO' || (form.isDropShip && (form.dropShipPartnerId === '' || form.dropShipPartnerLocationId === '')) || 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.paymentRuleId === '' || form.paymentTermId === '' || form.dateOrdered === '' || form.datePromised === '' || form.partnerId === '' || form.partnerLocationId === '' || form.warehouseId === '' || form.deliveryViaRuleId === '' || form.priorityRuleId === '' || form.priceListId === '' || form.currencyId === '' || form.salesRepId === '' || form.docStatusId === 'CO' || (form.isDropShip && (form.dropShipPartnerId === '' || form.dropShipPartnerLocationId === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.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>
          
          <button type="button" class="button" @click="print();">Print Preview</button>

          <template v-if="form.docStatusId !== 'CO' && form.docStatusId !== 'VO'">
            <button type="button" class="button" @click="setDocumentAction('CO')">Complete</button>
          </template>
          <template v-if="form.docStatusId === 'CO' || form.docStatusId === 'RE'">
            <button type="button" class="button" @click="setDocumentAction('CL')">Close</button>
          </template>
          <template v-if="form.docStatusId === 'CO' || form.docStatusId === 'VO' || form.docStatusId === 'CL'">
            <button type="button" class="button" @click="setDocumentAction('RE')">Re-activate</button>
          </template>
          <button type="button" class="button" @click="setDocumentAction('VO')">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>
        <ProcurementsOrderForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div>
        <ProcurementsOrderDetailRecord action="edit" :info="form" tab="order_line" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="PO_Order" :info="form" />
      </div>
    </div>
    
    <Teleport to="body">
      <PrintPreview modelName="orders" />
      <ProcurementsOrderDocumentAction v-model="showDocumentAction" :id="form.id" v-model:docId="form.docStatusId"/>
    </Teleport>
  </NuxtLayout>
</template>