<script setup>
import { string } from 'alga-js'
//import { DatePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'

const props = defineProps({
  modelValue: Object,
  lines: Array
})

const emit = defineEmits(['update:modelValue', 'update:lines', 'save'])

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 form = ref({
  id: props.modelValue.id || '',
  uid: props.modelValue?.uid || '',
  client: props.modelValue.client || '',
  clientId: props.modelValue.clientId || '',
  organization: props.modelValue.organization || organization.value?.Name || '',
  organizationId: props.modelValue.organizationId || organizationId.value || '',
  isActive: props.modelValue.isActive ?? true,
  documentNo: props.modelValue.documentNo || '',
  description: props.modelValue.description || '',
  isApproved: props.modelValue.isApproved ?? false,
  name: props.modelValue.name,
  processing: props.modelValue.processing ?? true,
  isSOTrx: false,
  processed: props.modelValue.processed ?? false,
  amt: props.modelValue.amt || 0,
  help: props.modelValue.help || '',
  inOut: props.modelValue.inOut || '',
  inOutId: props.modelValue.inOutId || '',
  order: props.modelValue.order || '',
  orderId: props.modelValue.orderId || '',
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || '',
  docStatus: props.modelValue.docStatus || '',
  docStatusId: props.modelValue.docStatusId || '',
  salesRep: props.modelValue.salesRep || '',
  salesRepId: props.modelValue.salesRepId || '',
  rmaType: props.modelValue.rmaType || '',
  rmaTypeId: props.modelValue.rmaTypeId || '',
  currency: props.modelValue.currency || '',
  currencyId: props.modelValue.currencyId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.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
    
    if(key === 'inouts' && Number(res?.records?.length) >= 1) {
      getOptions.value[key].records = res.records.map(item => {
        item.name = `${item.DocumentNo}_${item.C_BPartner_ID.identifier}_${item.DateAcct}`
        return item
      })
    }
  }
  loading.value[key] = false
}

const filterOptions = async (model, key, filter = '') => {
  if(filter) {
    await setOptions('filters/'+model+'/'+filter, key)
    filtering.value[key] = filter
  } else {
    if(!filtering.value?.[key] || filtering.value?.[key] === '') {
      await setOptions('models/'+model, key)
    }
  }
}

watch(() => props.modelValue, () => {
  form.value = props.modelValue
})

