<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 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 lines = ref([])
const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  documentNo: '',
  movementDate: date.now('date'),
  approvalAmt: 0,
  chargeAmt: 0,
  freightAmt: 0,
  description: '',
  poReference: '',
  isActive: true,
  isApproved: false,
  isInTransit: false,
  warehouse: warehouse.value?.Name || '',
  warehouseId: warehouseId.value || '',
  warehouseTo: '',
  warehouseToId: '',
  docType: '',
  docTypeId: '',
  shipper: '',
  shipperId: '',
  salesRep: user.value?.Name ?? '',
  salesRepId: user.value?.id ?? userId.value ?? '',
  user: '',
  userId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  freightCostRule: '',
  freightCostRuleId: '',
  priorityRule: '',
  priorityRuleId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  processed: false,
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/materials/stock-transfers/'+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 || '',
      documentNo: '',
      movementDate: res?.MovementDate || '',
      approvalAmt: 0,
      chargeAmt: 0,
      freightAmt: 0,
      description: res?.Description || '',
      poReference: res?.POReference || '',
      isActive: true,
      isApproved: false,
      isInTransit: false,
      processed: false,
      processing: false,
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      warehouseTo: res?.M_WarehouseTo_ID?.identifier || '',
      warehouseToId: res?.M_WarehouseTo_ID?.id || '',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      shipper: res?.M_Shipper_ID?.identifier || '',
      shipperId: res?.M_Shipper_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_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 || '',
      freightCostRule: res?.FreightCostRule?.identifier || '',
      freightCostRuleId: res?.FreightCostRule?.id || '',
      priorityRule: res?.PriorityRule?.identifier || '',
      priorityRuleId: res?.PriorityRule?.id || '',
      deliveryRule: res?.DeliveryRule?.identifier || '',
      deliveryRuleId: res?.DeliveryRule?.id || '',
      deliveryViaRule: res?.DeliveryViaRule?.identifier || '',
      deliveryViaRuleId: res?.DeliveryViaRule?.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: 'Draft',
      docStatusId: 'DR',
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
  
    setActiveSave()
  }
}
onMounted(retrieve)

const checkRequiredLines = computed(() => {
  return lines.value.filter(i => i.locatorId === '' || i.locatorToId === '' || i.line === '' ||  i.productId === '' || i.movementQty === '' || i.targetQty === '').length >= 1
})

const setActiveSave = () => {
  if(form.value.movementDate !== '' && form.value.docTypeId !== '' && !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('/materials/stock-transfers')
  }
}

const save = async (record) => {
  form.value = record
  
  setActiveSave()
}

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

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

  let newObjValue = {}
  if(lines.value.length >= 1) {
    newObjValue = {...newObjValue, 
      movementLines: lines.value.map(entry => {
        let newObjEntry = {}
        if(entry.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: entry.productId
            }
          }
        }
        if(entry.locatorId) {
          newObjEntry = {...newObjEntry, 
            M_Locator_ID: {
              id: entry.locatorId,
              tableName: 'M_Locator'
            }
          }
        }
        if(entry.locatorToId) {
          newObjEntry = {...newObjEntry, 
            M_LocatorTo_ID: {
              id: entry.locatorToId,
              tableName: 'M_Locator'
            }
          }
        }
        if(entry.attributeSetInstanceId) {
          newObjEntry = {...newObjEntry, 
            M_AttributeSetInstance_ID: {
              id: entry.attributeSetInstanceId,
              tableName: 'M_AttributeSetInstance'
            }
          }
        }
        if(entry.attributeSetInstanceToId) {
          newObjEntry = {...newObjEntry, 
            M_AttributeSetInstanceTo_ID: {
              id: entry.attributeSetInstanceToId,
              tableName: 'M_AttributeSetInstance'
            }
          }
        }
        if(entry.movementId) {
          newObjEntry = {...newObjEntry, 
            M_Movement_ID: {
              id: entry.movementId,
              tableName: 'M_Movement'
            }
          }
        }

        return {
          line: entry.line,
          isActive: entry.isActive,
          movementQty: entry?.movementQty || 0,
          targetQty: entry?.targetQty || 0,
          scrappedQty: entry?.scrappedQty || 0,
          confirmedQty: entry?.confirmedQty || 0,
          description: entry.description,
          ...newObjEntry
        }
      })
    }
  }

  const res = await $fetch('/api/materials/stock-transfers/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      documentNo: form.value.documentNo,
      movementDate: form.value.movementDate,
      approvalAmt: form.value.approvalAmt,
      chargeAmt: form.value.chargeAmt,
      freightAmt: form.value.freightAmt,
      description: form.value.description,
      poReference: form.value.poReference,
      isActive: form.value.isActive,
      isApproved: form.value.isApproved,
      isInTransit: form.value.isInTransit,
      warehouseId: form.value.warehouseId,
      warehouseToId: form.value.warehouseToId,
      docTypeId: form.value.docTypeId,
      shipperId: form.value.shipperId,
      salesRepId: form.value.salesRepId,
      userId: form.value.userId,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      freightCostRuleId: form.value.freightCostRuleId,
      priorityRuleId: form.value.priorityRuleId,
      deliveryRuleId: form.value.deliveryRuleId,
      deliveryViaRuleId: form.value.deliveryViaRuleId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
      docStatusId: form.value.docStatusId,
      processed: form.value.processed,
      processing: form.value.processing,
      ...newObjValue
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/materials/stock-transfers/' + res.id + '/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/materials/stock-transfers/'+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: 'Materials'},
  { link: '/materials/stock-transfers', text: 'Stock Transfers'},
  { link: '#', text: 'Add Stock Transfer', active: true}
]))

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

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

<template>
  <Head>
    <Title>Add Stock Transfer</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.movementDate === '' || form.docTypeId === '' || 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>
        <MaterialsStockTransferForm v-model="form" v-model:tab="tab" @save="save"/>
      </div>
      <div>
        <MaterialsStockTransferLineTable v-model="lines" action="create" :info="form" @save="saveLines" />
      </div>
    </div>
  </NuxtLayout>
</template>