<script setup>
import { date } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
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 || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  documentNo: props.modelValue.documentNo || '',
  isPrinted: props.modelValue.isPrinted ?? false,
  dateDoc: props.modelValue.dateDoc || date.now('date'),
  dateAcct: props.modelValue.dateAcct || date.now('date'),
  totalDr: props.modelValue.totalDr || 0,
  totalCr: props.modelValue.totalCr || 0,
  isApproved: props.modelValue.isApproved ?? false,
  currencyRate: props.modelValue.currencyRate || 1,
  controlAmt: props.modelValue.controlAmt || 0,
  processed: props.modelValue.processed ?? false,
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || '',
  docStatus: props.modelValue.docStatus || 'Draft',
  docStatusId: props.modelValue.docStatusId || 'DR',
  postingType: props.modelValue.postingType || '',
  postingTypeId: props.modelValue.postingTypeId || '',
  acctSchema: props.modelValue.acctSchema || '',
  acctSchemaId: props.modelValue.acctSchemaId || '',
  category: props.modelValue.category || '',
  categoryId: props.modelValue.categoryId || '',
  period: props.modelValue.period || '',
  periodId: props.modelValue.periodId || '',
  currency: props.modelValue.currency || '',
  currencyId: props.modelValue.currencyId || '',
  conversionType: props.modelValue.conversionType || '',
  conversionTypeId: props.modelValue.conversionTypeId || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || ''
  }
})

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 save = (saveType = '') => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, '', saveType)
  }
}
</script>

<template>
  <form @submit.prevent="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">Accounting Schema *</label>
              <ClientOnly>
                <SelectBox v-model="form.acctSchemaId" :options="getOptions?.['acct_schemas']?.records || [{id: form.acctSchemaId, Name: form.acctSchema}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_acctschema', 'acct_schemas')" :loading="loading?.['acct_schemas'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block">Document No</label>
              <input type="text" v-model="form.documentNo" class="input" />
            </div>
          </div>

          <label class="label d-block mt-2">Description *</label>
          <textarea v-model="form.description" class="input"></textarea>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Posting Type *</label>
              <select v-model="form.postingTypeId" class="select">
                <option value="A">Actual</option>
                <option value="B">Budget</option>
                <option value="E">Commitment</option>
                <option value="R">Reservation</option>
                <option value="S">Statistical</option>
              </select>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Journal Batch</label>
              <input type="text" class="input" readonly />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Document Type *</label>
              <ClientOnly>
                <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('models/c_doctype', 'doc_types')" :loading="loading?.['doc_types'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">GL Category *</label>
              <ClientOnly>
                <SelectBox v-model="form.categoryId" :options="getOptions?.['categories']?.records || [{id: form.categoryId, Name: form.category}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/gl_category', 'categories')" :loading="loading?.['categories'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Document Date *</label>
              <DatePicker v-model="form.dateDoc" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Account Date *</label>
              <DatePicker v-model="form.dateAcct" />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Period *</label>
              <ClientOnly>
                <SelectBox v-model="form.periodId" :options="getOptions?.['periods']?.records || [{id: form.periodId, Name: form.period}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_period', 'periods')" :loading="loading?.['periods'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Currency *</label>
              <ClientOnly>
                <SelectBox v-model="form.currencyId" :options="getOptions?.['currencies']?.records || [{id: form.currencyId, ISO_Code: form.currency}]" prop="ISO_Code" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_currency', 'currencies')" :loading="loading?.['currencies'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Document Status *</label>
              <select v-model="form.docStatusId" class="select" disabled>
                <option value="DR">Draft</option>
              </select>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Control Amount</label>
              <input type="text" v-model="form.controlAmt" class="input" />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Total Debit *</label>
              <input type="text" :value="form.totalDr" class="input" readonly />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Total Credit *</label>
              <input type="text" :value="form.totalCr" class="input" readonly />
            </div>
          </div>

        </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">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">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isApproved" class="checkInput" id="isApproved" :checked="form.isApproved">
              <label class="checkLabel" for="isApproved">Approved</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isPrinted" class="checkInput" id="isPrinted" :checked="form.isPrinted">
              <label class="checkLabel" for="isPrinted">Printed</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.processed" class="checkInput" id="processed" :checked="form.processed">
              <label class="checkLabel" for="processed">Processed</label>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="m-3">
      <div class="d-flex gap-10px">
        <button type="submit" class="button" :class="(form.docTypeId === '' || form.description === '' || form.postingTypeId === '' || form.acctSchemaId === '' || form.categoryId === '' || form.periodId === '' || form.currencyId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
        <button type="button" @click="save('preview')" class="button" :class="(form.docTypeId === '' || form.description === '' || form.postingTypeId === '' || form.acctSchemaId === '' || form.categoryId === '' || form.periodId === '' || form.currencyId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Preview</button>
        <button type="button" @click="save('changes')" class="button" :class="(form.docTypeId === '' || form.description === '' || form.postingTypeId === '' || form.acctSchemaId === '' || form.categoryId === '' || form.periodId === '' || form.currencyId === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save Changes</button>
      </div>
    </div>
  </form>
</template>