<script setup>
import { toast } from 'bulma-toast'

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

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

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  name: '',
  description: '',
  isActive: true,
  value: '',
  isDefault: false,
  plannedMargin: 0.0,
  isSelfService: false,
  assetGroup: '',
  assetGroupId: '',
  printColor: '',
  printColorId: '',
  mMPolicy: '',
  mMPolicyId: '',
  parentProductCategory: '',
  parentProductCategoryId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/materials/product-categories/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    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 || '',
      name: res?.Name || '',
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      value: res?.Value || '',
      isDefault: res?.IsDefault ?? false,
      plannedMargin: res?.PlannedMargin || 0.0,
      isSelfService: res?.IsSelfService ?? false,
      assetGroup: res?.A_Asset_Group_ID?.identifier || '',
      assetGroupId: res?.A_Asset_Group_ID?.id || '',
      printColor: res?.AD_PrintColor_ID?.identifier || '',
      printColorId: res?.AD_PrintColor_ID?.id || '',
      mMPolicy: res?.MMPolicy?.identifier || '',
      mMPolicyId: res?.MMPolicy?.id || '',
      parentProductCategory: res?.M_Product_Category_Parent_ID?.identifier || '',
      parentProductCategoryId: res?.M_Product_Category_Parent_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.isDefault == (lastRecord.value?.IsDefault ?? false) &&
    form.value.plannedMargin == (lastRecord.value?.PlannedMargin || 0.0) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.assetGroupId == (lastRecord.value?.A_Asset_Group_ID?.id || '') &&
    form.value.printColorId == (lastRecord.value?.AD_PrintColor_ID?.id || '') &&
    form.value.mMPolicyId == (lastRecord.value?.MMPolicy?.id || '') &&
    form.value.parentProductCategoryId == (lastRecord.value?.M_Product_Category_Parent_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/materials/product-categories/${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 {
    router.push('/materials/product-categories')
  }
}

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/product-categories/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      organizationId: form.value.organizationId,
      name: form.value.name,
      description: form.value.description,
      isActive: form.value.isActive,
      sendCategoryLetter: form.value.sendCategoryLetter,
      isDefault: form.value.isDefault,
      createLevelsSequentially: form.value.createLevelsSequentially
    }
  })

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

    if(saveType === 'preview') {
      router.push('/materials/product-categories/'+res.id+'/view')
    } else if(saveType === 'changes') {
      location.reload()
    } else if(saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      // location.reload()
    } 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
    })
  }
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/product-categories', text: 'Product Categories'},
  { link: '#', text: 'Add Product Category', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Product Category</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.mMPolicyId === '' || form.plannedMargin === '' || 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.mMPolicyId === '' || form.plannedMargin === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.mMPolicyId === '' || form.plannedMargin === '' || 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="editwrapper">
        <MaterialsProductCategoryForm v-model="form" @save="save"/>
      </div>
      <div>
        <MaterialsProductCategoryDetailRecord action="edit" :info="form" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="M_Product_Category" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>