<script setup>
import { date } from 'alga-js'
import { DatePicker, DateTimePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'

const props = defineProps({
  modelValue: Object,
  tab: String
})

const emit = defineEmits(['update:modelValue', 'update:tab', 'save'])

const form = ref({
  id: props.modelValue.id || '',
  inOutId: props.modelValue.inOutId || '',
  name: props.modelValue?.name || '',
  companyName: props.modelValue?.companyName || '',
  email: props.modelValue?.email || '',
  telephone: props.modelValue?.telephone || '',
  address: props.modelValue?.address || '',
  houseNumber: props.modelValue?.houseNumber || '',
  address2: props.modelValue?.address2 || '',
  city: props.modelValue?.city || '',
  country: props.modelValue?.country || '',
  postalCode: props.modelValue?.postalCode || '',
  countryState: props.modelValue?.countryState || '',
  toServicePoint: props.modelValue?.toServicePoint || '',
  toPostNumber: props.modelValue?.toPostNumber || '',
  customsInvoiceNR: props.modelValue?.customsInvoiceNR || '',
  customsShipmentType: props.modelValue?.customsShipmentType || '',
  weight: props.modelValue?.weight || '',
  length: props.modelValue?.length || '',
  width: props.modelValue?.width || '',
  height: props.modelValue?.height || '',
  totalOrderValue: props.modelValue?.totalOrderValue || '',
  totalOrderValueCurrency: props.modelValue?.totalOrderValueCurrency || '',
  shippingMethodCheckoutName: props.modelValue?.shippingMethodCheckoutName || '',
  senderAddress: props.modelValue?.senderAddress || 1,
  quantity: props.modelValue?.quantity || 1,
  totalInsuredValue: props.modelValue?.totalInsuredValue || 0,
  isReturn: props.modelValue?.isReturn ?? false,
  requestLabel: props.modelValue?.requestLabel ?? false,
  applyShippingRules: props.modelValue?.applyShippingRules ?? false,
  requestLabelAsync: props.modelValue?.requestLabelAsync ?? false,
  shipment: props.modelValue?.shipment || '',
  shipmentId: props.modelValue?.shipmentId || 8,
  dateCreated: props.modelValue?.dateCreated || '',
  dateUpdated: props.modelValue?.dateUpdated || '',
  dateAnnounced: props.modelValue?.dateAnnounced || '',
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false,
  }
})

const loading = ref({})
const filtering = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const filterOptions = async (model, key, filter = '') => {
  if(filter) {
    await setOptions('filters/'+model+'/'+filter, key)
    filtering.value[key] = filter
  } else {
    if(!filtering.value?.[key] || filtering.value?.[key] === '') {
      await setOptions('models/'+model, key)
    }
  }
}

const loadShipment = async (val, opt) => {
  form.value.inOutId = opt?.id || ''
  form.value.name = opt?.C_BPartner_ID?.identifier || ''
  form.value.companyName = opt?.AD_Org_ID?.identifier || ''
  form.value.weight = opt?.Weight || ''
  form.value.length = opt?.Volume || ''
  
  let resl = {}
  if(opt?.C_BPartner_ID?.id) {
    resl = await $fetch('/api/partners/partner-locations/'+opt.C_BPartner_ID.id, {
      headers: useRequestHeaders(['cookie'])
    })
  }
  form.value.address = resl?.C_Location_ID?.Address1 || ''
  form.value.address2 = resl?.C_Location_ID?.Address2 || ''
  form.value.city = resl?.C_Location_ID?.City|| ''
  form.value.postalCode = resl?.C_Location_ID?.Postal|| ''
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
})

const save = () => {
  //form.value.alert.processing = true
  emit('update:modelValue', form.value)
  emit('save', form.value)
  /*if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id)
  } else {
    emit('save', form.value, '')
  }*/
}
</script>

