<script setup>
import { date, array } 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 || '',
  order: props.info?.order || '',
  orderId: props.info?.orderId || '',
  paySchedule: '',
  payScheduleId: '',
  discountAmt: 0,
  discountDate: date.now('date'),
  dueAmt: 0,
  dueDate: date.now('date'),
  processed: false,
  isActive: true,
  isValid: false,
  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.order = props.info?.order || ''
  form.value.orderId = props.info?.orderId || ''
})

const showDetailRecordModal = 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 || '',
    order: props.info?.order || '',
    orderId: props.info?.orderId || '',
    paySchedule: '',
    payScheduleId: '',
    discountAmt: 0,
    discountDate: date.now('date'),
    dueAmt: 0,
    dueDate: date.now('date'),
    processed: false,
    isActive: true,
    isValid: false,
    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 () => {
  const newId = route.params?.id || props.info?.id || null
  if(newId) {
    const res = await $fetch('/api/orders/'+newId+'/payment-schedule', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          order: item?.C_Order_ID?.identifier || '',
          orderId: item?.C_Order_ID?.id || '',
          paySchedule: item?.C_PaySchedule_ID?.identifier || '',
          payScheduleId: item?.C_PaySchedule_ID?.id || '',
          discountAmt: item?.DiscountAmt || 0,
          discountDate: item?.DiscountDate || date.now('date'),
          dueAmt: item?.DueAmt || 0,
          dueDate: item?.DueDate || date.now('date'),
          processed: item?.Processed ?? false,
          isActive: item?.IsActive ?? true,
          isValid: item?.IsValid ?? false,
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

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

  if(entry.id) {
    await $fetch('/api/orders/'+entry.id+'/payment-schedule', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
}

const save = async () => {
  if(form.value.id !== '') {
    const res = await $fetch('/api/orders/'+route.params.id+'/payment-schedule', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        payScheduleId: form.value.payScheduleId,
        discountAmt: form.value.discountAmt,
        discountDate: form.value.discountDate,
        dueAmt: form.value.dueAmt,
        dueDate: form.value.dueDate,
        processed: form.value.processed,
        isActive: form.value.isActive,
        isValid: form.value.isValid,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } 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: 2000
      })
    }
  } else {
    const res = await $fetch('/api/orders/'+route.params.id+'/payment-schedule', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        orderId: route.params.id,
        payScheduleId: form.value.payScheduleId,
        discountAmt: form.value.discountAmt,
        discountDate: form.value.discountDate,
        dueAmt: form.value.dueAmt,
        dueDate: form.value.dueDate,
        processed: form.value.processed,
        isActive: form.value.isActive,
        isValid: form.value.isValid,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } 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: 2000
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Payment Schedule</th>
            <th>Due Date</th>
            <th>Discount Date</th>
            <th>Amount due</th>
            <th>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.length) === 0">
            <td :colspan="action !== 'view' ? 8 : 7" 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.paySchedule }}</td>
            <td>{{ entry.dueDate }}</td>
            <td>{{ entry.discountDate }}</td>
            <td>{{ entry.dueAmt }}</td>
            <td>{{ entry.discountAmt }}</td>
            <td>
              <div class="check">
                <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" :disabled="action === 'view'">
                <label class="checkLabel" :for="'isActive_'+index">Active</label>
              </div>
            </td>
            <td>
              <div class="check">
                <input type="checkbox" v-model="entry.isValid" class="checkInput" :id="'isValid_'+index" :checked="entry.isValid" disabled>
                <label class="checkLabel" :for="'isValid_'+index">Valid</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; form.paySchedule = ''; form.payScheduleId = '';" 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">Payment Schedule</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">
                  <label class="label d-block">Pay Schedule</label>
                  <ClientOnly>
                    <SelectBox v-model="form.payScheduleId" :options="getOptions?.['pay_schedules']?.records?.map(i => {i.Name = `${i.C_PaymentTerm_ID.identifier}_${i.NetDays}_Days_${i.Percentage}%`; return i;}) || [{id: form.payScheduleId, Name: form.paySchedule}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_payschedule', 'pay_schedules')" :loading="loading?.['pay_schedules'] ?? true" />
                  </ClientOnly>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Due Date *</label>
                      <DatePicker v-model="form.dueDate" />
                      
                      <label class="label d-block mt-2">Amount due *</label>
                      <input type="text" v-model="form.dueAmt" class="input" :disabled="action === 'view'" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Discount Date *</label>
                      <DatePicker v-model="form.discountDate" />

                      <label class="label d-block mt-2">Discount Amount *</label>
                      <input type="text" v-model="form.discountAmt" class="input" :disabled="action === 'view'" />
                    </div>
                  </div>

                </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.isValid" class="checkInput" id="isValid" :checked="form.isValid">
                      <label class="checkLabel" for="isValid">Valid</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.locationId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>