<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,
  vendorProductNo: '',
  vendorCategory: '',
  priceEffective: date.now('date'),
  manufacturer: '',
  discontinued: false,
  priceList: 0,
  priceLastPO: 0,
  orderMin: 1,
  orderPack: 1,
  pricePO: 0,
  isCurrentVendor: false,
  qualityRating: 0,
  deliveryTimePromised: 0,
  deliveryTimeActual: 0,
  costPerOrder: 0,
  priceLastInv: 0,
  royaltyAmt: 0,
  partner: '',
  partnerId: '',
  uom: '',
  uomId: '',
  currency: '',
  currencyId: '',
  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,
    vendorProductNo: '',
    vendorCategory: '',
    priceEffective: date.now('date'),
    manufacturer: '',
    discontinued: false,
    priceList: 0,
    priceLastPO: 0,
    orderMin: 1,
    orderPack: 1,
    pricePO: 0,
    isCurrentVendor: false,
    qualityRating: 0,
    deliveryTimePromised: 0,
    deliveryTimeActual: 0,
    costPerOrder: 0,
    priceLastInv: 0,
    royaltyAmt: 0,
    upc: '',
    partner: '',
    partnerId: '',
    uom: '',
    uomId: '',
    currency: '',
    currencyId: '',
    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+'/purchasing', {
      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,
          vendorProductNo: item?.VendorProductNo || '',
          vendorCategory: item?.VendorCategory || '',
          priceEffective: item?.PriceEffective || date.now('date'),
          manufacturer: item?.Manufacturer || '',
          discontinued: item?.Discontinued ?? false,
          priceList: item?.PriceList || 0,
          priceLastPO: item?.PriceLastPO || 0,
          orderMin: item?.Order_Min || 1,
          orderPack: item?.Order_Pack || 1,
          pricePO: item?.PricePO || 0,
          isCurrentVendor: item?.IsCurrentVendor ?? true,
          qualityRating: item?.QualityRating || 0,
          deliveryTimePromised: item?.DeliveryTime_Promised || 0,
          deliveryTimeActual: item?.DeliveryTime_Actual || 0,
          costPerOrder: item?.CostPerOrder || 0,
          priceLastInv: item?.PriceLastInv || 0,
          royaltyAmt: item?.RoyaltyAmt || 0,
          upc: item?.upc || '',
          partner: item?.C_BPartner_ID?.identifier || '',
          partnerId: item?.C_BPartner_ID?.id || '',
          uom: item?.C_UOM_ID?.identifier || '',
          uomId: item?.C_UOM_ID?.id || '',
          currency: item?.C_Currency_ID?.identifier || '',
          currencyId: item?.C_Currency_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+'/purchasing', {
      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+'/purchasing', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        vendorProductNo: form.value.vendorProductNo,
        vendorCategory: form.value.vendorCategory,
        priceEffective: form.value.priceEffective,
        manufacturer: form.value.manufacturer,
        discontinued: form.value.discontinued,
        priceList: form.value.priceList,
        priceLastPO: form.value.priceLastPO,
        orderMin: form.value.orderMin,
        orderPack: form.value.orderPack,
        pricePO: form.value.pricePO,
        isCurrentVendor: form.value.isCurrentVendor,
        qualityRating: form.value.qualityRating,
        deliveryTimePromised: form.value.deliveryTimePromised,
        deliveryTimeActual: form.value.deliveryTimeActual,
        costPerOrder: form.value.costPerOrder,
        priceLastInv: form.value.priceLastInv,
        royaltyAmt: form.value.royaltyAmt,
        upc: form.value.upc,
        partnerId: form.value.partnerId,
        uomId: form.value.uomId,
        currencyId: form.value.currencyId,
      }
    })
    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+'/purchasing', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        vendorProductNo: form.value.vendorProductNo,
        vendorCategory: form.value.vendorCategory,
        priceEffective: form.value.priceEffective,
        manufacturer: form.value.manufacturer,
        discontinued: form.value.discontinued,
        priceList: form.value.priceList,
        priceLastPO: form.value.priceLastPO,
        orderMin: form.value.orderMin,
        orderPack: form.value.orderPack,
        pricePO: form.value.pricePO,
        isCurrentVendor: form.value.isCurrentVendor,
        qualityRating: form.value.qualityRating,
        deliveryTimePromised: form.value.deliveryTimePromised,
        deliveryTimeActual: form.value.deliveryTimeActual,
        costPerOrder: form.value.costPerOrder,
        priceLastInv: form.value.priceLastInv,
        royaltyAmt: form.value.royaltyAmt,
        upc: form.value.upc,
        partnerId: form.value.partnerId,
        uomId: form.value.uomId,
        currencyId: form.value.currencyId,
        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>Partner</th>
            <th>Quality</th>
            <th>Currency</th>
            <th>List Price</th>
            <th>Royalty</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.partner }}</td>
            <td>{{ entry.qualityRating }}</td>
            <td>{{ entry.currency }}</td>
            <td>{{ entry.listPrice }}</td>
            <td>{{ entry.royaltyAmt }}</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">Purchasing Product</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">
                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block">Partner *</label>
                      <input v-if="form.id !== ''" type="text" :value="form.partner" class="input" readonly />
                      <ClientOnly v-else>
                        <SelectBox v-model="form.partnerId" :options="getOptions?.['partners']?.records || [{id: form.partnerId, Name: form.partner}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_bpartner', 'partners')" :loading="loading?.['partners'] ?? true" />
                      </ClientOnly>
                      
                      <label class="label d-block mt-2">Currency</label>
                      <ClientOnly>
                        <SelectBox v-model="form.currencyId" :options="getOptions?.['currencies']?.records || [{id: form.currencyId, ISO_Code: form.currency}]" prop="ISO_Code" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_currency', 'currencies')" :loading="loading?.['currencies'] ?? true" />
                      </ClientOnly>

                      <label class="label d-block mt-2">List Price</label>
                      <input type="text" v-model="form.priceList" class="input" />

                      <label class="label d-block mt-2">PO Price</label>
                      <input type="text" v-model="form.pricePO" class="input" />

                      <label class="label d-block mt-2">Last PO Price</label>
                      <input type="text" :value="form.priceLastPO" class="input" readonly />
                      
                      <label class="label d-block mt-2">Minimum Order Qty</label>
                      <input type="text" v-model="form.orderMin" class="input" />

                      <label class="label d-block mt-2">Promised Delivery Time</label>
                      <input type="text" v-model="form.deliveryTimePromised" class="input" />

                      <label class="label d-block mt-2">Cost per Order</label>
                      <input type="text" v-model="form.costPerOrder" class="input" />

                      <label class="label d-block mt-2">Partner Product Key *</label>
                      <input type="text" v-model="form.vendorProductNo" class="input" />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">Quality Rating</label>
                      <input type="text" v-model="form.qualityRating" class="input" />

                      <label class="label d-block mt-2">UPC/EAN</label>
                      <input type="text" v-model="form.upc" class="input" />

                      <label class="label d-block mt-2">Price effective</label>
                      <DatePicker v-model="form.priceEffective" />

                      <label class="label d-block mt-2">Royalty Amount</label>
                      <input type="text" v-model="form.royaltyAmt" class="input" />

                      <label class="label d-block mt-2">Last Invoice Price</label>
                      <input type="text" :value="form.priceLastInv" class="input" readonly />
                      
                      <label class="label d-block mt-2">Order Pack Qty</label>
                      <input type="text" v-model="form.orderPack" class="input" />

                      <label class="label d-block mt-2">Actual Delivery Time</label>
                      <input type="text" :value="form.deliveryTimeActual" class="input" readonly />
                      
                      <label class="label d-block mt-2">Partner Category</label>
                      <input type="text" v-model="form.vendorCategory" class="input" />

                      <label class="label d-block mt-2">Manufacturer</label>
                      <input type="text" v-model="form.manufacturer" class="input" />
                    </div>
                  </div>

                </div>
                <div class="column is-one-third">
                  <label class="label d-block">UOM</label>
                  <ClientOnly>
                    <SelectBox v-model="form.uomId" :options="getOptions?.['uoms']?.records || [{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>

                  <label class="label d-block mt-2">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.isCurrentVendor" class="checkInput" id="isCurrentVendor" :checked="form.isCurrentVendor">
                      <label class="checkLabel" for="isCurrentVendor">Current Vendor</label>
                    </div>
                    <div class="check">
                      <input type="checkbox" v-model="form.discontinued" class="checkInput" id="discontinued" :checked="form.discontinued">
                      <label class="checkLabel" for="discontinued">Discontinued</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.partnerId === '' || form.vendorProductNo === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>