<template>
  <div @mouseleave="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'basic'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend">
                  <label class="label">Shipment ID *</label>
                  <input v-if="form.inOutId !== ''" type="text" :value="form.inOutId" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.inOutId" :options="getOptions?.['shipments']?.records || [{id: form.inOutId, DocumentNo: form.inOutId}]" prop="DocumentNo" dataprop="id" datatype="string" :size="5" @click="setOptions('shipments/co', 'shipments')" @change="loadShipment" :loading="loading?.['shipments'] ?? true" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Invoice Number</label>
                  <input type="text" v-model="form.customsInvoiceNR" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Customs Shipment Type</label>
                  <select v-model="form.customsShipmentType" class="select">
                    <option :value="0">Gift</option>
                    <option :value="1">Documents</option>
                    <option :value="2">Commercial Goods</option>
                    <option :value="3">Commercial Sample</option>
                    <option :value="4">Returned Goods</option>
                  </select>
                </div>

                <div class="legend mt-2">
                  <label class="label">Method Checkout Name</label>
                  <input type="text" v-model="form.shippingMethodCheckoutName" class="input" />
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend">
                  <label class="label">Name *</label>
                  <input type="text" v-model="form.name" class="input" />
                </div>
                
                <div class="legend mt-2">
                  <label class="label">Company Name</label>
                  <input type="text" v-model="form.companyName" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Email</label>
                  <input type="text" v-model="form.email" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Telephone</label>
                  <input type="text" v-model="form.telephone" class="input" />
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend">
                  <label class="label">Quantity</label>
                  <input type="text" v-model="form.quantity" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Weight</label>
                  <input type="text" v-model="form.weight" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Length</label>
                  <input type="text" v-model="form.length" class="input" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Width</label>
                  <input type="text" v-model="form.width" class="input" />
                </div>
                
                <div class="legend mt-2">
                  <label class="label">Height</label>
                  <input type="text" v-model="form.height" class="input" />
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Total Order Value</label>
              <input type="text" v-model="form.totalOrderValue" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">Order Value Currency</label>
              <input type="text" v-model="form.totalOrderValueCurrency" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">Total Insured Value</label>
              <input type="text" v-model="form.totalInsuredValue" class="input" />
            </div>

            <label class="label d-block mt-2">Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isReturn" class="checkInput" id="isReturn" :checked="form.isReturn">
                <label class="checkLabel" for="isReturn">Is Return</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.requestLabel" class="checkInput" id="requestLabel" :checked="form.requestLabel">
                <label class="checkLabel" for="requestLabel">Request Label</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.applyShippingRules" class="checkInput" id="applyShippingRules" :checked="form.applyShippingRules">
                <label class="checkLabel" for="applyShippingRules">Apply Shipping Rules</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.requestLabelAsync" class="checkInput" id="requestLabelAsync" :checked="form.requestLabelAsync">
                <label class="checkLabel" for="requestLabelAsync">Request Label Async</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'address'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend">
              <label class="label">Address *</label>
              <input type="text" v-model="form.address" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">House Number *</label>
              <input type="text" v-model="form.houseNumber" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">Country State</label>
              <input type="text" v-model="form.countryState" class="input" />
            </div>
            
            <div class="legend mt-2">
              <label class="label">Postal Code *</label>
              <input type="text" v-model="form.postalCode" class="input" />
            </div>
            
            <div class="legend mt-2">
              <label class="label">To Service Point</label>
              <input type="text" v-model="form.toServicePoint" class="input" />
            </div>
          </div>
          <div class="column is-half">
            <div class="legend">
              <label class="label">Address 2</label>
              <input type="text" v-model="form.address2" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">City *</label>
              <input type="text" v-model="form.city" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">Country *</label>
              <input type="text" v-model="form.country" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">Sender Address</label>
              <input type="text" v-model="form.senderAddress" class="input" />
            </div>

            <div class="legend mt-2">
              <label class="label">To Post Number</label>
              <input type="text" v-model="form.toPostNumber" class="input" />
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'shipment'">
        <div class="columns is-desktop">
          <div class="column is-half">
            
          </div>
          <div class="column is-half">
            
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-half">
            
          </div>
          <div class="column is-half">
            
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Date Created</label>
                  <input type="text" :value="form.dateCreated" class="input" readonly />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Date Updated</label>
                  <input type="text" :value="form.dateUpdated" class="input" readonly />
                </div>
              </div>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Date Received</label>
              <input type="text" :value="form.dateAnnounced" class="input" readonly />
            </div>
          </div>
        </div>
      </template>

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