const vendorRmaLines = ref([])
const takeVendorRmaLines = async (opt) => {
  if(opt?.m_inoutline) {
    vendorRmaLines.value = opt.m_inoutline.map(item => {
      return {
        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 || '',
        rma: `${form.value.documentNo}_${form.value.dateAcct}` || '',
        rmaId: form.value.id || '',
        isActive: true,
        line: item?.Line || '',
        product: item?.M_Product_ID?.Name || '',
        productId: item?.M_Product_ID?.id || '',
        galleries: [],
        qty: 1,
        amt: 0,
        lineNetAmt: 0,
        processed: false,
        tax: '',
        taxId: '',
        inOutLine: `${item?.Line}_${item?.M_Product_ID?.Name}_${item?.QtyEntered}` || '',
        inOutLineId: item?.id || '',
        charge: '',
        chargeId: '',
        show: false,
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    }).sort((a, b) => Number(a.line) - Number(b.line))
    emit('update:lines', vendorRmaLines.value)
    
    const newEntries = []
    for(let item of vendorRmaLines.value) {
      const response = await $fetch(`/api/materials/products/${item.productId}`)
      if(response?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
        if(resp) {
          item.galleries = resp
        }
      }
      newEntries.push(item)
    }
    vendorRmaLines.value = newEntries
    emit('update:lines', vendorRmaLines.value)
  }
}

const handleInOut = (opt) => {
  form.value.partner = opt?.C_BPartner_ID?.identifier || ''
  form.value.partnerId = opt?.C_BPartner_ID?.id || ''
  form.value.salesRep = opt?.SalesRep_ID?.identifier || ''
  form.value.salesRepId = opt?.SalesRep_ID?.id || ''
  takeVendorRmaLines(opt)
}

const debounce = (func, timeout = 300) => {
  let timer;
  return (...args) => {
    clearTimeout(timer)
    timer = setTimeout(() => { func.apply(this, args); }, timeout)
  }
}

const save = debounce(() => {
  emit('update:modelValue', form.value)
  emit('save', form.value)
})
</script>

<template>
  <div @mouseleave.self="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      
      <div class="columns is-desktop">
        <div class="column is-two-thirds">
          <label class="label">Name *</label>
          <input type="text" v-model="form.name" class="input" @keyup="save" />

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Document Type *</label>
              <ClientOnly>
                <!--<SelectBox v-model="form.docTypeId" :options="getOptions?.['doc_types']?.records?.filter(i => Number(i.id) === 150) || [{id: form.docTypeId, Name: form.docType}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="filterOptions('c_doctype', 'doc_types', string.urlEncode(`isActive eq true AND DocBaseType eq 'POO' AND DocSubTypeSO eq 'RM' AND IsSOTrx eq false`))" @search="(val) => filterOptions('c_doctype', 'doc_types', string.urlEncode(`isActive eq true AND DocBaseType eq 'POO' AND DocSubTypeSO eq 'RM' AND IsSOTrx eq false AND contains(Name,'${val}')`))" :loading="loading?.['doc_types'] ?? true" @change="save" />-->
                <SelectBox v-model="form.docTypeId" :options="getOptions?.['doc_types']?.records || [{id: form.docTypeId, Name: form.docType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('types/VRM', 'doc_types')" @change="save" :loading="loading?.['doc_types'] ?? true" />
              </ClientOnly>
              
              <label class="label d-block mt-2">Material Receipt *</label>
              <ClientOnly>
                <SelectBox v-model="form.inOutId" :options="getOptions?.['inouts']?.records?.filter(i => i.IsSOTrx === false && i?.C_Order_ID) || [{id: form.inOutId, name: form.inOut}]" prop="name" dataprop="id" datatype="string" :size="5" @load="filterOptions('m_inout', 'inouts', string.urlEncode(`isActive eq true AND isSOTrx eq false&$expand=m_inoutline($expand=m_product_id)`))" @search="(val) => filterOptions('m_inout', 'inouts', string.urlEncode(`isActive eq true AND isSOTrx eq false AND contains(DocumentNo,'${val}')&$expand=m_inoutline($expand=m_product_id)`))" :loading="loading?.['inouts'] ?? true" @change="(val, opt) => {handleInOut(opt); save();}" />
              </ClientOnly>
              
              <label class="label d-block mt-2">Sales Representative *</label>
              <ClientOnly>
                <SelectBox v-model="form.salesRepId" :options="getOptions?.['sales_reps']?.records || [{id: form.salesRepId, Name: form.salesRep}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="filterOptions('ad_user', 'sales_reps', string.urlEncode(`isActive eq true`))" @search="(val) => filterOptions('ad_user', 'sales_reps', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['sales_reps'] ?? true" @change="save" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">RMA Type *</label>
              <ClientOnly>
                <SelectBox v-model="form.rmaTypeId" :options="getOptions?.['rma_types']?.records || [{id: form.rmaTypeId, Name: form.rmaType}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="filterOptions('m_rmatype', 'rma_types', string.urlEncode(`isActive eq true`))" @search="(val) => filterOptions('m_rmatype', 'rma_types', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['rma_types'] ?? true" @change="save" />
              </ClientOnly>

              <label class="label d-block mt-2">Business Partner</label>
              <input type="text" v-model="form.partner" class="input" readonly />
              <!--<ClientOnly>
                <SelectBox v-model="form.partnerId" :options="getOptions?.['partners']?.records || [{id: form.partnerId, Name: form.partner}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="filterOptions('c_bpartner', 'partners', string.urlEncode(`isActive eq true`))" @search="(val) => filterOptions('c_bpartner', 'partners', string.urlEncode(`isActive eq true AND contains(Name,'${val}')`))" :loading="loading?.['partners'] ?? true" @change="save" />
              </ClientOnly>-->
              
              <label class="label d-block mt-2">Amount</label>
              <input type="text" v-model="form.amt" class="input" readonly />
            </div>
          </div>
          
          <label class="label d-block mt-2">Description</label>
          <textarea v-model="form.description" class="input" @keyup="save"></textarea>
          
          <label class="label d-block mt-2">Comment/Help</label>
          <textarea v-model="form.help" class="input" @keyup="save"></textarea>

          <div class="columns is-desktop">
            <div class="column is-full">
              <label class="label d-block mt-2">Document Status</label>
              <select v-model="form.docStatusId" class="select" @change="save" disabled>
                <option value="CO">Completed</option>
                <option value="IP">In Progress</option>
                <option value="DR">Drafted</option>
                <option value="VO">Void</option>
              </select>
            </div>
          </div>

        </div>

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

          <label class="label d-block mt-2">Tenant *</label>
          <input type="text" :value="clientName" 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" @change="save">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isApproved" class="checkInput" id="isApproved" :checked="form.isApproved" @change="save">
              <label class="checkLabel" for="isApproved">Approved</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.processing" class="checkInput" id="processing" :checked="form.processing" @change="save">
              <label class="checkLabel" for="processing">Processing</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.processed" class="checkInput" id="processed" :checked="form.processed" @change="save">
              <label class="checkLabel" for="processed">Processed</label>
            </div>
          </div>

        </div>
      </div>

    </div>
  </div>
</template>