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

const route = useRoute()
const organizationId = useCookie('logship_organization_id')

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

const entries = ref([])
const form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  dunning: props.info?.name || '',
  dunningId: props.info?.id || '',
  isActive: true,
  name: '',
  description: '',
  printName: '',
  note: '',
  daysAfterDue: 0,
  daysBetweenDunning: 0,
  interestPercent: 0,
  feeAmt: 0,
  isShowAllDue: false,
  isShowNotDue: false,
  isSetCreditStop: false,
  isSetPaymentTerm: false,
  isStatement: false,
  chargeInterest: false,
  chargeFee: false,
  printFormat: '',
  printFormatId: '',
  paymentTerm: '',
  paymentTermId: '',
  invoiceCollectionType: '',
  invoiceCollectionTypeId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.dunning = props.info?.name || ''
  form.value.dunningId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const showAddressModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    dunning: props.info?.name || '',
    dunningId: props.info?.id || '',
    isActive: true,
    name: '',
    description: '',
    printName: '',
    note: '',
    daysAfterDue: 0,
    daysBetweenDunning: 0,
    interestPercent: 0,
    feeAmt: 0,
    isShowAllDue: false,
    isShowNotDue: false,
    isSetCreditStop: false,
    isSetPaymentTerm: false,
    isStatement: false,
    chargeInterest: false,
    chargeFee: false,
    printFormat: '',
    printFormatId: '',
    paymentTerm: '',
    paymentTermId: '',
    invoiceCollectionType: '',
    invoiceCollectionTypeId: '',
    alert: {
      status: '',
      message: '',
      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) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/partners/dunnings/'+route.params.id+'/level', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || item?.uid || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          isActive: item?.IsActive ?? true,
          name: item?.Name || '',
          description: item?.Description || '',
          printName: item?.PrintName || '',
          note: item?.Note || '',
          daysAfterDue: item?.DaysAfterDue || 0,
          daysBetweenDunning: item?.DaysBetweenDunning || 0,
          interestPercent: item?.InterestPercent || 0,
          feeAmt: item?.FeeAmt || 0,
          isShowAllDue: item?.IsShowAllDue ?? false,
          isShowNotDue: item?.IsShowNotDue ?? false,
          isSetCreditStop: item?.IsSetCreditStop ?? false,
          isSetPaymentTerm: item?.IsSetPaymentTerm ?? false,
          isStatement: item?.IsStatement ?? false,
          chargeInterest: item?.ChargeInterest ?? false,
          chargeFee: item?.ChargeFee ?? false,
          printFormat: item?.Dunning_PrintFormat_ID?.identifier || '',
          printFormatId: item?.Dunning_PrintFormat_ID?.id || '',
          paymentTerm: item?.C_PaymentTerm_ID?.identifier || '',
          paymentTermId: item?.C_PaymentTerm_ID?.id || '',
          invoiceCollectionType: item?.InvoiceCollectionType?.identifier || '',
          invoiceCollectionTypeId: item?.InvoiceCollectionType?.id || '',
          dunning: item?.C_Dunning_ID?.identifier || '',
          dunningId: item?.C_Dunning_ID?.id || '',
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  //entries.value.splice(index, 1)

  if(entry.id) {
    const res = await $fetch('/api/partners/dunnings/'+entry.id+'/level', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const save = async () => {
  if(form.value.id !== '') {
    const res = await $fetch('/api/partners/dunnings/'+route.params.id+'/level', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        name: form.value.name,
        description: form.value.description,
        printName: form.value.printName,
        note: form.value.note,
        daysAfterDue: form.value.daysAfterDue,
        daysBetweenDunning: form.value.daysBetweenDunning,
        interestPercent: form.value.interestPercent,
        feeAmt: form.value.feeAmt,
        isShowAllDue: form.value.isShowAllDue,
        isShowNotDue: form.value.isShowNotDue,
        isSetCreditStop: form.value.isSetCreditStop,
        isSetPaymentTerm: form.value.isSetPaymentTerm,
        isStatement: form.value.isStatement,
        chargeInterest: form.value.chargeInterest,
        chargeFee: form.value.chargeFee,
        printFormatId: form.value.printFormatId,
        paymentTermId: form.value.paymentTermId,
        invoiceCollectionTypeId: form.value.invoiceCollectionTypeId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 7500,
        position: 'bottom-right'
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 7500,
        position: 'bottom-right'
      })
    }
  } else {
    const res = await $fetch('/api/partners/dunnings/'+route.params.id+'/level', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        name: form.value.name,
        description: form.value.description,
        printName: form.value.printName,
        note: form.value.note,
        daysAfterDue: form.value.daysAfterDue,
        daysBetweenDunning: form.value.daysBetweenDunning,
        interestPercent: form.value.interestPercent,
        feeAmt: form.value.feeAmt,
        isShowAllDue: form.value.isShowAllDue,
        isShowNotDue: form.value.isShowNotDue,
        isSetCreditStop: form.value.isSetCreditStop,
        isSetPaymentTerm: form.value.isSetPaymentTerm,
        isStatement: form.value.isStatement,
        chargeInterest: form.value.chargeInterest,
        chargeFee: form.value.chargeFee,
        printFormatId: form.value.printFormatId,
        paymentTermId: form.value.paymentTermId,
        invoiceCollectionTypeId: form.value.invoiceCollectionTypeId,
        dunningId: form.value.dunningId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 7500,
        position: 'bottom-right'
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 7500,
        position: 'bottom-right'
      })
    }
  }
}

