<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 client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

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

const lines = ref([])
const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  warehouse: warehouse.value?.Name || '',
  warehouseId: warehouseId.value || '',
  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: window('partners')?.data?.identifier || '',
  partnerId: window('partners')?.data?.id || '',
  partnerLocation: '',
  partnerLocationId: '',
  user: user.value?.Name || '',
  userId: user.value?.id || userId.value || '',
  dropShipPartner: window('partners')?.data?.identifier || '',
  dropShipPartnerId: window('partners')?.data?.id || '',
  dropShipPartnerLocation: '',
  dropShipPartnerLocationId: '',
  dropShipUser: '',
  dropShipUserId: '',
  returnPartner: window('partners')?.data?.identifier || '',
  returnPartnerId: window('partners')?.data?.id || '',
  returnPartnerLocation: '',
  returnPartnerLocationId: '',
  returnUser: '',
  returnUserId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  freightCostRule: '',
  freightCostRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  priorityRule: '',
  priorityRuleId: '',
  order: '',
  orderId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  salesRep: user.value?.Name || '',
  salesRepId: user.value?.id || userId.value || '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  name: '',
  inOut: '',
  inOutId: '',
  rmaType: '',
  rmaTypeId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const checkRequiredLines = computed(() => {
  return lines.value.filter(i => i.productId === '' || i.uomId === '' || i.qtyEntered === '' || i.locatorId === '' || i.orderLineId === '').length >= 1
})

const setActiveSave = () => {
  if(form.value.docTypeId !== '' && form.value.dateOrdered !== '' && form.value.dateAcct !== '' && form.value.partnerId !== '' && form.value.partnerLocationId !== '' && form.value.freightCostRuleId !== '' && form.value.warehouseId !== '' && form.value.priorityRuleId !== '' && form.value.orderId !== '' && !checkRequiredLines.value) {
    activeSave.value = true
  } else {
    activeSave.value = 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(window('partners')?.path || '/sales/returns')
    let newUrl = '/sales/orders'
    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
  
  setActiveSave()
}

const saveLines = async (inOutLines) => {
  lines.value = inOutLines
  
  setActiveSave()
}

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

  let newObjValue = {}
  if(lines.value.length >= 1) {
    newObjValue = {...newObjValue, 
      inOutLines: lines.value.map(entry => {
        let newObjEntry = {}
        if(entry.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: entry.productId
            }
          }
        }
        if(entry.uomId) {
          newObjEntry = {...newObjEntry, 
            C_UOM_ID: {
              id: entry.uomId
            }
          }
        }
        if(entry.locatorId) {
          newObjEntry = {...newObjEntry, 
            M_Locator_ID: {
              id: entry.locatorId
            }
          }
        }
        if(entry.orderLineId) {
          newObjEntry = {...newObjEntry, 
            C_OrderLine_ID: {
              id: entry.orderLineId
            }
          }
        }
        if(entry.attributeSetInstanceId) {
          newObjEntry = {...newObjEntry, 
            M_AttributeSetInstance_ID: {
              id: entry.attributeSetInstanceId
            }
          }
        }
        if(entry.projectId) {
          newObjEntry = {...newObjEntry, 
            C_Project_ID: {
              id: entry.projectId
            }
          }
        }
        if(entry.campaignId) {
          newObjEntry = {...newObjEntry, 
            C_Campaign_ID: {
              id: entry.campaignId
            }
          }
        }

        return {
          line: entry.line,
          isActive: entry.isActive,
          movementQty: entry?.movementQty || entry.qtyEntered,
          targetQty: entry?.targetQty || 0,
          scrappedQty: entry?.scrappedQty || 0,
          pickedQty: entry?.pickedQty || 0,
          confirmedQty: entry?.confirmedQty || 0,
          qtyEntered: entry.qtyEntered,
          isDescription: entry.isDescription,
          description: entry.description,
          isInvoiced: entry.isInvoiced,
          ...newObjEntry
        }
      }),
      rmaLines: lines.value.map(entry => {
        let newObjEntry = {}
        if(entry.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: entry.productId
            }
          }
        }
        /*if(entry.taxId) {
          newObjEntry = {...newObjEntry, 
            C_Tax_ID: {
              id: entry.taxId
            }
          }
        }
        if(entry.inOutLineId) {
          newObjEntry = {...newObjEntry, 
            M_InOutLine_ID: {
              id: entry.inOutLineId
            }
          }
        }
        if(entry.chargeId) {
          newObjEntry = {...newObjEntry, 
            C_Charge_ID: {
              id: entry.chargeId
            }
          }
        }*/
        
        return {
          AD_Org_ID: {
            id: form.value.organizationId,
            tableName: 'AD_Org'
          },
          line: entry.line,
          isActive: entry.isActive,
          qty: entry.qtyEntered,
          //processed: entry.processed ?? false,
          //amt: entry.amt,
          //taxAmt: entry.taxAmt,
          description: entry.description,
          //lineNetAmt: entry.lineNetAmt,
          ...newObjEntry
        }
      })
    }
  }

  const res = await $fetch('/api/inouts/quick-rma', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      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,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      userId: form.value.userId,
      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,
      name: form.value.name,
      inOutId: form.value.inOutId,
      rmaTypeId: form.value.rmaTypeId,
      ...newObjValue
    }
  })

  if(Number(res.status || 500) === 200) {
    windowFrom.value = ''
    windowParam.value = {}
    form.value.alert.processing = false
    activeSave.value = false

    //location.href = '/sales/orders'
    //console.log(res)
    toast({
      message: 'Saved!',
      type: 'is-success',
      duration: 2000
    })
    /*if(saveType === 'preview') {
      router.push('/sales/returns/'+res.customer_return.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/sales/returns/'+res.customer_return.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: '#', text: 'Sales'},
  { link: '/sales/orders', text: 'Orders'},
  { link: '#', text: 'Add 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'
  }
}
</script>

<template>
  <Head>
    <Title>Add 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.name === '' || form.rmaTypeId === '' || form.docTypeId === '' || form.dateOrdered === '' || form.dateAcct === '' || form.partnerId === '' || form.partnerLocationId === '' || form.freightCostRuleId === '' || form.warehouseId === '' || form.priorityRuleId === '' || form.orderId === '' || checkRequiredLines || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <button v-if="tab !== 'status'" type="button" @click="openOtherTab" class="button">Next</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 class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <SalesQuickReturnForm v-model="form" v-model:tab="tab" v-model:lines="lines" @save="save" />
      </div>
      <div>
        <SalesReturnLineTable v-model="lines" action="create" :info="form" @save="saveLines" />
      </div>
    </div>
  </NuxtLayout>
</template>