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

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

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouses = useCookie('logship_warehouses')
const warehouseId = useCookie('logship_warehouse_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 || '',
  documentNo: props.modelValue.documentNo || '',
  movementDate: props.modelValue.movementDate || date.now('date'),
  approvalAmt: props.modelValue.approvalAmt || 0,
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  isApproved: props.modelValue.isApproved ?? false,
  warehouse: props.modelValue.warehouse || '',
  warehouseId: props.modelValue.warehouseId || '',
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || '',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  docStatus: props.modelValue.docStatus || 'Draft',
  docStatusId: props.modelValue.docStatusId || 'DR',
  processed: props.modelValue.processed ?? false,
  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

    if(key === 'warehouses' && res?.records?.[0]) {
      form.value.warehouseId = String(res.records[0].id || '')
      form.value.warehouse = res.records[0].Name || ''
    }
  }
  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="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'inventory'">
        <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">Document No</label>
                  <input type="text" v-model="form.documentNo" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Document Type *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.docType" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.docTypeId" :options="getOptions?.['doc_types']?.records || [{id: form.docTypeId, Name: form.docType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('types/MMIPI', 'doc_types')" @change="save" :loading="loading?.['doc_types'] ?? true" />
                  </ClientOnly>
                </div>
              </div>
              <div class="column is-half">
                <div class="legend">
                  <label class="label">Movement Date *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.movementDate" class="input" readonly />
                  <DatePicker v-else v-model="form.movementDate" @handler="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Perpetual Inventory</label>
                  <input type="text" class="input" readonly />
                </div>
              </div>
            </div>

            <div class="legend mt-1">
              <label class="label">Warehouse *</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.warehouse" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-if="form.organizationId" v-model="form.warehouseId" :options="getOptions?.['warehouses']?.records || [{id: form.warehouseId, Name: form.warehouse}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${form.organizationId}`), 'warehouses')" @change="save" :loading="loading?.['warehouses'] ?? true" />
                <SelectBox v-else v-model="form.warehouseId" :options="warehouses" @change="(val, opt) => {form.warehouse = opt.name; save();}" prop="name" dataprop="id" datatype="string" :size="5" />
              </ClientOnly>
            </div>
            
            <div class="legend mt-2">
              <label class="label">Description</label>
              <textarea v-model="form.description" class="input" :disabled="form.docStatusId === 'CO'" @keyup="save"></textarea>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Organization *</label>
              <input v-if="form.docStatusId === 'CO'" 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; setOptions('filters/m_warehouse/'+string.urlEncode(`ad_org_id eq ${opt.id}`), 'warehouses'); save();}" :loading="loading?.['orgs'] ?? true" />
            </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="check">
              <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" :disabled="form.docStatusId === 'CO'" @change="save">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend">
              <label class="label">Project</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.project" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.projectId" :options="getOptions?.['projects']?.records || [{id: form.projectId, Name: form.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('projects', 'projects')" @change="save" :loading="loading?.['projects'] ?? true" />
              </ClientOnly>
            </div>
          </div>
          <div class="column is-half">
            <div class="legend">
              <label class="label">Campaign</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.campaign" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.campaignId" :options="getOptions?.['campaigns']?.records || [{id: form.campaignId, Name: form.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('marketings/campaigns', 'campaigns')" @change="save" :loading="loading?.['campaigns'] ?? true" />
              </ClientOnly>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="legend">
              <label class="label">Document Status *</label>
              <select v-model="form.docStatusId" class="select" disabled>
                <option value="CO">Completed</option>
                <option value="DR">Drafted</option>
                <option value="VO">Void</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">Approval Amount</label>
              <input type="text" :value="form.approvalAmt" class="input" readonly />
            </div>
          </div>
          <div class="column is-one-third">
            <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.isApproved" class="checkInput" id="isApproved" :checked="form.isApproved" disabled>
                <label class="checkLabel" for="isApproved">Approved</label>
              </div>
            </div>
          </div>
        </div>
      </template>

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