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

const props = defineProps({
  modelValue: Object
})

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
})

const getDays = computed(() => {
  return date.days('2023-12-05')
})

const form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue?.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  name: props.modelValue.name || '',
  value: props.modelValue.value || '',
  description: props.modelValue.description || '',
  documentNote: props.modelValue.documentNote || '',
  afterDelivery: props.modelValue.afterDelivery ?? false,
  netDays: props.modelValue.netDays ?? 30,
  netDay: props.modelValue.netDay ?? 0,
  graceDays: props.modelValue.graceDays ?? 0,
  isActive: props.modelValue.isActive ?? false,
  isDefault: props.modelValue.isDefault ?? false,
  isValid: props.modelValue.isValid ?? false,
  isDueFixed: props.modelValue.isDueFixed ?? false,
  fixMonthCutoff: props.modelValue.fixMonthCutoff || 0,
  fixMonthDay: props.modelValue.fixMonthDay || 0,
  fixMonthOffset: props.modelValue.fixMonthOffset || 0,
  isNextBusinessDay: props.modelValue.isNextBusinessDay ?? false,
  discount: props.modelValue.discount || 0,
  discount2: props.modelValue.discount2 || 0,
  discountDays: props.modelValue.discountDays || 0,
  discountDays2: props.modelValue.discountDays2 || 0,
  paymentTermUsage: props.modelValue.paymentTermUsage || 'Both',
  paymentTermUsageId: props.modelValue.paymentTermUsageId || 'B',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false,
  }
})

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    /*if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }*/
    
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

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

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const save = debounce(() => {
  emit('update:modelValue', form.value)
  emit('save', form.value)
})
</script>

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

      <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">Name *</label>
                <input type="text" v-model="form.name" class="input" @keyup="save" />
              </div>
            </div>
            <div class="column is-half">
              <div class="legend">
                <label class="label">Search Key</label>
                <input type="text" v-model="form.value" class="input" @keyup="save" />
              </div>
            </div>
          </div>
      
          <div class="legend mt-2">
            <label class="label">Description</label>
            <textarea v-model="form.description" class="input" @keyup="save"></textarea>
          </div>

          <template v-if="form.isDueFixed">
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Fix Month Day</label>
                  <input type="text" v-model="form.fixMonthDay" class="input" @keyup="save" />
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Fix Month Cutoff</label>
                  <input type="text" v-model="form.fixMonthCutoff" class="input" @keyup="save" />
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend mt-2">
                  <label class="label">Fix Month Offset</label>
                  <input type="text" v-model="form.fixMonthOffset" class="input" @keyup="save" />
                </div>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend mt-2">
                  <label class="label">Net Days *</label>
                  <input type="text" v-model="form.netDays" @input="form.netDays = Number(form.netDays) >= 1 ? form.netDays : 30" class="input" @keyup="save" />
                </div>
              </div>
              <div class="column is-half">
                <div class="legend mt-2">
                  <label class="label">Net Day</label>
                  <select v-model="form.netDay" class="select" @change="save">
                    <option v-for="(dy, ind) in getDays" :key="dy.value" :value="Number(dy.value)" :selected="Number(dy.value) === Number(form.netDay)">{{ dy.text }}</option>
                  </select>
                </div>
              </div>
            </div>
          </template>

          <div class="columns is-desktop">
            <div class="column is-half">
              <div class="legend mt-2">
                <label class="label">Discount Days *</label>
                <input type="text" v-model="form.discountDays" @input="form.discountDays = Number(form.discountDays) >= 1 ? form.discountDays : 10" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Discount *</label>
                <input type="text" v-model="form.discount" @input="form.discount = Number(form.discount) >= 1 ? form.discount : 2" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Grace Days *</label>
                <input type="text" v-model="form.graceDays" @input="form.graceDays = Number(form.graceDays) >= 1 ? form.graceDays : 0" class="input" @keyup="save" />
              </div>
            </div>
            <div class="column is-half">
              <div class="legend mt-2">
                <label class="label">Discount Days 2 *</label>
                <input type="text" v-model="form.discountDays2" @input="form.discountDays2 = Number(form.discountDays2) >= 1 ? form.discountDays2 : 0" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Discount 2 *</label>
                <input type="text" v-model="form.discount2" @input="form.discount2 = Number(form.discount2) >= 1 ? form.discount2 : 0" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Payment Term Usage *</label>
                <select v-model="form.paymentTermUsageId" class="select" @change="save">
                  <option value="B">Both</option>
                  <option value="P">Purchases</option>
                  <option value="S">Sales</option>
                </select>
              </div>
            </div>
          </div>

          <div class="legend mt-2">
            <label class="label">Document Note</label>
            <textarea v-model="form.documentNote" class="input" @keyup="save"></textarea>
          </div>
        </div>
        <div class="column is-one-third">
          <div class="legend">
            <label class="label">Organization *</label>
            <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />
          </div>

          <div class="legend mt-2">
            <label class="label">Tenant *</label>
            <input type="text" :value="clientName" class="input" readonly />
          </div>

          <label class="label d-block mt-2">Status</label>
          <div class="d-flex flexDirection-column">
            <div class="check">
              <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" @change="save">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDefault" class="checkInput" id="isDefault" :checked="form.isDefault" @change="save">
              <label class="checkLabel" for="isDefault">Default</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isValid" class="checkInput" id="isValid" :checked="form.isValid" @change="save">
              <label class="checkLabel" for="isValid">Valid</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDueFixed" class="checkInput" id="isDueFixed" :checked="form.isDueFixed" @change="save">
              <label class="checkLabel" for="isDueFixed">Fixed Due Date</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isNextBusinessDay" class="checkInput" id="isNextBusinessDay" :checked="form.isNextBusinessDay" @change="save">
              <label class="checkLabel" for="isNextBusinessDay">Next Business Day</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.afterDelivery" class="checkInput" id="afterDelivery" :checked="form.afterDelivery" @change="save">
              <label class="checkLabel" for="afterDelivery">After Delivery</label>
            </div>
          </div>
        </div>
      </div>

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