<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 user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  strapiProductId: '',
  strapiProductDocumentId: '',
  name: '',
  sku: '',
  upc: '',
  isActive: true,
  value: '',
  versionNo: '',
  description: '',
  help: '',
  documentNote: '',
  isSummary: false,
  isStocked: true,
  isPurchased: true,
  isSold: true,
  volume: 0,
  weight: 0,
  width: 0,
  length: 0, 
  height: 0,
  discontinued: false,
  isBOM: false,
  isInvoicePrintDetails: false,
  isPickListPrintDetails: false,
  isVerified: false,
  guaranteeDaysMin: 0,
  isWebStoreFeatured: false,
  isSelfService: false,
  isDropShip: false,
  isExcludeAutoDelivery: false,
  unitsPerPack: 0,
  lowLevel: 0,
  isKanban: false,
  isManufactured: false,
  isPhantom: false,
  isOwnBox: false,
  isAutoProduce: false,
  shelfWidth: 0,
  shelfHeight: 0,
  shelfDepth: 0,
  unitsPerPallet: 0,
  classification: '',
  customsTariffNumber: 0,
  group1: '',
  group2: '',
  asin: '',
  mpn: '',
  uom: '',
  uomId: '',
  productCategory: '',
  productCategoryId: '',
  taxCategory: '',
  taxCategoryId: '',
  productType: 'I',
  productTypeId: 'I',
  attributeSet: '',
  attributeSetId: '',
  attributeSetInstance: '',
  attributeSetInstanceId: '',
  revenueRecognition: '',
  revenueRecognitionId: '',
  salesRep: user.value?.Name ?? '',
  salesRepId: user.value?.id ?? userId.value ?? '',
  mailText: '',
  mailTextId: '',
  labelPrinter: 'labelprinter-2',
  labelPrinterId: 'b',
  qtyonhand: 0, 
  qtyreserved: 0, 
  qtyavilable: 0, 
  qtypurchased: 0,
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: 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/products')
  }
}

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

  if(form.value.name !== '' && form.value.productTypeId !== '' && form.value.productCategoryId !== '' && form.value.uomId !== '' && form.value.taxCategoryId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

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

  const res = await $fetch('/api/materials/products/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      name: form.value.name,
      sku: form.value.sku,
      upc: form.value.upc,
      isActive: form.value.isActive,
      value: form.value.value,
      versionNo: form.value.versionNo,
      description: form.value.description,
      help: form.value.help,
      documentNote: form.value.documentNote,
      isSummary: form.value.isSummary,
      isStocked: form.value.isStocked,
      isPurchased: form.value.isPurchased,
      isSold: form.value.isSold,
      volume: form.value.volume,
      weight: form.value.weight,
      discontinued: form.value.discontinued,
      isBOM: form.value.isBOM,
      isInvoicePrintDetails: form.value.isInvoicePrintDetails,
      isPickListPrintDetails: form.value.isPickListPrintDetails,
      isVerified: form.value.isVerified,
      guaranteeDaysMin: form.value.guaranteeDaysMin,
      isWebStoreFeatured: form.value.isWebStoreFeatured,
      isSelfService: form.value.isSelfService,
      isDropShip: form.value.isDropShip,
      isExcludeAutoDelivery: form.value.isExcludeAutoDelivery,
      unitsPerPack: form.value.unitsPerPack,
      lowLevel: form.value.lowLevel,
      isKanban: form.value.isKanban,
      isManufactured: form.value.isManufactured,
      isPhantom: form.value.isPhantom,
      isOwnBox: form.value.isOwnBox,
      isAutoProduce: form.value.isAutoProduce,
      shelfWidth: form.value.shelfWidth,
      shelfHeight: form.value.shelfHeight,
      shelfDepth: form.value.shelfDepth,
      unitsPerPallet: form.value.unitsPerPallet,
      classification: form.value.classification,
      customsTariffNumber: form.value.customsTariffNumber,
      group1: form.value.group1,
      group2: form.value.group2,
      uomId: form.value.uomId,
      productCategoryId: form.value.productCategoryId,
      taxCategoryId: form.value.taxCategoryId,
      productTypeId: form.value.productTypeId,
      attributeSetId: form.value.attributeSetId,
      attributeSetInstanceId: form.value.attributeSetInstanceId,
      revenueRecognitionId: form.value.revenueRecognitionId,
      salesRepId: form.value.salesRepId,
      mailTextId: form.value.mailTextId,
      labelPrinterId: form.value.labelPrinterId,
      asin: form.value.asin,
      mpn: form.value.mpn,
    }
  })

  if(Number(res.status) === 200 && Number(res.id) !== 0) {
    form.value.alert.processing = false
    activeSave.value = false

    if(saveType === 'preview') {
      router.push('/materials/products/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/materials/products/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 7500,
        position: 'bottom-right'
      })
    } 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: 7500,
      position: 'bottom-right'
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/products', text: 'Products'},
  { link: '#', text: 'Add Product', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'classification', text: 'Classification'},
  { value: 'gallery', text: 'Gallery'},
  { value: 'reference', text: 'Reference'},
  { value: 'status', text: 'Status'}
]))

const openOtherTab = () => {
  if(tab.value === 'basic') {
    tab.value = 'classification'
  } else if(tab.value === 'classification') {
    tab.value = 'gallery'
  } else if(tab.value === 'gallery') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'status'
  }
}
</script>

<template>
  <Head>
    <Title>Add Product</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.productTypeId === '' || form.productCategoryId === '' || form.uomId === '' || form.taxCategoryId === '' || 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>
        <MaterialsProductForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <MaterialsProductDetailRecord action="create" :info="form" tab="product_price" />
      </div>
    </div>
  </NuxtLayout>
</template>