<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 || 'tenant_info')
const entries = ref({
  tenant_info: [],
  tenant_share: []
})
const tabs = ref([
  {value: 'tenant_info', text: 'Tenant Info'},
  {value: 'tenant_share', text: 'Tenant Share'}
])

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 === 'tenant_share') {
    entries.value.tenant_share.push({
      id: '',
      organization: '',
      organizationId: '',
      table: '',
      tableId: '',
      shareType: '',
      shareTypeId: '',
      name: '',
      description: '',
      isActive: true,
      show: true
    })
  }

  emit('handler', tab.value, entries.value)
}
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/tenants/'+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('tenant_detail_record', tab.value)
  }
}
onMounted(() => {
  const getSessionStorageTab = sessionStorage.getItem('tenant_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('tenant_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('tenant_tab_position', tabElem.value.scrollLeft)
  }
}
onMounted(() => {
  const getTabPosition = sessionStorage.getItem('tenant_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 === 'tenant_info'">
              <th>Organization</th>
              <th title="Discount calculated from Line Amounts">Discount Line Amounts</th>
              <th>Keep Log Days</th>
              <th>Confirm On Doc Close</th>
              <th>Confirm On Doc Void</th>
              <th class="w-100px">Action</th>
            </tr>
            <tr v-else-if="tab === 'tenant_share'">
              <th>Organization *</th>
              <th>Name</th>
              <th>Table *</th>
              <th>Share Type *</th>
              <th class="w-100px">Active</th>
              <th v-if="action !== 'view'" 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 === 'tenant_info'">
              <template v-for="(entry, index) in entries[tab]" :key="index">
                <tr>
                  <td>
                    <div v-if="action !== 'add' && entry.id !== ''">{{ entry.organization }}</div>
                  </td>
                  <td>
                    <div class="check">
                      <input type="checkbox" v-model="entry.isDiscountLineAmt" class="checkInput" :id="'isDiscountLineAmt_'+tab+'_'+index" :checked="entry.isDiscountLineAmt" :disabled="action !== 'add' && entry.id !== ''">
                      <label class="checkLabel" :for="'isDiscountLineAmt_'+tab+'_'+index">Discount</label>
                    </div>
                  </td>
                  <td>
                    <div class="check">
                      <input type="checkbox" v-model="entry.keepLogDays" class="checkInput" :id="'keepLogDays_'+tab+'_'+index" :checked="entry.keepLogDays" :disabled="action !== 'add' && entry.id !== ''">
                      <label class="checkLabel" :for="'keepLogDays_'+tab+'_'+index">Log Days</label>
                    </div>
                  </td>
                  <td>
                    <div class="check">
                      <input type="checkbox" v-model="entry.isConfirmOnDocClose" class="checkInput" :id="'isConfirmOnDocClose_'+tab+'_'+index" :checked="entry.isConfirmOnDocClose" :disabled="action !== 'add' && entry.id !== ''">
                      <label class="checkLabel" :for="'isConfirmOnDocClose_'+tab+'_'+index">Doc Close</label>
                    </div>
                  </td>
                  <td>
                    <div class="check">
                      <input type="checkbox" v-model="entry.isConfirmOnDocVoid" class="checkInput" :id="'isConfirmOnDocVoid_'+tab+'_'+index" :checked="entry.isConfirmOnDocVoid" :disabled="action !== 'add' && entry.id !== ''">
                      <label class="checkLabel" :for="'isConfirmOnDocVoid_'+tab+'_'+index">Doc Void</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 Tree</label>
                        <input class="input" readonly v-model="entry.treeOrg" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Menu Tree</label>
                        <input class="input" readonly v-model="entry.treeMenu" />
                      </div>  
                      <div class="col-md-6 mb-2">
                        <label class="label">BPartner Tree</label>
                        <input class="input" readonly v-model="entry.treeBPartner" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Product Tree</label>
                        <input class="input" readonly v-model="entry.treeProduct" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Project Tree</label>
                        <input class="input" readonly v-model="entry.treeProject" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Sales Region Tree</label>
                        <input class="input" readonly v-model="entry.treeSalesRegion" />
                      </div>
                    </div>
                  </td>
                </tr>
              </template>
            </template>
            <template v-else-if="tab === 'tenant_share'">
              <template v-for="(entry, index) in entries[tab]" :key="index">
                <tr>
                  <td>
                    <div v-if="action !== 'add' && entry.id !== ''">{{ entry.organization }}</div>
                    <div v-else>
                      <ClientOnly>
                        <SelectBox v-model="entry.organizationId" :options="getOptions?.['organizations']?.records || entries[tab].map(i => ({id: i.organizationId, Name: i.organization}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'organizations')" :loading="loading?.['organizations'] ?? true" placeholder="----" />
                      </ClientOnly>
                    </div>
                  </td>
                  <td>
                    <div v-if="action !== 'add' && entry.id !== ''">{{ entry.name }}</div>
                    <div v-else>
                      <input class="input" v-model="entry.name" />
                    </div>
                  </td>
                  <td>
                    <div v-if="action !== 'add' && entry.id !== ''">{{ entry.table }}</div>
                    <div v-else>
                      <ClientOnly>
                        <SelectBox v-model="entry.tableId" :options="getOptions?.['tables']?.records || entries[tab].map(i => ({id: i.tableId, Name: i.table}))" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_table', 'tables')" :loading="loading?.['tables'] ?? true" placeholder="----" />
                      </ClientOnly>
                    </div>
                  </td>
                  <td>
                    <div v-if="action !== 'add' && entry.id !== ''">{{ entry.shareType }}</div>
                    <div v-else>
                      <select v-model="entry.shareTypeId" class="select">
                        <option value="N">None</option>
                      </select>
                    </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 v-if="action !== 'view'">
                    <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="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-12 mb-2">
                        <label class="label">Description</label>
                        <textarea class="input" v-model="entry.treeOrg"></textarea>
                      </div>
                    </div>
                  </td>
                </tr>
              </template>
            </template>
            <tr v-if="action !== 'view' && tab !== 'tenant_info'">
              <td colspan="5">
                <button type="button" @click="addEntry" class="button">Add Record</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>