const langHandler = (val, opt) => {
  console.log(val)
  console.log(opt)
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Name</th>
            <th>Print Text</th>
            <th>Days after due</th>
            <th>Days between dunning</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.length) === 0">
            <td :colspan="action !== 'view' ? 7 : 6" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.name }}</td>
            <td>{{ entry.printName }}</td>
            <td>{{ entry.daysAfterDue }}</td>
            <td>{{ entry.daysBetweenDunning }}</td>
            <td class="textAlignCenter">
              <div class="check">
                <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" disabled>
                <!--<label class="checkLabel" :for="'isActive_'+index">Active</label>-->
              </div>
            </td>
            <td v-if="action !== 'view'">
              <div class="d-flex justify-flexEnd gap-5px">
                <span @click="form = entry; showDetailRecordModal = true;" class="cursor-pointer fg-warning">
                  <i class="menu-icon tf-icons ti ti-pencil"></i>
                </span>
                <span @click="destroy(entry, index)" class="cursor-pointer fg-danger">
                  <i class="menu-icon tf-icons ti ti-trash"></i>
                </span>
              </div>
            </td>
          </tr>
          <tr v-if="action !== 'view'">
            <td colspan="5">
              <button type="button" @click="showDetailRecordModal = true;" class="button">Add Record</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

  <Teleport to="body">
    <div class="modal" :class="{'active': showDetailRecordModal}" :style="{display: showDetailRecordModal ? 'block' : 'none'}">
      <div class="modalDialog modalCenter modalPrintPreview" @click.self="closeDetailRecordModal">
        <div class="modalContent">
          <div class="modalHeader">
            <h3 class="modalTitle">Dunning Level</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody">
            <div class="my-5 mx-5">
              <AlertAction v-model='form.alert.status' :alert="form.alert" />
              <div class="columns">
                <div class="column is-two-thirds">
                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block">Name *</label>
                      <input type="text" v-model="form.name" class="input" />

                      <label class="label d-block mt-2">Collection Status</label>
                      <select v-model="form.invoiceCollectionTypeId" class="select">
                        <option value="C">Collection Agency</option>
                        <option value="D">Dunning</option>
                        <option value="L">Legal Procedure</option>
                        <option value="U">Uncollectable</option>
                      </select>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">Print Text *</label>
                      <input type="text" v-model="form.printName" class="input" />

                      <label class="label d-block mt-2">Print Format</label>
                      <ClientOnly>
                        <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>

                  <template v-if="form.isSetPaymentTerm === true">
                    <label class="label d-block mt-2">Payment Term</label>
                    <ClientOnly>
                      <SelectBox v-model="form.paymentTermId" :options="getOptions?.['payment_terms']?.records || [{id: form.paymentTermId, Name: form.paymentTerm}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_paymentterm', 'payment_terms')" :loading="loading?.['payment_terms'] ?? true" />
                    </ClientOnly>
                  </template>

                  <label class="label d-block mt-2">Description</label>
                  <textarea v-model="form.description" class="input"></textarea>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Days after due date *</label>
                      <input type="text" v-model="form.daysAfterDue" class="input" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Days between dunning *</label>
                      <input type="text" v-model="form.daysBetweenDunning" class="input" />
                    </div>
                  </div>

                  <label class="label d-block mt-2">Note</label>
                  <textarea v-model="form.note" class="input"></textarea>
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">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">
                      <label class="checkLabel" for="isActive">Active</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isShowAllDue" class="checkInput" id="isShowAllDue" :checked="form.isShowAllDue">
                      <label class="checkLabel" for="isShowAllDue">Show All Due</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isShowNotDue" class="checkInput" id="isShowNotDue" :checked="form.isShowNotDue">
                      <label class="checkLabel" for="isShowNotDue">Show Not Due</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isSetCreditStop" class="checkInput" id="isSetCreditStop" :checked="form.isSetCreditStop">
                      <label class="checkLabel" for="isSetCreditStop">Set Credit Stop</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isSetPaymentTerm" class="checkInput" id="isSetPaymentTerm" :checked="form.isSetPaymentTerm">
                      <label class="checkLabel" for="isSetPaymentTerm">Set Payment Term</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isStatement" class="checkInput" id="isStatement" :checked="form.isStatement">
                      <label class="checkLabel" for="isStatement">Statement</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.chargeInterest" class="checkInput" id="chargeInterest" :checked="form.chargeInterest">
                      <label class="checkLabel" for="chargeInterest">Charge Interest</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.chargeFee" class="checkInput" id="chargeFee" :checked="form.chargeFee">
                      <label class="checkLabel" for="chargeFee">Charge Fee</label>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="modalFooter">
            <div></div>
            <div class="d-flex gap-10px">
              <button type="button" class="button" @click="closeDetailRecordModal">Close</button>
              <button type="button" class="button" @click="save" :class="(form.name === '' || form.printName === '' || form.daysAfterDue === '' || form.daysBetweenDunning === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>