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

const router = useRouter()

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  warehouse: '',
  warehouseId: '',
  name: '',
  value: '',
  description: '',
  help: '',
  isActive: true,
  marketplace: '',
  marketplaceId: '',
  marketplaceUrl: '',
  marketplaceKey: '',
  marketplaceSecret: '',
  marketplaceToken: '',
  startingOrderId: '',
  startingOrderDate: date.now('date'),
  priceList: '',
  priceListId: '',
  priceListVersion: '',
  priceListVersionId: '',
  syncProductToIdempiere: false,
  syncProductFromIdempiere: false,
  syncOrderToIdempiere: false,
  syncOrderFromIdempiere: false,
  syncShipmentToIdempiere: false,
  syncShipmentFromIdempiere: false,
  isExcludetrackingmail: false,
  isCustomTrackingMail: false,
  isSentCustomTrackingMail: false,
  isBoMConvert: false,
  isTaxIncluded: true,
  plentyOneOrderFilterCode: 5.1,
  plentyOneOrderImportCode: 8,
  plentyOneOrderCommissionCode: 6,
  plentyOneWarehouseId: 102,
  DHLURL: '',
  DHLKey: '',
  DHLSecret: '',
  DHLUser: '',
  DHLPass: '',
  DHLUseCustom: false,
  DHLBillingNumberDE: '',
  DHLBillingNumberINT: '',
  shipperCustom1: '',
  shipperCustom1Id: '',
  shipperCustom2: '',
  shipperCustom2Id: '',
  externalShippingProfile1: '',
  externalShippingProfile2: '',
  removeArticleString: '',
  jtlMerchantId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const back = () => {
  router.push('/settings/order-sources')
}

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

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

  const res = await $fetch('/api/settings/order-sources/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      warehouseId: form.value.warehouseId,
      name: form.value.name,
      value: form.value.value,
      description: form.value.description,
      help: form.value.help,
      isActive: form.value.isActive,
      marketplaceId: form.value.marketplaceId,
      marketplaceUrl: form.value.marketplaceUrl,
      marketplaceKey: form.value.marketplaceKey,
      marketplaceSecret: form.value.marketplaceSecret,
      marketplaceToken: form.value.marketplaceToken,
      startingOrderId: form.value.startingOrderId,
      startingOrderDate: form.value.startingOrderDate,
      syncProductToIdempiere: form.value.syncProductToIdempiere,
      syncProductFromIdempiere: form.value.syncProductFromIdempiere,
      syncOrderToIdempiere: form.value.syncOrderToIdempiere,
      syncOrderFromIdempiere: form.value.syncOrderFromIdempiere,
      syncShipmentToIdempiere: form.value.syncShipmentToIdempiere,
      syncShipmentFromIdempiere: form.value.syncShipmentFromIdempiere,
      priceListId: form.value.priceListId,
      priceListVersionId: form.value.priceListVersionId,
      isExcludetrackingmail: form.value.isExcludetrackingmail,
      isCustomTrackingMail: form.value.isCustomTrackingMail,
      isSentCustomTrackingMail: form.value.isSentCustomTrackingMail,
      isBoMConvert: form.value.isBoMConvert,
      isTaxIncluded: form.value.isTaxIncluded,
      plentyOneOrderFilterCode: form.value.plentyOneOrderFilterCode,
      plentyOneOrderImportCode: form.value.plentyOneOrderImportCode,
      plentyOneOrderCommissionCode: form.value.plentyOneOrderCommissionCode,
      plentyOneWarehouseId: form.value.plentyOneWarehouseId,
      DHLURL: form.value.DHLURL,
      DHLKey: form.value.DHLKey,
      DHLSecret: form.value.DHLSecret,
      DHLUser: form.value.DHLUser,
      DHLPass: form.value.DHLPass,
      DHLUseCustom: form.value.DHLUseCustom,
      DHLBillingNumberDE: form.value.DHLBillingNumberDE,
      DHLBillingNumberINT: form.value.DHLBillingNumberINT,
      shipperCustom1Id: form.value.shipperCustom1Id,
      shipperCustom2Id: form.value.shipperCustom2Id,
      externalShippingProfile1: form.value.externalShippingProfile1,
      externalShippingProfile2: form.value.externalShippingProfile2,
      removeArticleString: form.value.removeArticleString,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/settings/order-sources/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/settings/order-sources/'+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
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '/settings/order-sources', text: 'Order Sources'},
  { link: '#', text: 'Add Order Source', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Order Source</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.marketplaceId === '' || form.marketplaceUrl === '' || !((form.marketplaceKey !== '' && form.marketplaceSecret !== '') || form.marketplaceToken !== '') || 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>
          <SettingsOrderSourceForm v-model="form" @save="save"/>
        </div>
      </div>

    </div>
  </NuxtLayout>
</template>