<script setup>
const props = defineProps({
  action: String,
  info: Object,
  tab: String
})

const tab = ref(props.tab || 'invoice_line')
const tabs = ref([
  {value: 'invoice_line', text: 'Invoice Line'},
  {value: 'invoice_tax', text: 'Invoice Tax'},
  {value: 'payment_schedule', text: 'Payment Schedule'}
])

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

/*const addEntry = () => {
  if(tab.value === 'invoice_line') {
    let lineNum = 1
    if(Number(entries.value.invoice_line.length || 0) === 1) {
      lineNum = 2
    } else if(Number(entries.value.invoice_line.length || 0) >= 2) {
      lineNum = Number(array.math(entries.value.invoice_line, 'max', 'line')) + 1
    }
    entries.value.invoice_line.push({
      id: '',
      line: lineNum,
      product: '',
      productId: '',
      qtyEntered: 1,
      uom: '',
      uomId: '',
      priceActual: 0,
      priceEntered: 0,
      priceList: 0,
      priceLimit: 0,
      tax: '',
      taxId: '',
      taxAmt: 0,
      lineNetAmt: 0,
      inOutLine: '',
      inOutLineId: '',
      attributeSetInstance: '',
      attributeSetInstanceId: '',
      charge: '',
      chargeId: '',
      project: '',
      projectId: '',
      campaign: '',
      campaignId: '',
      isActive: true,
      show: true
    })
  } else if(tab.value === 'payment_schedule') {
    entries.value.payment_schedule.push({
      id: '',
      paySchedule: '',
      payScheduleId: '',
      discountAmt: 0,
      discountDate: date.now('date'),
      dueAmt: 0,
      dueDate: date.now('date'),
      processed: false,
      isActive: true,
      isValid: 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/invoices/'+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.invoice_line = array.move(entries.value.invoice_line, index, 'line', type)
}

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

const checkProductInvoiceLine = (id) => {
  const productIds = entries.value.invoice_line.map(i => i.productId)
  return productIds.includes(id)
}*/

