<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 boMActive = useBoMActive()
const boM = useBoM()

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 || '',
  isActive: true,
  isCritical: false,
  isQtyPercentage: false,
  assay: 0,
  forecast: 0,
  leadTimeOffset: 0,
  line: 0,
  qtyBOM: 1,
  qtyBatch: 0,
  scrap: 0,
  validFrom: date.now('date'),
  costAllocationPerc: 0,
  product: props.info?.name || '',
  productId: props.info?.id || '',
  productBOM: boM.value?.name ?? '',
  productBOMId: boM.value?.id ?? '',
  issueMethod: '',
  issueMethodId: '',
  componentType: 'Component',
  componentTypeId: 'CO',
  uom: '',
  uomId: '',
  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 takeBoM = () => {
  form.value.productBOM = boM.value?.name ?? ''
  form.value.productBOMId = boM.value?.id ?? ''
}
onMounted(takeBoM)
watch(boM, takeBoM, {deep: true})

const showDetailRecordModal = ref(boMActive.value ?? false)
//const showAddressModal = ref(false)

watch(boMActive, () => {
  showDetailRecordModal.value = boMActive.value ?? false
})

const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false
  boMActive.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    isActive: true,
    isCritical: false,
    isQtyPercentage: false,
    assay: 0,
    forecast: 0,
    leadTimeOffset: 0,
    line: 0,
    qtyBOM: 1,
    qtyBatch: 0,
    scrap: 0,
    validFrom: date.now('date'),
    costAllocationPerc: 0,
    product: props.info?.name || '',
    productId: props.info?.id || '',
    productBOM: boM.value?.name ?? '',
    productBOMId: boM.value?.id ?? '',
    issueMethod: '',
    issueMethodId: '',
    componentType: 'Component',
    componentTypeId: 'CO',
    uom: '',
    uomId: '',
    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.records
    
    if(key === 'product_boms' && Number(res?.records?.length ?? 0) >= 1) {
      getOptions.value[key] = res.records.map(item => {
        item.product_bom = item.M_Product_ID.identifier
        item.product_bom_id = item.M_Product_ID.id
        return item
      })
    }
  }
  loading.value[key] = false
}

