<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 form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  name: '',
  description: '',
  isActive: true,
  validFrom: date.now('date'),
  isQuantityBased: false,
  isBPartnerFlatDiscount: false,
  flatDiscount: 0,
  cumulativeLevel: 'Line',
  cumulativeLevelId: 'L',
  discountType: 'Breaks',
  discountTypeId: 'B',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/materials/discount-schemas/'+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 || '',
      name: res?.Name || '',
      description: res?.Description || '',
      isActive: true,
      validFrom: date.now('date'),
      isQuantityBased: res?.IsQuantityBased ?? false,
      isBPartnerFlatDiscount: res?.IsBPartnerFlatDiscount ?? false,
      flatDiscount: res?.FlatDiscount || 0,
      cumulativeLevel: res?.CumulativeLevel?.identifier || 'Line',
      cumulativeLevelId: res?.CumulativeLevel?.id || 'L',
      discountType: res?.DiscountType?.identifier || 'Breaks',
      discountTypeId: res?.DiscountType?.id || 'B',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    
    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  if(form.value.name !== '' && form.value.cumulativeLevelId !== '' && form.value.discountTypeId !== '') {
    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/discount-schemas')
  }
}

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

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

  const res = await $fetch('/api/materials/discount-schemas/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      name: form.value.name,
      description: form.value.description,
      isActive: form.value.isActive,
      validFrom: form.value.validFrom,
      isQuantityBased: form.value.isQuantityBased,
      isBPartnerFlatDiscount: form.value.isBPartnerFlatDiscount,
      flatDiscount: form.value.flatDiscount,
      cumulativeLevelId: form.value.cumulativeLevelId,
      discountTypeId: form.value.discountTypeId,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/materials/discount-schemas/' + res.id + '/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/materials/discount-schemas/'+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/discount-schemas', text: 'Discount Schemas'},
  { link: '#', text: 'Add Discount Schema', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Discount Schema</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.cumulativeLevelId === '' || form.discountTypeId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</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>
      <div class="banner">
        <div>
          <MaterialsDiscountSchemaForm v-model="form" @save="save" />
        </div>
        <div v-if="form.discountTypeId === 'B'" class="opacity-0.6 pointerEvents-none">
          <MaterialsDiscountSchemaDetailRecord action="create" :info="form" />
        </div>
      </div>
    </div>
  </NuxtLayout>
</template>