<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 || '',
  product: props.info?.name || '',
  productId: props.info?.id || '',
  isActive: true,
  movementDate: '',
  movementQty: '',
  movementType: '',
  movementTypeId: '',
  locator: '',
  locatorId: '',
  movementLine: '',
  movementLineId: '',
  attributeSetInstance: '',
  attributeSetInstanceId: '',
  inOutLine: '',
  inOutLineId: '',
  inventoryLine: '',
  inventoryLineId: '',
  movementLine: '',
  movementLineId: '',
  productionLine: '',
  productionLineId: '',
  projectIssue: '',
  projectIssueId: '',
  costCollector: '',
  costCollectorId: '',
  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.product = props.info?.name || ''
  form.value.productId = 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 || '',
    product: props.info?.name || '',
    productId: props.info?.id || '',
    isActive: true,
    movementDate: '',
    movementQty: '',
    movementType: '',
    movementTypeId: '',
    locator: '',
    locatorId: '',
    movementLine: '',
    movementLineId: '',
    attributeSetInstance: '',
    attributeSetInstanceId: '',
    inOutLine: '',
    inOutLineId: '',
    inventoryLine: '',
    inventoryLineId: '',
    movementLine: '',
    movementLineId: '',
    productionLine: '',
    productionLineId: '',
    projectIssue: '',
    projectIssueId: '',
    costCollector: '',
    costCollectorId: '',
    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/materials/products/'+route.params.id+'/transaction', {
      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 || '',
          product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          isActive: item?.IsActive ?? true,
          accountingSchema: item?.C_AcctSchema_ID?.identifier || '',
          accountingSchemaId: item?.C_AcctSchema_ID?.id || '',
          movementDate: item?.MovementDate || '',
          movementQty: item?.MovementQty || '',
          movementType: item?.MovementType?.identifier || '',
          movementTypeId: item?.MovementType?.id || '',
          locator: item?.M_Locator_ID?.identifier || item?.M_Locator_ID?.Value || '',
          locatorId: item?.M_Locator_ID?.id || '',
          movementLine: item?.M_MovementLine_ID?.identifier || '',
          movementLineId: item?.M_MovementLine_ID?.id || '',
          attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
          attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
          inOutLine: item?.M_InOutLine_ID?.identifier || '',
          inOutLineId: item?.M_InOutLine_ID?.id || '',
          inventoryLine: item?.M_InventoryLine_ID?.identifier || '',
          inventoryLineId: item?.M_InventoryLine_ID?.id || '',
          productionLine: item?.M_ProductionLine_ID?.identifier || '',
          productionLineId: item?.M_ProductionLine_ID?.id || '',
          projectIssue: item?.C_ProjectIssue_ID?.identifier || '',
          projectIssueId: item?.C_ProjectIssue_ID?.id || '',
          costCollector: item?.PP_Cost_Collector_ID?.identifier || '',
          costCollectorId: item?.PP_Cost_Collector_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/materials/products/'+entry.id+'/transaction', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      retrieve()
    }
  }
}

const save = async () => {
  if(form.value.id !== '') {
    const res = await $fetch('/api/materials/products/'+route.params.id+'/transaction', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        movementDate: form.value.movementDate,
        movementQty: form.value.movementQty,
        movementTypeId: form.value.movementTypeId,
        locatorId: form.value.locatorId,
        movementLineId: form.value.movementLineId,
        attributeSetInstanceId: form.value.attributeSetInstanceId,
        inOutLineId: form.value.inOutLineId,
        inventoryLineId: form.value.inventoryLineId,
        productionLineId: form.value.productionLineId,
        projectIssueId: form.value.projectIssueId,
        costCollectorId: form.value.costCollectorId,
      }
    })
    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/materials/products/'+route.params.id+'/transaction', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        movementDate: form.value.movementDate,
        movementQty: form.value.movementQty,
        movementTypeId: form.value.movementTypeId,
        locatorId: form.value.locatorId,
        movementLineId: form.value.movementLineId,
        attributeSetInstanceId: form.value.attributeSetInstanceId,
        inOutLineId: form.value.inOutLineId,
        inventoryLineId: form.value.inventoryLineId,
        productionLineId: form.value.productionLineId,
        projectIssueId: form.value.projectIssueId,
        costCollectorId: form.value.costCollectorId,
        productId: form.value.productId,
      }
    })
    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'
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Type</th>
            <th>Quantity</th>
            <th>Date</th>
            <th>Locator</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' ? 6 : 5" 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.movementType }}</td>
            <td>{{ entry.movementDate }}</td>
            <td>{{ entry.movementQty }}</td>
            <td>{{ entry.locator }}</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-info">
                  <i class="menu-icon tf-icons ti ti-eye"></i>
                </span>
                <!--<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">Product Transactions</h3>
            <div class="cursor-pointer" @click="closeDetailRecordModal">
              <span class="tf-icon ti ti-x ti-sm me-1"></span>
            </div>
          </div>
          <div class="modalBody mnh-450px">
            <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">Locator *</label>
                  <input v-if="form.id !== ''" type="text" :value="form.locator" class="input" readonly />
                  <ClientOnly v-else>
                    <SelectBox v-model="form.locatorId" :options="getOptions?.['locators']?.records || [{id: form.locatorId, Name: form.locator}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_locator', 'locators')" :loading="loading?.['locators'] ?? true" />
                  </ClientOnly>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Attribute Set Instance</label>
                      <input type="text" v-model="form.attributeSetInstance" class="input" readonly />
                      
                      <label class="label d-block mt-2">Movement Quantity *</label>
                      <input type="text" v-model="form.movementQty" class="input" readonly />

                      <label class="label d-block mt-2">Shipment/Receipt Line</label>
                      <input type="text" v-model="form.inOutLine" class="input" readonly />
                      
                      <label class="label d-block mt-2">Move Line</label>
                      <input type="text" v-model="form.movementLine" class="input" readonly />
                      
                      <label class="label d-block mt-2">Project Issue</label>
                      <input type="text" v-model="form.projectIssue" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Movement Type *</label>
                      <input type="text" v-model="form.movementType" class="input" readonly />
                      
                      <label class="label d-block mt-2">Movement Date *</label>
                      <input type="text" v-model="form.movementDate" class="input" readonly />
                      
                      <label class="label d-block mt-2">Phys.Inventory Line</label>
                      <input type="text" v-model="form.inventoryLine" class="input" readonly />
                      
                      <label class="label d-block mt-2">Production Line</label>
                      <input type="text" v-model="form.productionLine" class="input" readonly />
                      
                      <label class="label d-block mt-2">Manufacturing Cost Collector</label>
                      <input type="text" v-model="form.costCollector" class="input" readonly />
                    </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" disabled>
                      <label class="checkLabel" for="isActive">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">Close</button>
              <!--<button type="button" class="button" @click="save" :class="(form.accountingSchemaId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>-->
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>