const openTab = async (val) => {
  if(tab.value !== val) {
    tab.value = val
    sessionStorage.setItem('sales_invoice_detail_record', tab.value)
  }
}
onMounted(() => {
  const getSessionStorageTab = sessionStorage.getItem('sales_invoice_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)" />
    <SalesInvoiceDetailRecordLine v-if="tab === 'invoice_line'" :action="action" :info="info" />
    <SalesInvoiceDetailRecordTax v-else-if="tab === 'invoice_tax'" :action="action" :info="info" />
    <SalesInvoiceDetailRecordPaymentSchedule v-else-if="tab === 'payment_schedule'" :action="action" :info="info" />
    <!--<div class="cardBody p-0px">
      <div class="tableResponsive">
        <table class="table tableList tableFlush" @mouseout="mutateEntry">
          <thead>
            <tr v-if="tab === 'invoice_line'">
              <th>Line</th>
              <th>Product *</th>
              <th>Unit *</th>
              <th class="w-120px">Qty *</th>
              <th class="w-120px">Price *</th>
              <th class="w-120px">Amount</th>
              <th class="w-100px">Action</th>
            </tr>
            <tr v-else-if="tab === 'invoice_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>
            <tr v-else-if="tab === 'payment_schedule'">
              <th>Payment Schedule</th>
              <th v-if="action === 'view'">Due Date</th>
              <th v-if="action === 'view'">Discount Date</th>
              <th v-if="action === 'view'">Amount due</th>
              <th v-if="action === 'view'">Discount Amount</th>
              <th class="w-100px">Active</th>
              <th class="w-100px">Valid</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="7" class="align-center">No detail record yet, please add a new one.</td>
            </tr>
            <template v-if="tab === 'invoice_line'">
              <template v-for="(entry, index) in entries[tab]" :key="index">
                <tr>
                  <td>{{ entry.line }}</td>
                  <td>
                    <div v-if="action === 'view' || entry.productId" @click="entry.productId = entry.id === '' ? '' : entry.productId">{{ entry.product }}</div>
                    <div v-else>
                      <ClientOnly>
                        <SelectBox v-model="entry.productId" :options="getOptions?.['products']?.records?.filter(i => !checkProductInvoiceLine(i.id)) || [{id: entry.productId, Name: entry.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'products')" @change="(val, opt) => setInvoiceLine(entry, opt)" :loading="loading?.['products'] ?? true" placeholder="----" />
                      </ClientOnly>
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view' || (entry.uomId && entry.id)">{{ entry.uom }}</div>
                    <div v-else>
                      <ClientOnly>
                        <SelectBox v-model="entry.uomId" :options="getOptions?.['units']?.records || [{id: entry.uomId, Name: entry.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_uom', 'units')" :loading="loading?.['units'] ?? true" placeholder="----" />
                      </ClientOnly>
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view' || (entry.productId && entry.id)">{{ entry.qtyEntered }}</div>
                    <div v-else>
                      <input type="text" v-model="entry.qtyEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered); mutateEntry();" class="input" />
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view' || (entry.productId && entry.id)">{{ entry.priceEntered }}</div>
                    <div v-else>
                      <input type="text" v-model="entry.priceEntered" @input="entry.lineNetAmt = Number(entry.qtyEntered) * Number(entry.priceEntered); mutateEntry();" class="input" />
                    </div>
                  </td>
                  <td>
                    <div v-if="action === 'view' || (entry.productId && entry.id)">{{ 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.invoice_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="row mb-2 mt-2"> 
                      <div class="col-md-6 mb-2">
                        <label class="label">Line</label>
                        <input type="text" :value="entry.line || Number(index) + 1" class="input" readonly />
                      </div>
                      <div class="col-md-6 mb-2">
                        <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>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Cost Price</label>
                        <input type="text" v-model="entry.priceActual" class="input" :disabled="action === 'view'" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Price List</label>
                        <input type="text" v-model="entry.priceList" class="input" :disabled="action === 'view'" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">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>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Tax Amount</label>
                        <input type="text" v-model="entry.taxAmt" class="input" :disabled="action === 'view'" />
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Project</label>
                        <template v-if="action === 'view'">
                          <input type="text" :value="entry.project" class="input" readonly />
                        </template>
                        <ClientOnly v-else>
                          <SelectBox v-model="entry.projectId" :options="getOptions?.['projects']?.records || [{id: entry.projectId, Name: entry.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_project', 'projects')" :loading="loading?.['projects'] ?? true" placeholder="----" />
                        </ClientOnly>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Campaign</label>
                        <template v-if="action === 'view'">
                          <input type="text" :value="entry.campaign" class="input" readonly />
                        </template>
                        <ClientOnly v-else>
                          <SelectBox v-model="entry.campaignId" :options="getOptions?.['campaigns']?.records || [{id: entry.campaignId, Name: entry.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_campaign', 'campaigns')" :loading="loading?.['campaigns'] ?? true" placeholder="----" />
                        </ClientOnly>
                      </div>
                      <div class="col-md-12 mb-2">
                        <label class="label">Description</label>
                        <textarea v-model="entry.description" class="input" :disabled="action === 'view'"></textarea>
                      </div>       
                      <div class="col-md-6">
                        <label class="label">Attribute Set Instance</label>
                        <input type="text" v-model="entry.attributeSetInstance" class="input" readonly />
                      </div>  
                      <div class="col-md-6">
                        <label class="label">Asset</label>
                        <input type="text" class="input" readonly/>
                      </div>
                    </div>
                  </td>
                </tr>
              </template>
            </template>
            <template v-else-if="tab === 'invoice_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>
            <template v-else-if="tab === 'payment_schedule'">
              <template v-for="(entry, index) in entries[tab]" :key="index">
                <tr>
                  <td>
                    <div v-if="action === 'view'">{{ entry.paySchedule }}</div>
                    <div v-else>
                      <ClientOnly>
                        <SelectBox v-model="entry.payScheduleId" :options="getOptions?.['pay_schedules']?.records?.map(i => {i.Name = i.C_PaymentTerm_ID.identifier; return i;}) || [{id: entry.payScheduleId, Name: entry.paySchedule}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_payschedule', 'pay_schedules')" :loading="loading?.['pay_schedules'] ?? true" placeholder="----" />
                      </ClientOnly>
                    </div>
                  </td>
                  <td v-if="action === 'view'">{{ entry.dueDate }}</td>
                  <td v-if="action === 'view'">{{ entry.discountDate }}</td>
                  <td v-if="action === 'view'">{{ entry.dueAmt }}</td>
                  <td v-if="action === 'view'">{{ entry.discountAmt }}</td>
                  <td>
                    <div class="check">
                      <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+tab+'_'+index" :checked="entry.isActive" :disabled="action === 'view'">
                      <label class="checkLabel" :for="'isActive_'+tab+'_'+index">Active</label>
                    </div>
                  </td>
                  <td>
                    <div class="check">
                      <input type="checkbox" :value="entry.isValid" class="checkInput" :id="'isValid_'+tab+'_'+index" :checked="entry.isValid" disabled>
                      <label class="checkLabel" :for="'isValid_'+tab+'_'+index">Valid</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 @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' ? 5 : 4">
                    <div class="row mb-2 mt-2">     
                      <div class="col-md-6 mb-2">
                        <label class="label">Due Date *</label>
                        <template v-if="action === 'view'">
                          <input type="text" v-model="entry.dueDate" class="input" disabled />
                        </template>
                        <template v-else>
                          <DatePicker v-model="entry.dueDate" />
                        </template>
                      </div>     
                      <div class="col-md-6 mb-2">
                        <label class="label">Amount due *</label>
                        <input type="text" v-model="entry.dueAmt" class="input" :disabled="action === 'view'" />
                      </div>    
                      <div class="col-md-6 mb-2">
                        <label class="label">Discount Date *</label>
                        <template v-if="action === 'view'">
                          <input type="text" v-model="entry.discountDate" class="input" disabled />
                        </template>
                        <template v-else>
                          <DatePicker v-model="entry.discountDate" />
                        </template>
                      </div>
                      <div class="col-md-6 mb-2">
                        <label class="label">Discount Amount *</label>
                        <input type="text" v-model="entry.discountAmt" class="input" :disabled="action === 'view'" />
                      </div>
                    </div>
                  </td>
                </tr>
              </template>
            </template>
            <tr v-if="action !== 'view' && tab !== 'invoice_tax'">
              <td colspan="5">
                <button type="button" @click="addEntry" class="button">Add Record</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>-->
  </div>
</template>