<script setup>
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 || '',
  isActive: props.modelValue.isActive ?? true,
  name: props.modelValue.name || '',
  description: props.modelValue.description || '',
  isDocNoControlled: props.modelValue.isDocNoControlled ?? false,
  printName: props.modelValue.printName || '',
  hasCharges: props.modelValue.hasCharges ?? false,
  hasProforma: props.modelValue.hasProforma ?? false,
  isDefault: props.modelValue.isDefault ?? false,
  documentCopies: props.modelValue.documentCopies || 1,
  isSOTrx: props.modelValue.isSOTrx ?? false,
  isDefaultCounterDoc: props.modelValue.isDefaultCounterDoc ?? false,
  isPickQAConfirm: props.modelValue.isPickQAConfirm ?? false,
  isShipConfirm: props.modelValue.isShipConfirm ?? false,
  isInTransit: props.modelValue.isInTransit ?? false,
  isSplitWhenDifference: props.modelValue.isSplitWhenDifference ?? false,
  isCreateCounter: props.modelValue.isCreateCounter ?? false,
  isIndexed: props.modelValue.isIndexed ?? false,
  isOverwriteSeqOnComplete: props.modelValue.isOverwriteSeqOnComplete ?? false,
  isOverwriteDateOnComplete: props.modelValue.isOverwriteDateOnComplete ?? false,
  isPrepareSplitDocument: props.modelValue.isPrepareSplitDocument ?? false,
  isChargeOrProductMandatory: props.modelValue.isChargeOrProductMandatory ?? false,
  isNoPriceListCheck: props.modelValue.isNoPriceListCheck ?? false,
  documentNote: props.modelValue.documentNote || '',
  printFormat: props.modelValue.printFormat || '',
  printFormatId: props.modelValue.printFormatId || '',
  definiteSequence: props.modelValue.definiteSequence || '',
  definiteSequenceId: props.modelValue.definiteSequenceId|| '',
  docNoSequence: props.modelValue.docNoSequence || '',
  docNoSequenceId: props.modelValue.docNoSequenceId || '',
  category: props.modelValue.category || '',
  categoryId: props.modelValue.categoryId || '',
  docBaseType: props.modelValue.docBaseType || '',
  docBaseTypeId: props.modelValue.docBaseTypeId || '',
  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 save = () => {
  //form.value.alert.processing = true
  emit('update:modelValue', form.value)
  emit('save', form.value)
  /*if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, '', saveType)
  }*/
}
</script>

