<script setup>
import { string } 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 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,
  isDefault: props.modelValue.isDefault ?? false,
  isSelfService: props.modelValue.isSelfService ?? false,
  dueDateTolerance: props.modelValue.dueDateTolerance || 7,
  isEMailWhenOverdue: props.modelValue.isEMailWhenOverdue ?? false,
  isEMailWhenDue: props.modelValue.isEMailWhenDue ?? false,
  isInvoiced: props.modelValue.isInvoiced ?? false,
  isAutoChangeRequest: props.modelValue.isAutoChangeRequest ?? false,
  isConfidentialInfo: props.modelValue.isConfidentialInfo ?? false,
  isIndexed: props.modelValue.isIndexed ?? false,
  autoDueDateDays: props.modelValue.autoDueDateDays || 0,
  headerColor: props.modelValue.headerColor || '',
  contentColor: props.modelValue.contentColor || '',
  confidentialType: props.modelValue.confidentialType || '',
  confidentialTypeId: props.modelValue.confidentialTypeId || '',
  statusCategory: props.modelValue.statusCategory || '',
  statusCategoryId: props.modelValue.statusCategoryId || '',
  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) {
    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)
    }
  }
}

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="legend">
            <label class="label">Name *</label>
            <input type="text" v-model="form.name" class="input" @keyup="save" />
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <div class="legend mt-2">
                <label class="label">Status Category *</label>
                <ClientOnly>
                  <SelectBox v-model="form.statusCategoryId" :options="getOptions?.['status_categories']?.records || [{id: form.statusCategoryId, Name: form.statusCategory}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="filterOptions('r_statuscategory', 'status_categories', string.urlEncode(`isActive eq true`))" @search="(val) => filterOptions('r_statuscategory', 'status_categories', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['status_categories'] ?? true" @change="save" />
                </ClientOnly>
              </div>

              <div class="legend mt-2">
                <label class="label">Due Date Tolerance *</label>
                <input type="text" v-model="form.dueDateTolerance" class="input" @keyup="save" />
              </div>

              <div class="legend mt-2">
                <label class="label">Header Color</label>
                <input type="text" v-model="form.headerColor" class="input" @keyup="save" />
              </div>
            </div>
            <div class="column is-half">
              <div class="legend mt-2">
                <label class="label">Confidentiality *</label>
                <select v-model="form.confidentialTypeId" class="select" @change="save">
                  <option value="I">Internal</option>
                  <option value="C">Partner Confidential</option>
                  <option value="A">Public Information</option>
                </select>
              </div>

              <div class="legend mt-2">
                <label class="label">Auto Due Date Days</label>
                <input type="text" v-model="form.autoDueDateDays" class="input" @keyup="save" />
              </div>
              
              <div class="legend mt-2">
                <label class="label">Content Color</label>
                <input type="text" v-model="form.contentColor" 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>
        </div>
        <div class="column is-one-third">
          <div class="legend">
            <label class="label">Organization *</label>
            <input v-if="form.id !== ''" type="text" :value="form.organization" class="input" readonly />
            <SelectBox v-else 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="form.client || 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.isSelfService" class="checkInput" id="isSelfService" :checked="form.isSelfService" @change="save">
              <label class="checkLabel" for="isSelfService">Self Service</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isEMailWhenOverdue" class="checkInput" id="isEMailWhenOverdue" :checked="form.isEMailWhenOverdue" @change="save">
              <label class="checkLabel" for="isEMailWhenOverdue">Email When Overdue</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isEMailWhenDue" class="checkInput" id="isEMailWhenDue" :checked="form.isEMailWhenDue" @change="save">
              <label class="checkLabel" for="isEMailWhenDue">Email When Due</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isInvoiced" class="checkInput" id="isInvoiced" :checked="form.isInvoiced" @change="save">
              <label class="checkLabel" for="isInvoiced">Invoiced</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isAutoChangeRequest" class="checkInput" id="isAutoChangeRequest" :checked="form.isAutoChangeRequest" @change="save">
              <label class="checkLabel" for="isAutoChangeRequest">Auto Change Request</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 Info</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isIndexed" class="checkInput" id="isIndexed" :checked="form.isIndexed" @change="save">
              <label class="checkLabel" for="isIndexed">Indexed</label>
            </div>
          </div>
        </div>
      </div>

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