<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 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 || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  validFrom: props.modelValue.validFrom || date.now('date'),
  isQuantityBased: props.modelValue.isQuantityBased ?? false,
  isBPartnerFlatDiscount: props.modelValue.isBPartnerFlatDiscount ?? false,
  flatDiscount: props.modelValue.flatDiscount || 0,
  cumulativeLevel: props.modelValue.cumulativeLevel || 'Line',
  cumulativeLevelId: props.modelValue.cumulativeLevelId || 'L',
  discountType: props.modelValue.discountType || 'Breaks',
  discountTypeId: props.modelValue.discountTypeId || '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">Discount Type *</label>
                <select v-model="form.discountTypeId" class="select" @change="save">
                  <option value="B">Breaks</option>
                  <option value="F">Flat Percent</option>
                  <option value="P" disabled>Price List</option>
                </select>
              </div>
            </div>
          </div>

          <div v-if="form.discountTypeId === 'F'" class="columns is-desktop">
            <div class="column is-half">
              <div class="mt-2">
                <label class="label d-block mb-2">Business Partner</label>
                <div class="check">
                  <input type="checkbox" v-model="form.isBPartnerFlatDiscount" class="checkInput" id="isBPartnerFlatDiscount" :checked="form.isBPartnerFlatDiscount" @change="save">
                  <label class="checkLabel" for="isBPartnerFlatDiscount">Flat Discount</label>
                </div>
              </div>
            </div>
            <div class="column is-half">
              <div class="legend mt-2">
                <label class="label">Flat Discount %</label>
                <input type="text" v-model="form.flatDiscount" class="input" @keyup="save" />
              </div>
            </div>
          </div>

          <div v-if="form.discountTypeId === 'B'" class="columns is-desktop">
            <div class="column is-half">
              <div class="mt-2">
                <label class="label d-block mb-2">Quantity</label>
                <div class="check">
                  <input type="checkbox" v-model="form.isQuantityBased" class="checkInput" id="isQuantityBased" :checked="form.isQuantityBased" @change="save">
                  <label class="checkLabel" for="isQuantityBased">Quantity Based</label>
                </div>
              </div>
            </div>
            <div class="column is-half">
              <div class="legend mt-2">
                <label class="label">Accumulation Level</label>
                <select v-model="form.cumulativeLevelId" class="select" @change="save">
                  <option value="L">Line</option>
                </select>
              </div>
            </div>
          </div>

          <div class="legend mt-2">
            <label class="label">Description</label>
            <textarea v-model="form.description" 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="organizations" @change="save" prop="name" dataprop="id" datatype="string" :size="5" />
          </div>

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

          <label class="label d-block mt-2 mb-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>
        </div>
      </div>

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