<template>
  <div @mouseleave="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" :readonly="form.client === 'System'" />
            </div>
            <div class="column is-half">
              <label class="label d-block">Document Base Type *</label>
              <select v-model="form.docBaseTypeId" class="select">
                <option value="APC">AP Credit Memo</option>
                <option value="API">AP Invoice</option>
                <option value="APP">AP Payment</option>
                <option value="ARC">AR Credit Memo</option>
                <option value="ARI">AR Invoice</option>
                <option value="ARF">AR Pro Forma Invoice</option>
                <option value="ARR">AR Receipt</option>
                <option value="CMB">Bank Statement</option>
                <option value="CMC">Cash Journal</option>
                <option value="DOO">Distribution Order</option>
                <option value="FAA">Fixed Assets Addition</option>
                <option value="FDP">Fixed Assets Depreciation</option>
                <option value="FAD">Fixed Assets Disposal</option>
                <option value="GLD">GL Document</option>
                <option value="GLJ">GL Journal</option>
                <option value="MOF">Maintenance Order</option>
                <option value="MCC">Manufacturing Cost Collector</option>
                <option value="MOP">Manufacturing Order</option>
                <option value="MXI">Match Invoice</option>
                <option value="MXP">Match PO</option>
                <option value="MMS">Material Delivery</option>
                <option value="MMM">Material Movement</option>
                <option value="MMI">Material Physical Inventory</option>
                <option value="MMP">Material Production</option>
                <option value="MMR">Material Receipt</option>
                <option value="CMA">Payment Allocation</option>
                <option value="HRP">Payroll</option>
                <option value="PJI">Project Issue</option>
                <option value="POO">Purchase Order</option>
                <option value="POR">Purchase Requisition</option>
                <option value="MQO">Quality Order</option>
                <option value="SOO">Sales Order</option>
              </select>
              <!--<input v-if="form.client === 'System'" type="text" :value="form.docBaseType" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.docBaseTypeId" :options="getOptions?.['doc_base_types']?.records || [{id: form.docBaseTypeId, Name: form.docBaseType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_docbasegroup', 'doc_base_types')" :loading="loading?.['doc_base_types'] ?? true" />
              </ClientOnly>-->
            </div>
          </div>
        
          <label class="label d-block mt-2">Description</label>
          <textarea v-model="form.description" class="input" :disabled="form.client === 'System'"></textarea>
          
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">GL Category *</label>
              <input v-if="form.client === 'System'" type="text" :value="form.category" class="input" readonly />
              <ClientOnly v-else>
                <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 class="column is-half">
              <label class="label d-block mt-2">Print Text *</label>
              <input type="text" v-model="form.printName" class="input" :readonly="form.client === 'System'" />
            </div>
          </div>
        
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Document Sequence</label>
              <input v-if="form.client === 'System'" type="text" :value="form.docNoSequence" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.docNoSequenceId" :options="getOptions?.['doc_no_sequences']?.records || [{id: form.docNoSequenceId, Name: form.docNoSequence}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_sequence', 'doc_no_sequences')" :loading="loading?.['doc_no_sequences'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half" v-if="form.isOverwriteSeqOnComplete">
              <label class="label d-block mt-2">Definite Sequence</label>
              <input v-if="form.client === 'System'" type="text" :value="form.definiteSequence" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.definiteSequenceId" :options="getOptions?.['definite_sequences']?.records || [{id: form.definiteSequenceId, Name: form.definiteSequence}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_sequence', 'definite_sequences')" :loading="loading?.['definite_sequences'] ?? true" />
              </ClientOnly>
            </div>
          </div>
        
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Print Format *</label>
              <input v-if="form.client === 'System'" type="text" :value="form.printFormat" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.printFormatId" :options="getOptions?.['print_formats']?.records || [{id: form.printFormatId, Name: form.printFormat}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_printformat', 'print_formats')" :loading="loading?.['print_formats'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Document Copies *</label>
              <input type="text" v-model="form.documentCopies" class="input" :readonly="form.client === 'System'" />
            </div>
          </div>
        
          <label class="label d-block mt-2">Document Note</label>
          <textarea v-model="form.documentNote" class="input" :disabled="form.client === 'System'"></textarea>
        </div>

        <div class="column is-one-third">
          <label class="label d-block">Organization *</label>
          <input v-if="form.client === 'System'" type="text" :value="form.organization" class="input" readonly />
          <SelectBox v-else v-model="form.organizationId" :options="organizations" prop="name" dataprop="id" datatype="string" :size="5" />

          <label class="label d-block mt-2">Tenant *</label>
          <input type="text" :value="form.client || 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" :disabled="form.client === 'System'">
              <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" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isDefault">Default</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isSOTrx" class="checkInput" id="isSOTrx" :checked="form.isSOTrx" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isSOTrx">Sales Transaction</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDocNoControlled" class="checkInput" id="isDocNoControlled" :checked="form.isDocNoControlled" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isDocNoControlled">Document is Number Controlled</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isOverwriteSeqOnComplete" class="checkInput" id="isOverwriteSeqOnComplete" :checked="form.isOverwriteSeqOnComplete" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isOverwriteSeqOnComplete">Overwrite Sequence on Complete</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isOverwriteDateOnComplete" class="checkInput" id="isOverwriteDateOnComplete" :checked="form.isOverwriteDateOnComplete" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isOverwriteDateOnComplete">Overwrite Date on Complete</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isCreateCounter" class="checkInput" id="isCreateCounter" :checked="form.isCreateCounter" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isCreateCounter">Create Counter Document</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isChargeOrProductMandatory" class="checkInput" id="isChargeOrProductMandatory" :checked="form.isChargeOrProductMandatory" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isChargeOrProductMandatory">Mandatory Charge or Product</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDefaultCounterDoc" class="checkInput" id="isDefaultCounterDoc" :checked="form.isDefaultCounterDoc" :disabled="form.client === 'System'">
              <label class="checkLabel" for="isDefaultCounterDoc">Default Counter Document</label>
            </div>
          </div>
        </div>
      </div>

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