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

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

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

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 tab = ref(props.modelValue || 'organization_info')
const entries = ref({
  organization_info: []
})
const tabs = ref([
  {value: 'organization_info', text: 'Organization Info'}
])

watch(() => props.modelValue, () => {
  tab.value = props.modelValue
})

const loadEntries = () => {
  if(props?.entries) {
    entries.value = props.entries
  }
}
onMounted(loadEntries)
watch(() => props.entries, loadEntries)

const addEntry = () => {
  if(tab.value === 'organization_info' && Number(entries.value?.organization_info?.length || 0) === 0) {
    entries.value.organization_info.push({
      id: '',
      isActive: true,
      DUNS: '?',
      taxID: '?',
      locationId: '',
      warehouseId: '',
      orgTypeId: '',
      supervisorId: '',
      parentOrgId: '',
      show: true
    })
  }

  //emit('handler', tab.value, entries.value)
}
onMounted(addEntry)
const mutateEntry = () => {
  emit('handler', tab.value, entries.value)
}
const destroyEntry = async (entry, index) => {
  entries.value[tab.value].splice(index, 1)

  if(entry.id) {
    await $fetch('/api/admin/organizations/'+entry.id+'/'+tab.value.replaceAll('_', '-'), {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
  emit('handler', tab.value, entries.value)
}

const openTab = async (val) => {
  if(tab.value !== val) {
    tab.value = val
    emit('update:modelValue', tab.value)
    emit('handler', tab.value, entries.value)
    sessionStorage.setItem('organization_detail_record', tab.value)
  }
}
onMounted(() => {
  const getSessionStorageTab = sessionStorage.getItem('organization_detail_record')
  if(getSessionStorageTab) {
    openTab(getSessionStorageTab)
  }
})

const tabElem = ref(null)
const slidePrev = () => {
  if(tabElem.value !== null) {
    if(false) { //rtl
      tabElem.value.scrollLeft = Number(tabElem.value.scrollLeft) - 120
    } else {
      if(Number(tabElem.value.scrollLeft) >= 120) {
        tabElem.value.scrollLeft = Number(tabElem.value.scrollLeft) - 120
      } else {
        tabElem.value.scrollLeft = 0
      }
    }
    sessionStorage.setItem('organization_tab_position', tabElem.value.scrollLeft)
  }
}
const slideNext = () => {
  if(tabElem.value !== null) {
    if(false) { //rtl
      if(Number(tabElem.value.scrollLeft) >= 0) {
        tabElem.value.scrollLeft = 0
      } else {
        tabElem.value.scrollLeft = Number(tabElem.value.scrollLeft) + 120
      }
    } else {
      tabElem.value.scrollLeft = Number(tabElem.value.scrollLeft) + 120
    }
    sessionStorage.setItem('organization_tab_position', tabElem.value.scrollLeft)
  }
}
onMounted(() => {
  const getTabPosition = sessionStorage.getItem('organization_tab_position')
  if(getTabPosition && tabElem.value !== null) {
    tabElem.value.scrollLeft = Number(getTabPosition)
  }
})
</script>

<template>
  <div class="card sd-none bd-1px_solid_hexe4e3e6">
    <DetailRecordTab v-model="tab" :tabs="tabs" @handler="(val) => openTab(val.value)" />
    <div class="cardBody p-0px">
      <div class="tableResponsive">
        <table class="table tableList tableFlush" @mouseout="mutateEntry">
          <thead>
            <tr v-if="tab === 'organization_info'">
              <th>Tenant</th>
              <th>DUNS</th>
              <th>Tax ID</th>
              <th>Active</th>
              <th class="w-100px">Action</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="Number(entries[tab]?.length || 0) === 0">
              <td :colspan="action !== 'view' ? 6 : 5" class="align-center">No detail record yet, please add a new one.</td>
            </tr>
            <template v-if="tab === 'organization_info'">
              <template v-for="(entry, index) in entries[tab]" :key="index">
                <tr>
                  <td>
                    <div>{{ entry.tenant }}</div>
                  </td>
                  <td>
                    <div v-if="action === 'view'">{{ entry.DUNS }}</div>
                    <div v-else>
                      <input class="input" v-model="entry.DUNS" />
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view'">{{ entry.taxID }}</div>
                    <div v-else>
                      <input class="input" v-model="entry.taxID" />
                    </div>
                  </td>
                  <td>
                    <div class="check">
                      <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+tab+'_'+index" :checked="entry.isActive" :disabled="action !== 'add' && entry.id !== ''">
                      <label class="checkLabel" :for="'isActive_'+tab+'_'+index">Active</label>
                    </div>
                  </td>
                  <td>
                    <div class="d-flex justify-flexEnd gap-5px">
                      <span @click="entry.show = !entry.show" class="cursor-pointer fg-primary">
                        <i class="menu-icon tf-icons ti" :class="entry?.show ? 'ti-eye-off' : 'ti-eye'"></i>
                      </span>
                      <span v-if="action !== 'view' && entry.id === ''" @click="destroyEntry(entry, index)" class="cursor-pointer fg-danger">
                        <i class="menu-icon tf-icons ti ti-trash"></i>
                      </span>
                    </div>
                  </td>
                </tr>
                <tr v-if="entry?.show">
                  <td :colspan="action !== 'view' ? 6 : 5">
                    <div class="row mb-2 mt-2">     
                      <div class="col-md-6 mb-2">
                        <label class="label">Organization Type</label>
                        <div v-if="action === 'view'">
                          <input class="input" readonly v-model="entry.orgType" />
                        </div>
                        <div v-else>
                          <ClientOnly>
                            <SelectBox v-model="entry.orgTypeId" :options="getOptions?.['orgtypes']?.records || entries[tab].map(i => ({id: i.orgTypeId, Name: i.orgType}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_orgtype', 'orgtypes')" :loading="loading?.['orgtypes'] ?? true" />
                          </ClientOnly>
                        </div>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Parent Organization</label>
                        <div v-if="action === 'view'">
                          <input class="input" readonly v-model="entry.parentOrg" />
                        </div>
                        <div v-else>
                          <ClientOnly>
                            <SelectBox v-model="entry.parentOrgId" :options="getOptions?.['parent_organizations']?.records || entries[tab].map(i => ({id: i.parentOrgId, Name: i.parentOrg}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'parent_organizations')" :loading="loading?.['parent_organizations'] ?? true" />
                          </ClientOnly>
                        </div>
                      </div>  
                      <div class="col-md-6 mb-2">
                        <label class="label">Warehouse</label>
                        <div v-if="action === 'view'">
                          <input class="input" readonly v-model="entry.warehouse" />
                        </div>
                        <div v-else>
                          <ClientOnly>
                            <SelectBox v-model="entry.warehouseId" :options="getOptions?.['warehouses']?.records || entries[tab].map(i => ({id: i.warehouseId, Name: i.warehouse}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_warehouse', 'warehouses')" :loading="loading?.['warehouses'] ?? true" />
                          </ClientOnly>
                        </div>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Drop Ship Warehouse</label>
                        <input class="input" readonly />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Supervisor</label>
                        <div v-if="action === 'view'">
                          <input class="input" readonly v-model="entry.supervisor" />
                        </div>
                        <div v-else>
                          <ClientOnly>
                            <SelectBox v-model="entry.supervisorId" :options="getOptions?.['supervisors']?.records || entries[tab].map(i => ({id: i.supervisorId, Name: i.supervisor}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'supervisors')" :loading="loading?.['supervisors'] ?? true" />
                          </ClientOnly>
                        </div>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Calendar</label>
                        <input class="input" readonly />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Phone</label>
                        <input class="input" readonly />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">2nd Phone</label>
                        <input class="input" readonly />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Fax</label>
                        <input class="input" readonly />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">EMail Address</label>
                        <input class="input" readonly />
                      </div>
                    </div>
                  </td>
                </tr>
              </template>
            </template>
            <tr v-if="action !== 'view' && tab !== 'organization_info'">
              <td colspan="5">
                <button type="button" @click="addEntry" class="button">Add Record</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>