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

const props = defineProps({
  modelValue: Object
})

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouses = useCookie('warehouses')
const warehouseId = useCookie('warehouseId')

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 || '',
  name: props.modelValue.name || '',
  value: props.modelValue.value || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  note: props.modelValue.note || '',
  isSummary: props.modelValue.isSummary ?? false,
  isCommitment: props.modelValue.isCommitment ?? false,
  committedAmt: props.modelValue.committedAmt || 0,
  dateContract: props.modelValue.dateContract || date.now('date'),
  dateFinish: props.modelValue.dateFinish || date.now('date'),
  processed: props.modelValue.processed ?? false,
  plannedAmt: props.modelValue.plannedAmt || 0,
  plannedQty: props.modelValue.plannedQty || 0,
  plannedMarginAmt: props.modelValue.plannedMarginAmt || 0,
  invoicedAmt: props.modelValue.invoicedAmt || 0,
  invoicedQty: props.modelValue.invoicedQty || 0,
  projectBalanceAmt: props.modelValue.projectBalanceAmt || 0,
  committedQty: props.modelValue.committedQty || 0,
  isCommitCeiling: props.modelValue.isCommitCeiling ?? false,
  currency: props.modelValue.currency || '',
  currencyId: props.modelValue.currencyId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  partnerLocation: props.modelValue.partnerLocation || '',
  partnerLocationId: props.modelValue.partnerLocationId || '',
  salesRep: props.modelValue.salesRep || '',
  salesRepId: props.modelValue.salesRepId || '',
  priceListVersion: props.modelValue.priceListVersion || '',
  priceListVersionId: props.modelValue.priceListVersionId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  user: props.modelValue.user || '',
  userId: props.modelValue.userId || '',
  warehouse: props.modelValue.warehouse || '',
  warehouseId: props.modelValue.warehouseId || warehouseId.value || '',
  projectCategory: props.modelValue.projectCategory || '',
  projectCategoryId: props.modelValue.projectCategoryId || '',
  projInvoiceRule: props.modelValue.projInvoiceRule || '',
  projInvoiceRuleId: props.modelValue. projInvoiceRuleId || '',
  projectLineLevel: props.modelValue.projectLineLevel || '',
  projectLineLevelId: props.modelValue.projectLineLevelId || '',
  partnerSR: props.modelValue.partnerSR || '',
  partnerSRId: props.modelValue.partnerSRId || '',
  paymentTerm: props.modelValue.paymentTerm || '',
  paymentTermId: props.modelValue.paymentTermId || '',
  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) {
    if(key === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }
    
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

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

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">
          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Search Key</label>
              <input type="text" v-model="form.value" class="input" @keyup="save" />
            </div>
            <div class="column is-half" v-if="!form.isSummary">
              <label class="label d-block">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" @click="setOptions('models/ad_user', 'sales_reps')" @change="save" :loading="loading?.['sales_reps'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <label class="label d-block">Name *</label>
          <input type="text" v-model="form.name" class="input" @keyup="save" />

          <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">Note</label>
          <textarea v-model="form.note" class="input" @keyup="save"></textarea>

          <div v-if="!form.isSummary">
            <label class="label d-block mt-2">Line Level *</label>
            <select v-model="form.projectLineLevelId" class="select" @change="save">
              <option value="A">Phase</option>
              <option value="P">Project</option>
              <option value="T">Task</option>
            </select>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Contract Date</label>
                <DatePicker v-model="form.dateContract" @handler="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Finish Date</label>
                <DatePicker v-model="form.dateFinish" @handler="save" />
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Business Partner</label>
                <ClientOnly>
                  <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('partners/partners', 'partners')" :loading="loading?.['partners'] ?? true" @change="(val, opt) => {setOptions('partners/partners/'+opt.id+'/locations', 'locations'); save();}" />
                </ClientOnly>

                <label class="label d-block mt-2">Partner Location</label>
                <ClientOnly>
                  <SelectBox v-model="form.partnerLocationId" :options="getOptions?.['locations']?.records || [{id: form.partnerLocationId, Name: form.partnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" :loading="false" @change="save" />
                </ClientOnly>

                <label class="label d-block mt-2">Payment Term</label>
                <ClientOnly>
                  <SelectBox v-model="form.paymentTermId" :options="getOptions?.['payment_terms']?.records || [{id: form.paymentTermId, Name: form.paymentTerm}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_paymentterm', 'payment_terms')" @change="save" :loading="loading?.['payment_terms'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Warehouse</label>
                <ClientOnly>
                  <SelectBox v-model="form.warehouseId" :options="getOptions?.['warehouses']?.records || [{id: form.warehouseId, Name: form.warehouse}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_warehouse', 'warehouses')" @change="save" :loading="loading?.['warehouses'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Price List Version</label>
                <ClientOnly>
                  <SelectBox v-model="form.priceListVersionId" :options="getOptions?.['price_list_versions']?.records || [{id: form.priceListVersionId, Name: form.priceListVersion}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_pricelist_version', 'price_list_versions')" @change="save" :loading="loading?.['price_list_versions'] ?? true" />
                </ClientOnly>
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Agent or Partner Representative</label>
                <ClientOnly>
                  <SelectBox v-model="form.partnerSRId" :options="getOptions?.['partner_representatives']?.records || [{id: form.partnerSRId, Name: form.partnerSR}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('partners/partners', 'partner_representatives')" @change="save" :loading="loading?.['partner_representatives'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">User/Contact</label>
                <ClientOnly>
                  <SelectBox v-model="form.userId" :options="getOptions?.['users']?.records || [{id: form.userId, Name: form.user}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_user', 'users')" @change="save" :loading="loading?.['users'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Order Reference</label>
                <DatePicker v-model="form.poReference" @handler="save" />

                <label class="label d-block mt-2">Campaign</label>
                <ClientOnly>
                  <SelectBox v-model="form.campaignId" :options="getOptions?.['campaigns']?.records || [{id: form.campaignId, Name: form.campaign}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_campaign', 'campaigns')" @change="save" :loading="loading?.['campaigns'] ?? true" />
                </ClientOnly>

                <label class="label d-block mt-2">Currency *</label>
                <ClientOnly>
                  <SelectBox v-model="form.currencyId" :options="getOptions?.['currencies']?.records || [{id: form.currencyId, Name: form.currency}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_currency', 'currencies')" @change="save" :loading="loading?.['currencies'] ?? true" />
                </ClientOnly>
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Planned Amount *</label>
                <input type="text" v-model="form.plannedAmt" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Planned Margin *</label>
                <input type="text" v-model="form.plannedMarginAmt" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Committed Amount *</label>
                <input type="text" v-model="form.committedAmt" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Planned Quantity *</label>
                <input type="text" v-model="form.plannedQty" class="input" @keyup="save" />
                
                <label class="label d-block mt-2">Invoice Rule *</label>
                <select v-model="form.projInvoiceRuleId" class="select" @change="save">
                  <option value="C">Committed Amount</option>
                  <option value="-">None</option>
                  <option value="P">Product Quantity</option>
                  <option value="T">Time &amp; Material</option>
                  <option value="c">Time &amp; Material max Comitted</option>
                </select>
                
                <label class="label d-block mt-2">Committed Quantity *</label>
                <input type="text" v-model="form.committedQty" class="input" @keyup="save" />
              </div>
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <label class="label d-block mt-2">Invoiced Amount</label>
                <input type="text" v-model="form.invoicedAmt" class="input" readonly />
                
                <label class="label d-block mt-2">Project Balance</label>
                <input type="text" v-model="form.projectBalanceAmt" class="input" @keyup="save" />
              </div>
              <div class="column is-half">
                <label class="label d-block mt-2">Quantity Invoiced</label>
                <input type="text" v-model="form.invoicedQty" class="input" readonly />
              </div>
            </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="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.isSummary" class="checkInput" id="isSummary" :checked="form.isSummary" @change="save">
              <label class="checkLabel" for="isSummary">Summary Level</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isCommitment" class="checkInput" id="isCommitment" :checked="form.isCommitment" @change="save">
              <label class="checkLabel" for="isCommitment">Commitment</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isCommitCeiling" class="checkInput" id="isCommitCeiling" :checked="form.isCommitCeiling" @change="save">
              <label class="checkLabel" for="isCommitCeiling">Commit Ceiling</label>
            </div>
          </div>
        </div>
      </div>

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