<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 organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
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: organizations.value?.[0]?.id || props.info?.organization || '',
  organizationId: organizations.value?.[0]?.name || props.info?.organizationId || organizationId.value || '',
  product: props.info?.name || '',
  productId: props.info?.id || '',
  attributeSetInstance: props.info?.attributeSetInstance || '',
  attributeSetInstanceId: props.info?.attributeSetInstanceId || '',
  isActive: true,
  description: '',
  currentCostPrice: 0,
  futureCostPrice: 0,
  cumulatedAmt: 0,
  cumulatedQty: 0,
  percent: 0,
  processed: false,
  currentQty: 0,
  currentCostPriceLL: 0,
  futureCostPriceLL: 0,
  isCostFrozen: false,
  costType: '',
  costTypeId: '',
  acctSchema: '',
  acctSchemaId: '',
  costElement: '',
  costElementId: '',
  costingMethod: '',
  costingMethodId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = organizations.value?.[0]?.id || props.info?.organization || ''
  form.value.organizationId = organizations.value?.[0]?.name || props.info?.organizationId || organizationId.value || ''
  form.value.product = props.info?.name || ''
  form.value.productId = props.info?.id || ''
  form.value.attributeSetInstance = props.info?.attributeSetInstance || ''
  form.value.attributeSetInstanceId = props.info?.attributeSetInstanceId || ''
})

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 || '',
    attributeSetInstance: props.info?.attributeSetInstance || '',
    attributeSetInstanceId: props.info?.attributeSetInstanceId || '',
    isActive: true,
    description: '',
    currentCostPrice: 0,
    futureCostPrice: 0,
    cumulatedAmt: 0,
    cumulatedQty: 0,
    percent: 0,
    processed: false,
    currentQty: 0,
    currentCostPriceLL: 0,
    futureCostPriceLL: 0,
    isCostFrozen: false,
    costType: '',
    costTypeId: '',
    acctSchema: '',
    acctSchemaId: '',
    costElement: '',
    costElementId: '',
    costingMethod: '',
    costingMethodId: '',
    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+'/cost', {
      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 || '',
          isActive: item?.IsActive ?? true,
          description: item?.Description || '',
          currentCostPrice: item?.CurrentCostPrice || 0,
          futureCostPrice: item?.FutureCostPrice || 0,
          cumulatedAmt: item?.CumulatedAmt || 0,
          cumulatedQty: item?.CumulatedQty || 0,
          percent: item?.Percent || 0,
          processed: item?.Processed ?? false,
          currentQty: item?.CurrentQty || 0,
          currentCostPriceLL: item?.CurrentCostPriceLL || 0,
          futureCostPriceLL: item?.FutureCostPriceLL || 0,
          isCostFrozen: item?.IsCostFrozen ?? false,
          costType: item?.M_CostType_ID?.identifier || '',
          costTypeId: item?.M_CostType_ID?.id || '',
          acctSchema: item?.C_AcctSchema_ID?.identifier || '',
          acctSchemaId: item?.C_AcctSchema_ID?.id || '',
          costElement: item?.M_CostElement_ID?.identifier || '',
          costElementId: item?.M_CostElement_ID?.id || '',
          costingMethod: item?.CostingMethod?.identifier || '',
          costingMethodId: item?.CostingMethod?.id || '',
          attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
          attributeSetInstanceId: item?.M_AttributeSetInstance_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+'/cost', {
      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+'/cost', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        description: form.value.description,
        currentCostPrice: form.value.currentCostPrice,
        futureCostPrice: form.value.futureCostPrice,
        cumulatedAmt: form.value.cumulatedAmt,
        cumulatedQty: form.value.cumulatedQty,
        percent: form.value.percent,
        processed: form.value.processed,
        currentQty: form.value.currentQty,
        currentCostPriceLL: form.value.currentCostPriceLL,
        futureCostPriceLL: form.value.futureCostPriceLL,
        isCostFrozen: form.value.isCostFrozen,
        costTypeId: form.value.costTypeId,
        acctSchemaId: form.value.acctSchemaId,
        costElementId: form.value.costElementId,
        costingMethodId: form.value.costingMethodId,
        attributeSetInstanceId: form.value.attributeSetInstanceId,
      }
    })
    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+'/cost', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        isActive: form.value.isActive,
        description: form.value.description,
        currentCostPrice: form.value.currentCostPrice,
        futureCostPrice: form.value.futureCostPrice,
        cumulatedAmt: form.value.cumulatedAmt,
        cumulatedQty: form.value.cumulatedQty,
        percent: form.value.percent,
        processed: form.value.processed,
        currentQty: form.value.currentQty,
        currentCostPriceLL: form.value.currentCostPriceLL,
        futureCostPriceLL: form.value.futureCostPriceLL,
        isCostFrozen: form.value.isCostFrozen,
        costTypeId: form.value.costTypeId,
        acctSchemaId: form.value.acctSchemaId,
        costElementId: form.value.costElementId,
        costingMethodId: form.value.costingMethodId,
        attributeSetInstanceId: form.value.attributeSetInstanceId,
        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>Accounting Schema</th>
            <th>Cost Type</th>
            <th>Cost Element</th>
            <th>Current Cost</th>
            <th>Future Cost</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.acctSchema }}</td>
            <td>{{ entry.costType }}</td>
            <td>{{ entry.costElement }}</td>
            <td>{{ entry.currentCostPrice }}</td>
            <td>{{ entry.futureCostPrice }}</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">Product Costs</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">Accounting Schema *</label>
                      <template v-if="form.id !== ''">
                        <input type="text" :value="form.acctSchema" class="input" readonly />
                      </template>
                      <ClientOnly v-else>
                        <SelectBox v-model="form.acctSchemaId" :options="getOptions?.['acct_schemas']?.records || [{id: form.acctSchemaId, Name: form.acctSchema}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_acctschema', 'acct_schemas')" :loading="loading?.['acct_schemas'] ?? true" />
                      </ClientOnly>

                      <label class="label d-block mt-2">Cost Element *</label>
                      <template v-if="form.id !== ''">
                        <input type="text" :value="form.costElement" class="input" readonly />
                      </template>
                      <ClientOnly v-else>
                        <SelectBox v-model="form.costElementId" :options="getOptions?.['cost_elements']?.records || [{id: form.costElementId, Name: form.costElement}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_costelement', 'cost_elements')" :loading="loading?.['cost_elements'] ?? true" />
                      </ClientOnly>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block">Cost Type *</label>
                      <template v-if="form.id !== ''">
                        <input type="text" :value="form.costType" class="input" readonly />
                      </template>
                      <ClientOnly v-else>
                        <SelectBox v-model="form.costTypeId" :options="getOptions?.['cost_types']?.records || [{id: form.costTypeId, Name: form.costType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_costtype', 'cost_types')" :loading="loading?.['cost_types'] ?? true" />
                      </ClientOnly>

                      <!--<label class="label d-block">Cost Method</label>
                      <select v-model="form.bomUseId" class="select">
                        <option>Engineering</option>
                        <option>Manufacturing</option>
                        <option value="A">Master</option>
                        <option>Planning</option>
                        <option>Quality</option>
                      </select>-->
                    </div>
                  </div>

                  <label class="label d-block mt-2">Description</label>
                  <textarea v-model="form.description" class="input"></textarea>

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Current Cost Price *</label>
                      <input type="text" v-model="form.currentCostPrice" class="input" :readonly="form.id !== ''" />

                      <template v-if="form.id !== ''">
                        <label class="label d-block mt-2">Future Cost Price *</label>
                        <input type="text" v-model="form.futureCostPrice" class="input" />
                      </template>

                      <template v-else>
                        <label class="label d-block mt-2">Percent</label>
                        <input type="text" v-model="form.percent" class="input" />
                      </template>
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Current Cost Price Lower Level *</label>
                      <input type="text" v-model="form.currentCostPriceLL" class="input" readonly />
                      
                      <template v-if="form.id !== ''">
                        <label class="label d-block mt-2">Future Cost Price Lower Level</label>
                        <input type="text" v-model="form.futureCostPriceLL" class="input" readonly />
                      </template>
                    </div>
                  </div>

                  <label class="label d-block mt-2">Current Quantity</label>
                  <input type="text" v-model="form.currentQty" class="input" readonly />

                  <div class="columns">
                    <div class="column is-half">
                      <label class="label d-block mt-2">Accumulated Amt</label>
                      <input type="text" v-model="form.cumulatedAmt" class="input" readonly />
                    </div>
                    <div class="column is-half">
                      <label class="label d-block mt-2">Accumulated Qty</label>
                      <input type="text" v-model="form.cumulatedQty" class="input" readonly />
                    </div>
                  </div>
                </div>
                <div class="column is-one-third">
                  <label class="label d-block">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">Tenant *</label>
                  <input type="text" :value="form.client" class="input" readonly />-->

                  <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 v-if="form.id !== ''" class="check">
                      <input type="checkbox" v-model="form.isCostFrozen" class="checkInput" id="isCostFrozen" :checked="form.isCostFrozen" disabled>
                      <label class="checkLabel" for="isCostFrozen">Cost Frozen</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.acctSchemaId === '' || form.costTypeId === '' || form.costElementId === '' || form.currentCostPrice === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </Teleport>
</template>