const retrieve = async () => {
  if(route.params?.id) {
    const res = await $fetch('/api/materials/products/'+route.params.id+'/bom-components', {
      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 || '',
          isActive: item?.IsActive ?? true,
          isCritical: item?.IsCritical ?? false,
          isQtyPercentage: item?.IsQtyPercentage ?? false,
          assay: item?.Assay ?? 0,
          forecast: item?.Forecast ?? 0,
          leadTimeOffset: item?.LeadTimeOffset ?? 0,
          line: item?.Line ?? 0,
          qtyBOM: item?.QtyBOM ?? 1,
          qtyBatch: item?.QtyBatch ?? 0,
          scrap: item?.Scrap ?? 0,
          validFrom: item?.ValidFrom ?? date.now('date'),
          costAllocationPerc: item?.CostAllocationPerc ?? 0,
          product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
          productId: item?.M_Product_ID?.id || '',
          productBOM: item?.PP_Product_BOM_ID?.identifier || '',
          productBOMId: item?.PP_Product_BOM_ID?.id || '',
          issueMethod: item?.IssueMethod?.identifier || '',
          issueMethodId: item?.IssueMethod?.id || '',
          componentType: item?.ComponentType?.identifier || 'Component',
          componentTypeId: item?.ComponentType?.id || 'CO',
          uom: item?.C_UOM_ID?.identifier || '',
          uomId: item?.C_UOM_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+'/bom-components', {
      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+'/bom-components', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        isCritical: form.value.isCritical,
        isQtyPercentage: form.value.isQtyPercentage,
        assay: form.value.assay,
        forecast: form.value.forecast,
        leadTimeOffset: form.value.leadTimeOffset,
        line: form.value.line,
        qtyBOM: form.value.qtyBOM,
        qtyBatch: form.value.qtyBatch,
        scrap: form.value.scrap,
        validFrom: form.value.validFrom,
        costAllocationPerc: form.value.costAllocationPerc,
        //productId: form.value.productId,
        //productBOMId: form.value.productBOMId,
        issueMethodId: form.value.issueMethodId,
        componentTypeId: form.value.componentTypeId,
        uomId: form.value.uomId,
      }
    })
    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+'/bom-components', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        isCritical: form.value.isCritical,
        isQtyPercentage: form.value.isQtyPercentage,
        assay: form.value.assay,
        forecast: form.value.forecast,
        leadTimeOffset: form.value.leadTimeOffset,
        line: form.value.line,
        qtyBOM: form.value.qtyBOM,
        qtyBatch: form.value.qtyBatch,
        scrap: form.value.scrap,
        validFrom: form.value.validFrom,
        costAllocationPerc: form.value.costAllocationPerc,
        productId: form.value.productId,
        productBOMId: form.value.productBOMId,
        issueMethodId: form.value.issueMethodId,
        componentTypeId: form.value.componentTypeId,
        uomId: form.value.uomId,
      }
    })
    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>UOM</th>
            <th>Component Type</th>
            <th>Product</th>
            <th>Product BOM</th>
            <th>Valid From</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.uom }}</td>
            <td>{{ entry.componentType }}</td>
            <td>{{ entry.product }}</td>
            <td>{{ entry.productBOM }}</td>
            <td>{{ entry.validFrom }}</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">Bill of Material Component</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">Line No *</label>
                      <input type="text" v-model="form.lineNo" class="input" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">Product BOM *</label>
                      <ClientOnly>
                        <SelectBox v-model="form.productBOMId" :options="getOptions?.['product_boms'] || [{product_bom_id: form.productBOMId, product_bom: form.productBOM}]" prop="product_bom" dataprop="product_bom_id" datatype="string" :size="5" @click="setOptions('models/pp_product_bom', 'product_boms')" :loading="loading?.['product_boms'] ?? true" />
                      </ClientOnly>
                    </div>  
                  </div>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Product</label>
                      <ClientOnly>
                        <SelectBox v-model="form.productId" :options="getOptions?.['products'] || [{id: form.productId, Name: form.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'products')" :loading="loading?.['products'] ?? true" />
                      </ClientOnly>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Component Type</label>
                      <select v-model="form.componentTypeId" class="select">
                        <option value="BY">By-Product</option>
                        <option value="CP">Co-Product</option>
                        <option value="CO">Component</option>
                        <option value="OP">Option</option>
                        <option value="PK">Packing</option>
                        <option value="PH">Phantom</option>
                        <option value="PL">Planning</option>
                        <option value="TO">Tools</option>
                        <option value="VA">Variant</option>
                      </select>
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">UOM</label>
                      <ClientOnly>
                        <SelectBox v-model="form.uomId" :options="getOptions?.['uoms'] || [{id: form.uomId, Name: form.uom}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_uom', 'uoms')" :loading="loading?.['uoms'] ?? true" />
                      </ClientOnly>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Issue Method</label>
                      <select v-model="form.issueMethodId" class="select">
                        <option value="0">Issue</option>
                      </select>
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Valid From</label>
                      <DatePicker v-model="form.validFrom" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Cost Allocation Percentage</label>
                      <input type="text" v-model="form.costAllocationPerc" class="input" />
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-one-third">
                      <label class="label d-block mt-2">Assay</label>
                      <input type="text" v-model="form.assay" class="input" />
                    </div>
                    <div class="column is-one-third">
                      <label class="label d-block mt-2">Forecast</label>
                      <input type="text" v-model="form.forecast" class="input" />
                    </div>
                    <div class="column is-one-third">
                      <label class="label d-block mt-2">Lead Time Offset</label>
                      <input type="text" v-model="form.leadTimeOffset" class="input" />
                    </div>
                  </div>

                  <div class="columns">
                    <div class="column is-one-third">
                      <label class="label d-block mt-2">Qty BOM</label>
                      <input type="text" v-model="form.qtyBOM" class="input" />
                    </div>
                    <div class="column is-one-third">
                      <label class="label d-block mt-2">Qty Batch</label>
                      <input type="text" v-model="form.qtyBatch" class="input" />
                    </div>
                    <div class="column is-one-third">
                      <label class="label d-block mt-2">Scrap</label>
                      <input type="text" v-model="form.scrap" class="input" />
                    </div>
                  </div>
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">Status</label>
                  <div class="d-flex flexDirection-column gap-10px">
                    <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.isCritical" class="checkInput" id="isCritical" :checked="form.isCritical">
                      <label class="checkLabel" for="isCritical">Critical</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.isQtyPercentage" class="checkInput" id="isQtyPercentage" :checked="form.isQtyPercentage">
                      <label class="checkLabel" for="isQtyPercentage">Quantity Percentage</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.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>