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

const { t } = useTranslation()

const route = useRoute()
const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')

const clientName = ref('')
onMounted(() => {
  const getClient = localStorage.getItem('logship_clients')
  if(getClient) {
    const clientObj = JSON.parse(getClient)
    clientName.value = clientObj[0].name
  }
})

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 || '',
  partner: props.info?.name || '',
  partnerId: props.info?.id || '',
  isActive: true,
  dutiesShipperAccount: '',
  shipperAccount: '',
  shipperMeter: '',
  partnerLocation: '',
  partnerLocationId: '',
  shippingProcessor: '',
  shippingProcessorId: '',
  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.partner = props.info?.name || ''
  form.value.partnerId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const resetDetailRecordModal = () => {
  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    partner: props.info?.name || '',
    partnerId: props.info?.id || '',
    isActive: true,
    dutiesShipperAccount: '',
    shipperAccount: '',
    shipperMeter: '',
    partnerLocation: '',
    partnerLocationId: '',
    shippingProcessor: '',
    shippingProcessorId: '',
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false
  resetDetailRecordModal()
}

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/partners/'+route.params.id+'/shipping-accounts', {
      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 || '',
          partner: item?.C_BPartner_ID?.identifier || '',
          partnerId: item?.C_BPartner_ID?.id || '',
          isActive: item?.IsActive ?? true,
          dutiesShipperAccount: item?.DutiesShipperAccount || '',
          shipperAccount: item?.ShipperAccount || '',
          shipperMeter: item?.ShipperMeter || '',
          partnerLocation: item?.C_BPartner_Location_ID?.identifier || '',
          partnerLocationId: item?.C_BPartner_Location_ID?.id || '',
          shippingProcessor: item?.M_ShippingProcessor_ID?.identifier || '',
          shippingProcessorId: item?.M_ShippingProcessor_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/partners/'+entry.id+'/shipping-accounts', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const save = async () => {
  console.log(form.value)
  if(form.value.id !== '') {
    const res = await $fetch('/api/partners/partners/'+route.params.id+'/shipping-accounts', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        dutiesShipperAccount: form.value.dutiesShipperAccount,
        shipperAccount: form.value.shipperAccount,
        shipperMeter: form.value.shipperMeter,
        partnerLocationId: form.value.partnerLocationId,
        shippingProcessorId: form.value.shippingProcessorId,
      }
    })
    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/partners/partners/'+route.params.id+'/shipping-accounts', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        dutiesShipperAccount: form.value.dutiesShipperAccount,
        shipperAccount: form.value.shipperAccount,
        shipperMeter: form.value.shipperMeter,
        partnerLocationId: form.value.partnerLocationId,
        shippingProcessorId: form.value.shippingProcessorId,
        partnerId: form.value.partnerId,
      }
    })
    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>{{ t.shipper_account }}</th>
            <th>{{ t.meter }}</th>
            <th>{{ t.duties_shipper }}</th>
            <th>{{ t.location }}</th>
            <th class="w-100px">{{ t.active }}</th>
            <th v-if="action !== 'view'" class="w-100px">{{ t.action }}</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td :colspan="action !== 'view' ? 7 : 6" class="align-center">{{ t.no_detail_record }}</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.shipperAccount }}</td>
            <td>{{ entry.shipperMeter }}</td>
            <td>{{ entry.dutiesShipperAccount }}</td>
            <td>{{ entry.partnerLocation }}</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="resetDetailRecordModal(); showDetailRecordModal = true;" class="button">{{ t.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">{{ t.shipping_account }}</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">{{ t.shipper_account }}</label>
                      <input type="text" v-model="form.shipperAccount" class="input" />

                      <label class="label d-block mt-2">{{ t.duties_shipper_account }}</label>
                      <input type="text" v-model="form.dutiesShipperAccount" class="input" />

                      <label class="label d-block mt-2">{{ t.shipping_processor }}</label>
                      <ClientOnly>
                        <SelectBox v-model="form.shippingProcessorId" :options="getOptions?.['shipping_processors']?.records || [{id: form.shippingProcessorId, Name: form.shippingProcessor}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions(`models/m_shippingprocessor`, 'shipping_processors')" :loading="loading?.['shipping_processors'] ?? true" />
                      </ClientOnly>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">{{ t.shipper_meter }}</label>
                      <input type="text" v-model="form.shipperMeter" class="input" />

                      <label class="label d-block mt-2">{{ t.partner_location }}</label>
                      <ClientOnly>
                        <SelectBox v-model="form.partnerLocationId" :options="getOptions?.['partner_locations']?.records || [{id: form.partnerLocationId, Name: form.partnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions(`partners/partners/${form.partnerId}/locations/ship`, 'partner_locations')" :loading="loading?.['partner_locations'] ?? true" />
                      </ClientOnly>
                    </div>
                  </div>

                </div>
                <div class="column is-one-third">
                  <label class="label d-block">{{ t.organization }} *</label>
                  <SelectBox v-model="form.organizationId" :options="getOptions?.['orgs']?.records || [{id: form.organizationId, Name: form.organization}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_org', 'orgs')" @change="(val, opt) => {form.organization = opt.Name; save();}" :loading="loading?.['orgs'] ?? true" />

                  <label class="label d-block mt-2">{{ t.tenant }} *</label>
                  <input type="text" :value="form.client" class="input" readonly />

                  <label class="label d-block mt-2">{{ t.business_partner }} *</label>
                  <input type="text" :value="form.partner" class="input" readonly />

                  <label class="label d-block mt-2">{{ t.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">{{ t.active }}</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">{{ t.close }}</button>
              <button type="button" class="button" @click="save" :class="form.alert.processing ? 'pointerEvents-none opacity-0.6' : ''">{{ t.submit }}</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>