<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 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: '',
  userId: '',
  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: '',
  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: '',
      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: '',
      description: res?.Description || '',
      isApproved: false,
      processed: false,
      isSOTrx: true,
      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: false,
      isInDispute: false,
      volume: res?.Volume || 0,
      weight: res?.Weight || 0,
      isDropShip: res?.IsDropShip ?? false,
      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: 'Draft',
      docStatusId: '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
      }
    }

    lines.value = res.m_inoutline.map(item => {
      return {
        id: '',
        client: item?.AD_Client_ID?.identifier || '',
        clientId: item?.AD_Client_ID?.id || '',
        organization: item?.AD_Org_ID?.identifier || '',
        organizationId: item?.AD_Org_ID?.id || '',
        warehouse: item?.M_Warehouse_ID?.identifier || '',
        warehouseId: item?.M_Warehouse_ID?.id || '',
        inOut: item?.M_InOut_ID?.identifier || '',
        inOutId: item?.M_InOut_ID?.id || '',
        locator: item?.M_Locator_ID?.identifier || item?.M_Locator_ID?.Value || '',
        locatorId: item?.M_Locator_ID?.id || '',
        product: item?.M_Product_ID?.Name || '',
        productId: item?.M_Product_ID?.id || '',
        galleries: [],
        isActive: item?.IsActive ?? true,
        line: item?.Line || '',
        isAutoProduce: item?.IsAutoProduce ?? false,
        qtyEntered: item?.QtyEntered || 1,
        processed: item?.Processed ?? false,
        targetQty: item?.TargetQty || 0,
        scrappedQty: item?.ScrappedQty || 0,
        pickedQty: item?.PickedQty || 0,
        confirmedQty: item?.ConfirmedQty || 0,
        isDescription: item?.IsDescription ?? false,
        isInvoiced: item?.IsInvoiced ?? false,
        description: item?.Description || '',
        movementQty: item?.MovementQty || 1,
        orderLine: item?.C_OrderLine_ID?.identifier || '',
        orderLineId: item?.C_OrderLine_ID?.id || '',
        uom: item?.C_UOM_ID?.identifier || '',
        uomId: item?.C_UOM_ID?.id || '',
        attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
        attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
        project: item?.C_Project_ID?.identifier || '',
        projectId: item?.C_Project_ID?.id || '',
        campaign: item?.C_Campaign_ID?.identifier || '',
        campaignId: item?.C_Campaign_ID?.id || '',
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    })
    
    const newEntries = []
    for(let item of lines.value) {
      const response = await $fetch(`/api/materials/products/${item.productId}`)
      if(response?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
        if(resp) {
          item.galleries = resp
        }
      }
      newEntries.push(item)
    }
    lines.value = newEntries
  
    setActiveSave()
  }
}
onMounted(retrieve)

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/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
  
  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
        }
      })
    }
  }

  const res = await $fetch('/api/inouts/store', {
    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,
      ...newObjValue
    }
  })

  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') {
      router.push('/sales/returns/'+res.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/returns', text: 'Customer Returns'},
  { 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.docTypeId === '' || form.dateOrdered === '' || form.dateAcct === '' || form.partnerId === '' || form.partnerLocationId === '' || form.freightCostRuleId === '' || form.warehouseId === '' || form.priorityRuleId === '' || 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>
        <SalesReturnForm 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>