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

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 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) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const priorityBases = ref([
  { value: 'H', text: 'Higher' },
  { value: 'L', text: 'Lower' },
  { value: 'S', text: 'Same' }
])

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 || '',
  isActive: props.modelValue.isActive ?? true,
  isDefault: props.modelValue.isDefault ?? false,
  isConfidentialInfo: props.modelValue.isConfidentialInfo ?? false,
  creditWatchPercent: props.modelValue.creditWatchPercent || 0,
  priceMatchTolerance: props.modelValue.priceMatchTolerance || 0,
  printColor: props.modelValue.printColor || '',
  printColorId: props.modelValue.printColorId || '',
  priorityBase: props.modelValue.priorityBase || 'Lower',
  priorityBaseId: props.modelValue.priorityBaseId || 'L',
  priceList: props.modelValue.priceList || '',
  priceListId: props.modelValue.priceListId || '',
  poPriceList: props.modelValue.poPriceList || '',
  poPriceListId: props.modelValue.poPriceListId || '',
  discountSchema: props.modelValue.discountSchema || '',
  discountSchemaId: props.modelValue.discountSchemaId || '',
  poDiscountSchema: props.modelValue.poDiscountSchema || '',
  poDiscountSchemaId: props.modelValue.poDiscountSchemaId || '',
  dunning: props.modelValue.dunning || '',
  dunningId: props.modelValue.dunningId || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? 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">
              <label class="label d-block">Name *</label>
              <input type="text" v-model="form.name" class="input" @keyup="save" />

            </div>
            <div class="column is-half">
              <label class="label d-block">Search Key</label>
              <input type="text" v-model="form.value" class="input" @keyup="save" />

            </div>
          </div>

          <label class="label d-block mt-2">Description</label>
          <textarea v-model="form.description" class="input" @keyup="save"></textarea>
          
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Price List</label>
              <ClientOnly>
                <SelectBox v-model="form.priceListId" :options="getOptions?.['price_lists']?.records?.filter(i => i.IsSOPriceList === true && i.IsActive) || [{id: form.priceListId, Name: form.priceList}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/price-lists', 'price_lists')" @change="save" :loading="loading?.['price_lists'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">Discount Schema</label>
              <ClientOnly>
                <SelectBox v-model="form.discountSchemaId" :options="getOptions?.['discount-schemas']?.records?.filter(i => i.DiscountType.id !== 'P' && i.IsActive) || [{id: form.discountSchemaId, Name: form.discountSchema}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/discount-schemas', 'discount-schemas')" @change="save" :loading="loading?.['discount-schemas'] ?? true" />
              </ClientOnly>

              <label class="label d-block mt-2">Print Color</label>
              <ClientOnly>
                <SelectBox v-model="form.printColorId" :options="getOptions?.['print-colors']?.records?.filter(i => i.IsActive) || [{id: form.printColorId, Name: form.printColor}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('admin/print-colors', 'print-colors')" @change="save" :loading="loading?.['print-colors'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">PO Price List</label>
              <ClientOnly>
                <SelectBox v-model="form.poPriceListId" :options="getOptions?.['po_price_lists']?.records?.filter(i => i.IsSOPriceList === false && i.IsActive) || [{id: form.poPriceListId, Name: form.poPriceList}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/price-lists', 'po_price_lists')" @change="save" :loading="loading?.['po_price_lists'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">PO Discount Schema</label>
              <ClientOnly>
                <SelectBox v-model="form.poDiscountSchemaId" :options="getOptions?.['po_discount-schemas']?.records?.filter(i => i.DiscountType.id !== 'P' && i.IsActive) || [{id: form.poDiscountSchemaId, Name: form.poDiscountSchema}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('materials/discount-schemas', 'po_discount-schemas')" @change="save" :loading="loading?.['po_discount-schemas'] ?? true" />
              </ClientOnly>

              <label class="label d-block mt-2">Dunning</label>
              <ClientOnly>
                <SelectBox v-model="form.dunningId" :options="getOptions?.['dunnings']?.records?.filter(i => i.IsActive) || [{id: form.dunningId, Name: form.dunning}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/dunnings', 'dunnings')" @change="save" :loading="loading?.['dunnings'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <label class="label d-block mt-2">Credit Watch %</label>
          <input type="text" v-model="form.creditWatchPercent" class="input" @keyup="save" />

          <label class="label d-block mt-2">Price Match Tolerance</label>
          <input type="text" v-model="form.priceMatchTolerance" class="input" @keyup="save" />
        </div>
        <div class="column is-one-third">
          <label class="label d-block">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" />

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

          <label class="label d-block mt-2">Priority Base</label>
          <SelectBox v-model="form.priorityBaseId" :options="priorityBases" prop="text" dataprop="value" datatype="string" @change="save" :size="5" />

          <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.isConfidentialInfo" class="checkInput" id="isConfidentialInfo" :checked="form.isConfidentialInfo" @change="save">
              <label class="checkLabel" for="isConfidentialInfo">Confidential Information</label>
            </div>
          </div>
        </div>
      </div>

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