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

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

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 retrieve = async () => {
  const res = await $fetch('/api/settings/order-sources/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      name: res?.Name || '',
      value: res?.Value || '',
      description: res?.Description || '',
      help: res?.Help || '',
      isActive: res?.IsActive ?? true,
      marketplace: res?.Marketplace?.identifier || '',
      marketplaceId: res?.Marketplace?.id || '',
      marketplaceUrl: res?.marketplace_url || '',
      marketplaceKey: res?.marketplace_key || '',
      marketplaceSecret: res?.marketplace_secret || '',
      marketplaceToken: res?.marketplace_token || '',
      startingOrderId: res?.starting_order_id || '',
      startingOrderDate: res?.starting_order_date || date.now('date'),
      priceList: res?.M_PriceList_ID?.identifier || '',
      priceListId: res?.M_PriceList_ID?.id || '',
      priceListVersion: res?.M_PriceList_Version_ID?.identifier || '',
      priceListVersionId: res?.M_PriceList_Version_ID?.id || '',
      syncProductToIdempiere: res?.syncProductToIdempiere ?? false,
      syncProductFromIdempiere: res?.syncProductFromIdempiere ?? false,
      syncOrderToIdempiere: res?.syncOrderToIdempiere ?? false,
      syncOrderFromIdempiere: res?.syncOrderFromIdempiere ?? false,
      syncShipmentToIdempiere: res?.syncShipmentToIdempiere ?? false,
      syncShipmentFromIdempiere: res?.syncShipmentFromIdempiere ?? false,
      isExcludetrackingmail: res?.isExcludetrackingmail ?? res?.IsExcludetrackingmail ?? false,
      isCustomTrackingMail: res?.IsCustomTrackingMail ?? false,
      isSentCustomTrackingMail: res?.isSentCustomTrackingMail ?? false,
      isBoMConvert: res?.isBomConvert ?? false,
      isTaxIncluded: res?.IsTaxIncluded ?? true,
      plentyOneOrderFilterCode: res?.plentyone_orderfilter_code ?? 5.1,
      plentyOneOrderImportCode: res?.plentyone_orderimport_code ?? 8,
      plentyOneOrderCommissionCode: res?.plentyone_ordercommission_code ?? 6,
      plentyOneWarehouseId: res?.PlentyOne_Warehouse_ID ?? 102,
      DHLURL: res?.DHLURL ?? '',
      DHLKey: res?.DHLKEY ?? '',
      DHLSecret: res?.DHLSECRET ?? '',
      DHLUser: res?.DHLUSER ?? '',
      DHLPass: res?.DHLPASS ?? '',
      DHLUseCustom: res?.DHL_USE_CUSTOM ?? false,
      DHLBillingNumberDE: res?.dhl_billing_number_de ?? '',
      DHLBillingNumberINT: res?.dhl_billing_number_int ?? '',
      shipperCustom1: res?.M_Shipper_Custom1_ID?.identifier || '',
      shipperCustom1Id: res?.M_Shipper_Custom1_ID?.id || '',
      shipperCustom2: res?.M_Shipper_Custom2_ID?.identifier || '',
      shipperCustom2Id: res?.M_Shipper_Custom2_ID?.id || '',
      externalShippingProfile1: res?.External_Shipping_Profile_1 ?? '',
      externalShippingProfile2: res?.External_Shipping_Profile_2 ?? '',
      removeArticleString: res?.remove_article_string ?? '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
  }
}
onMounted(retrieve)

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/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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') {
      form.value.alert.processing = false
      location.reload()
    } else if(saveType === 'onlysave') {
      form.value.alert.processing = false
      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
    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: 'Edit Order Source', active: true}
]))
</script>

<template>
  <Head>
    <Title>Edit 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>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" class="button" :class="(form.name === '' || form.marketplaceId === '' || form.marketplaceUrl === '' || !((form.marketplaceKey !== '' && form.marketplaceSecret !== '') || form.marketplaceToken !== '') || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.marketplaceId === '' || form.marketplaceUrl === '' || !((form.marketplaceKey !== '' && form.marketplaceSecret !== '') || form.marketplaceToken !== '') || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</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>
      <div class="banner">
        <div class="editwrapper">
          <SettingsOrderSourceForm v-model="form" @save="save"/>
        </div>
      </div>

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