<script setup>
import { date, array } 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', 'update:entries', '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 || 'rma_line')
const entries = ref({
  rma_line: [],
  rma_tax: []
})
const tabs = ref([
  {value: 'rma_line', text: 'RMA Line'},
  {value: 'rma_tax', text: 'RMA Tax'}
])

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 === 'rma_line') {
    entries.value.rma_line.push({
      id: '',
      line: Number(array.math(entries.value.rma_line, 'max', 'line') + 1),
      product: '',
      productId: '',
      qty: 1,
      amt: 0,
      tax: '',
      taxId: '',
      lineNetAmt: 0,
      inOutLine: '',
      inOutLineId: '',
      charge: '',
      chargeId: '',
      isActive: true,
      processed: false,
      show: true
    })
  }

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

  if(entry.id) {
    await $fetch('/api/rma/'+entry.id+'/'+tab.value.replaceAll('_', '-'), {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
  emit('update:entries', entries.value)
  emit('handler', tab.value, entries.value)
}
const moveEntry = (index, type) => {
  entries.value.rma_line = array.move(entries.value.rma_line, index, 'line', type)
}

const setRMALine = (rmaLine, opt) => {
  //rmaLine.uom = opt?.C_UOM_ID.identifier || ''
  //rmaLine.uomId = opt?.C_UOM_ID.id || ''
  //rmaLine.attributeSetInstance = opt?.M_AttributeSetInstance_ID.identifier || ''
  //rmaLine.attributeSetInstanceId = opt?.M_AttributeSetInstance_ID.id || ''
  rmaLine.product = opt.Name
  rmaLine.productId = opt.id
}

const openTab = async (val) => {
  if(tab.value !== val) {
    tab.value = val
    emit('update:modelValue', tab.value)
    emit('update:entries', entries.value)
    emit('handler', tab.value, entries.value)
    sessionStorage.setItem('customer_rma_detail_record', tab.value)
  }
}
onMounted(() => {
  const getSessionStorageTab = sessionStorage.getItem('customer_rma_detail_record')
  if(getSessionStorageTab) {
    openTab(getSessionStorageTab)
  }
})
</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 === 'rma_line'">
              <th>Product *</th>
              <th class="w-120px">Qty *</th>
              <th class="w-120px">Amount *</th>
              <th class="w-120px">Line Amount</th>
              <th class="w-100px">Action</th>
            </tr>
            <tr v-else-if="tab === 'rma_tax'">
              <th>Tax</th>
              <th>Tax Amount</th>
              <th>Tax base Amount</th>
              <th>Price includes Tax</th>
              <th>Processed</th>
              <th class="w-100px">Active</th>
            </tr>
          </thead>
          <tbody>
            <tr v-if="Number(entries[tab]?.length || 0) === 0">
              <td colspan="7" class="align-center">No detail record yet, please add a new one.</td>
            </tr>
            <template v-if="tab === 'rma_line'">
              <template v-for="(entry, index) in entries[tab]" :key="index">
                <tr>
                  <td>
                    <div v-if="action === 'view' || (entry.productId && entry.id)">{{ entry.product }}</div>
                    <div v-else>
                      <ClientOnly>
                        <SelectBox v-model="entry.productId" :options="getOptions?.['products']?.records || [{id: entry.productId, Name: entry.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'products')" @change="(val, opt) => setRMALine(entry, opt)" :loading="loading?.['products'] ?? true" placeholder="----" />
                      </ClientOnly>
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view'">{{ entry.qty }}</div>
                    <div v-else>
                      <input type="text" v-model="entry.qty" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt); mutateEntry();" class="input" />
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view'">{{ entry.amt }}</div>
                    <div v-else>
                      <input type="text" v-model="entry.amt" @input="entry.lineNetAmt = Number(entry.qty) * Number(entry.amt); mutateEntry();" class="input" />
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view'">{{ entry.lineNetAmt }}</div>
                    <div v-else>
                      <input type="text" v-model="entry.lineNetAmt" class="input" readonly />
                    </div>
                  </td>
                  <td>
                    <div class="d-flex justify-flexEnd gap-5px">
                      <span v-if="Number(index) !== 0 && action !== 'view'" @click="moveEntry(index, 'up')" class="cursor-pointer fg-success">
                        <i class="menu-icon tf-icons ti ti-arrow-big-up"></i>
                      </span>
                      <span v-if="Number(index) !== (Number(entries.rma_line.length) - 1) && action !== 'view'" @click="moveEntry(index, 'down')" class="cursor-pointer fg-danger">
                        <i class="menu-icon tf-icons ti ti-arrow-big-down"></i>
                      </span>
                      <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'" @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="7">
                    <div class="m-2 mt-2">
                      <div class="columns is-desktop">
                        <div class="column is-half">
                          <label class="label">Line</label>
                          <input type="text" :value="entry.line || Number(index) + 1" class="input" readonly />

                          <label class="label d-block mt-2">Tax</label>
                          <template v-if="action === 'view'">
                            <input type="text" :value="entry.tax" class="input" readonly />
                          </template>
                          <ClientOnly v-else>
                            <SelectBox v-model="entry.taxId" :options="getOptions?.['taxes']?.records || [{id: entry.taxId, Name: entry.tax}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_tax', 'taxes')" :loading="loading?.['taxes'] ?? true" placeholder="----" />
                          </ClientOnly>

                          <label class="label d-block mt-2">Description</label>
                          <textarea v-model="entry.description" class="input" :disabled="action === 'view'"></textarea>
                        </div>
                        <div class="column is-half">
                          <label class="label">Charge</label>
                          <template v-if="action === 'view'">
                            <input type="text" :value="entry.charge" class="input" readonly />
                          </template>
                          <ClientOnly v-else>
                            <SelectBox v-model="entry.chargeId" :options="getOptions?.['charges']?.records || [{id: entry.chargeId, Name: entry.charge}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_charge', 'charges')" :loading="loading?.['charges'] ?? true" placeholder="----" />
                          </ClientOnly>

                          <!--<label class="label d-block mt-2">Tax Amount</label>
                          <input type="text" v-model="entry.taxAmt" class="input" :disabled="action === 'view'" />-->

                          <label class="label d-block mt-2">Shipment/Receipt Line</label>
                          <template v-if="action === 'view'">
                            <input type="text" :value="entry.inOutLineId" class="input" readonly />
                          </template>
                          <ClientOnly v-else>
                            <SelectBox v-model="entry.inOutLineId" :options="getOptions?.['inout_lines']?.records || [{id: entry.inOutLineId, Name: entry.inOutLine}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_inoutline', 'inout_lines')" :loading="loading?.['inout_lines'] ?? true" placeholder="----" />
                          </ClientOnly>
                        </div>
                      </div>

                    </div>
                  </td>
                </tr>
              </template>
            </template>
            <template v-else-if="tab === 'rma_tax'">
              <tr v-for="(entry, index) in entries[tab]" :key="index">
                <td>{{ entry.tax }}</td>
                <td>{{ entry.taxAmt }}</td>
                <td>{{ entry.taxBaseAmt }}</td>
                <td>
                  <div class="check">
                    <input type="checkbox" v-model="entry.isTaxIncluded" class="checkInput" :id="'isTaxIncluded_'+tab+'_'+index" :checked="entry.isTaxIncluded" disabled>
                    <label class="checkLabel" :for="'isTaxIncluded_'+tab+'_'+index">Tax Included</label>
                  </div>
                </td>
                <td>
                  <div class="check">
                    <input type="checkbox" v-model="entry.processed" class="checkInput" :id="'processed_'+tab+'_'+index" :checked="entry.processed" disabled>
                    <label class="checkLabel" :for="'processed_'+tab+'_'+index">Processed</label>
                  </div>
                </td>
                <td>
                  <div class="check">
                    <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+tab+'_'+index" :checked="entry.isActive" disabled>
                    <label class="checkLabel" :for="'isActive_'+tab+'_'+index">Active</label>
                  </div>
                </td>
              </tr>
            </template>
            <tr v-if="action !== 'view' && tab !== 'rma_tax'">
              <td colspan="5">
                <button type="button" @click="addEntry" class="button">Add Record</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>