<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'
import shared from '@/assets/langs/shared.js'

const lang = ref('en-US')
const nuxtToast = useToast()
const getLang = computed(() => {
  return shared(lang.value)
})

const router = useRouter()
const route = useRoute()

const activeSave = useActiveSave()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

const { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')

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

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  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 storageCount = (storages, key) => {
  const newStorage = storages.map(i => i[key]).reduce((acc, prev) => Number(acc) + Number(prev), 0)
  return newStorage
}

const retrieve = async () => {
  const res = await $fetch('/api/materials/products/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    const qtyOnHand = storageCount(res?.M_Storage ?? [], 'QtyOnHand')
    const qtyReserved = storageCount(res?.M_Storage ?? [], 'QtyReserved')

    form.value = {
      id: route.params.id,
      uid: res?.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 || '',
      strapiProductId: res?.Strapi_Product_ID || '',
      strapiProductDocumentId: res?.Strapi_Product_documentId || '',
      name: res?.Name || '',
      sku: res?.SKU || '',
      upc: res?.UPC || '',
      isActive: res?.IsActive ?? true,
      value: res?.Value || '',
      versionNo: res?.VersionNo || '',
      description: res?.Description || '',
      help: res?.Help || '',
      documentNote: res?.DocumentNote || '',
      isSummary: res?.IsSummary ?? false,
      isStocked: res?.IsStocked ?? true,
      isPurchased: res?.IsPurchased ?? true,
      isSold: res?.IsSold ?? true,
      volume: res?.Volume || 0,
      weight: res?.Weight || 0,
      width: res?.width || res?.Width || 0,
      length: res?.length || res?.Length || 0, 
      height: res?.height || res?.Height || 0,
      discontinued: res?.Discontinued ?? false,
      isBOM: res?.IsBOM ?? false,
      isInvoicePrintDetails: res?.IsInvoicePrintDetails ?? false,
      isPickListPrintDetails: res?.IsPickListPrintDetails ?? false,
      isVerified: res?.IsVerified ?? false,
      guaranteeDaysMin: res?.GuaranteeDaysMin || 0,
      isWebStoreFeatured: res?.IsWebStoreFeatured ?? false,
      isSelfService: res?.IsSelfService ?? false,
      isDropShip: res?.IsDropShip ?? false,
      isExcludeAutoDelivery: res?.IsExcludeAutoDelivery ?? false,
      unitsPerPack: res?.UnitsPerPack || 0,
      lowLevel: res?.LowLevel || 0,
      isKanban: res?.IsKanban ?? false,
      isManufactured: res?.IsManufactured ?? false,
      isPhantom: res?.IsPhantom ?? false,
      isOwnBox: res?.IsOwnBox ?? false,
      isAutoProduce: res?.IsAutoProduce ?? false,
      shelfWidth: res?.ShelfWidth || 0,
      shelfHeight: res?.ShelfHeight || 0,
      shelfDepth: res?.ShelfDepth || 0,
      unitsPerPallet: res?.UnitsPerPallet || 0,
      classification: res?.Classification || '',
      customsTariffNumber: res?.CustomsTariffNumber || 0,
      group1: res?.Group1 || '',
      group2: res?.Group2 || '',
      asin: res?.asin || '',
      mpn: res?.mpn || '',
      uom: res?.C_UOM_ID?.identifier || '',
      uomId: res?.C_UOM_ID?.id || '',
      productCategory: res?.M_Product_Category_ID?.identifier || '',
      productCategoryId: res?.M_Product_Category_ID?.id || '',
      taxCategory: res?.C_TaxCategory_ID?.identifier || '',
      taxCategoryId: res?.C_TaxCategory_ID?.id || '',
      productType: res?.ProductType?.identifier || 'I',
      productTypeId: res?.ProductType?.id || 'I',
      attributeSet: res?.M_AttributeSet_ID?.identifier || '',
      attributeSetId: res?.M_AttributeSet_ID?.id || '',
      attributeSetInstance: res?.M_AttributeSetInstance_ID?.identifier || '',
      attributeSetInstanceId: res?.M_AttributeSetInstance_ID?.id || '',
      revenueRecognition: res?.C_RevenueRecognition_ID?.identifier || '',
      revenueRecognitionId: res?.C_RevenueRecognition_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      mailText: res?.R_MailText_ID?.identifier || '',
      mailTextId: res?.R_MailText_ID?.id || '',
      labelPrinter: res?.labelprinter?.identifier || 'labelprinter-2',
      labelPrinterId: res?.labelprinter?.id || 'b',
      qtyonhand: qtyOnHand, 
      qtyreserved: qtyReserved, 
      qtyavilable: Number(qtyOnHand) - Number(qtyReserved), 
      qtypurchased: storageCount(res?.M_Storage ?? [], 'QtyOrdered'),
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }
}
onMounted(() => {
  retrieve()
  defaultSideBarMenu.value = getMenuType()
})

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.strapiProductId == (lastRecord.value?.Strapi_Product_ID || '') &&
    form.value.strapiProductDocumentId == (lastRecord.value?.Strapi_Product_documentId || '') &&
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.sku == (lastRecord.value?.SKU || '') &&
    form.value.upc == (lastRecord.value?.UPC || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.versionNo == (lastRecord.value?.VersionNo || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.help == (lastRecord.value?.Help || '') &&
    form.value.documentNote == (lastRecord.value?.DocumentNote || '') &&
    form.value.isSummary == (lastRecord.value?.IsSummary ?? false) &&
    form.value.isStocked == (lastRecord.value?.IsStocked ?? true) &&
    form.value.isPurchased == (lastRecord.value?.IsPurchased ?? true) &&
    form.value.isSold == (lastRecord.value?.IsSold ?? true) &&
    form.value.volume == (lastRecord.value?.Volume || 0) &&
    form.value.weight == (lastRecord.value?.Weight || 0) &&
    form.value.width == (lastRecord.value?.width || lastRecord.value?.Width || 0) &&
    form.value.length == (lastRecord.value?.length || lastRecord.value?.Length || 0) &&
    form.value.height == (lastRecord.value?.height || lastRecord.value?.Height || 0) &&
    form.value.discontinued == (lastRecord.value?.Discontinued ?? false) &&
    form.value.isBOM == (lastRecord.value?.IsBOM ?? false) &&
    form.value.isInvoicePrintDetails == (lastRecord.value?.IsInvoicePrintDetails ?? false) &&
    form.value.isPickListPrintDetails == (lastRecord.value?.IsPickListPrintDetails ?? false) &&
    form.value.isVerified == (lastRecord.value?.IsVerified ?? false) &&
    form.value.guaranteeDaysMin == (lastRecord.value?.GuaranteeDaysMin || 0) &&
    form.value.isWebStoreFeatured == (lastRecord.value?.IsWebStoreFeatured ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.isDropShip == (lastRecord.value?.IsDropShip ?? false) &&
    form.value.isExcludeAutoDelivery == (lastRecord.value?.IsExcludeAutoDelivery ?? false) &&
    form.value.unitsPerPack == (lastRecord.value?.UnitsPerPack || 0) &&
    form.value.lowLevel == (lastRecord.value?.LowLevel || 0) &&
    form.value.isKanban == (lastRecord.value?.IsKanban ?? false) &&
    form.value.isManufactured == (lastRecord.value?.IsManufactured ?? false) &&
    form.value.isPhantom == (lastRecord.value?.IsPhantom ?? false) &&
    form.value.isOwnBox == (lastRecord.value?.IsOwnBox ?? false) &&
    form.value.isAutoProduce == (lastRecord.value?.IsAutoProduce ?? false) &&
    form.value.shelfWidth == (lastRecord.value?.ShelfWidth || 0) &&
    form.value.shelfHeight == (lastRecord.value?.ShelfHeight || 0) &&
    form.value.shelfDepth == (lastRecord.value?.ShelfDepth || 0) &&
    form.value.unitsPerPallet == (lastRecord.value?.UnitsPerPallet || 0) &&
    form.value.classification == (lastRecord.value?.Classification || '') &&
    form.value.customsTariffNumber == (lastRecord.value?.CustomsTariffNumber || 0) &&
    form.value.group1 == (lastRecord.value?.Group1 || '') &&
    form.value.group2 == (lastRecord.value?.Group2 || '') &&
    form.value.asin == (lastRecord.value?.asin || '') &&
    form.value.mpn == (lastRecord.value?.mpn || '') &&
    form.value.uomId == (lastRecord.value?.C_UOM_ID?.id || '') &&
    form.value.productCategoryId == (lastRecord.value?.M_Product_Category_ID?.id || '') &&
    form.value.taxCategoryId == (lastRecord.value?.C_TaxCategory_ID?.id || '') &&
    form.value.productTypeId == (lastRecord.value?.ProductType?.id || 'I') &&
    form.value.attributeSetId == (lastRecord.value?.M_AttributeSet_ID?.id || '') &&
    form.value.attributeSetInstanceId == (lastRecord.value?.M_AttributeSetInstance_ID?.id || '') &&
    form.value.revenueRecognitionId == (lastRecord.value?.C_RevenueRecognition_ID?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.mailTextId == (lastRecord.value?.R_MailText_ID?.id || '') &&
    form.value.labelPrinterId == (lastRecord.value?.labelprinter?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/materials/products/${route.params.id}/duplicate`)
}

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    let newUrl = '/materials/products'
    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
  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/materials/products/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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,
      width: form.value.width,
      length: form.value.length, 
      height: form.value.height,
      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') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 7500,
        position: 'bottom-right'
      })
      retrieve()
    } 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 showAttachment = ref(false)

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

const tab = ref(route.query?.tab || 'basic')
const tabs = computed(() => {
  if (defaultSideBarMenu.value === 'c') {
    // Limited tabs for customer menu
    return [
      { value: 'basic', text: 'Basic'},
    ]
  }

  // Full tabs for other menus
  return [
    { 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>Edit 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 === '' || 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.name === '' || form.productTypeId === '' || form.productCategoryId === '' || form.uomId === '' || form.taxCategoryId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.alert.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>
        </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>
        <MaterialsProductForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div v-if="defaultSideBarMenu !== 'c'">
        <MaterialsProductDetailRecord action="edit" :info="form" tab="product_price" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="M_Product" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>