<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 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 || '',
  help: props.modelValue.help || '',
  isActive: props.modelValue.isActive ?? true,
  lot: props.modelValue.lot || 0,
  isDisposed: props.modelValue.isDisposed ?? false,
  isInPosession: props.modelValue.isInPosession ?? false,
  useLifeYears: props.modelValue.useLifeYears || 0,
  assetDisposalDate: props.modelValue.assetDisposalDate || date.now(),
  isOwned: props.modelValue.isOwned ?? false,
  locationComment: props.modelValue.locationComment || '',
  isDepreciated: props.modelValue.isDepreciated ?? false,
  lifeUseUnits: props.modelValue.lifeUseUnits || 0,
  //processing: props.modelValue.processing ?? false,
  guaranteeDate: props.modelValue.guaranteeDate || date.now(),
  useLifeMonths: props.modelValue.useLifeMonths || 0,
  assetServiceDate: props.modelValue.assetServiceDate || date.now(),
  useUnits: props.modelValue.useUnits || 0,
  serNo: props.modelValue.serNo || '',
  isFullyDepreciated: props.modelValue.isFullyDepreciated ?? false,
  qty: props.modelValue.qty || 0,
  lastMaintenanceDate: props.modelValue.lastMaintenanceDate || date.now(),
  nextMaintenenceDate: props.modelValue.nextMaintenenceDate || date.now(),
  lastMaintenanceUnit: props.modelValue.lastMaintenanceUnit || 0,
  nextMaintenenceUnit: props.modelValue.nextMaintenenceUnit || 0,
  lastMaintenanceNote: props.modelValue.lastMaintenanceNote || '',
  assetCreateDate: props.modelValue.assetCreateDate || date.now(),
  assetRevalDate: props.modelValue.assetRevalDate || date.now(),
  qtyCurrent: props.modelValue.qtyCurrent || 0,
  qtyOriginal: props.modelValue.qtyOriginal || 0,
  processed: props.modelValue.processed ?? false,
  assetActivationDate: props.modelValue.assetActivationDate || date.now(),
  inventoryNo: props.modelValue.inventoryNo || '',
  assetType: props.modelValue.assetType || 'MFX',
  manufacturedYear: props.modelValue.manufacturedYear || 1900,
  user: props.modelValue.user || '',
  userId: props.modelValue.userId || '',
  product: props.modelValue.product || '',
  productId: props.modelValue.productId || '',
  location: props.modelValue.location || '',
  locationId: props.modelValue.locationId || '',
  assetGroup: props.modelValue.assetGroup || '',
  assetGroupId: props.modelValue.assetGroupId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  partnerLocation: props.modelValue.partnerLocation || '',
  partnerLocationId: props.modelValue.partnerLocationId || '',
  attributeSetInstance: props.modelValue.attributeSetInstance || '',
  attributeSetInstanceId: props.modelValue.attributeSetInstanceId || '',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  parentAsset: props.modelValue.parentAsset || '',
  parentAssetId: props.modelValue.parentAssetId || '',
  assetStatus: props.modelValue.assetStatus || 'New',
  assetStatusId: props.modelValue.assetStatusId || 'NW',
  assetAction: props.modelValue.assetAction || '',
  assetActionId: props.modelValue.assetActionId || '',
  activity: props.modelValue.activity || '',
  activityId: props.modelValue.activityId || '',
  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">
              <label class="label d-block">Inventory No</label>
              <input type="text" v-model="form.inventoryNo" class="input" @keyup="save" />
            </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">Comment/Help</label>
          <textarea v-model="form.help" class="input" @keyup="save"></textarea>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Asset Group *</label>
              <ClientOnly>
                <SelectBox v-model="form.assetGroupId" :options="getOptions?.['asset_groups']?.records || [{id: form.assetGroupId, Name: form.assetGroup}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/a_asset_group', 'asset_groups')" @change="save" :loading="loading?.['asset_groups'] ?? true" />
              </ClientOnly>

              <label class="label d-block mt-2">Serial No</label>
              <input type="text" v-model="form.serNo" class="input" @keyup="save" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Product *</label>
              <ClientOnly>
                <SelectBox v-model="form.productId" :options="getOptions?.['products']?.records || [{id: form.productId, Name: form.product}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'products')" @change="save" :loading="loading?.['products'] ?? true" />
              </ClientOnly>

              <label class="label d-block mt-2">Attribute Set Instance</label>
              <input type="text" :value="form.attributeSetInstance" class="input" readonly />

              <label class="label d-block mt-2">Manufactured Year</label>
              <input type="text" v-model="form.manufacturedYear" class="input" @keyup="save" />
            </div>
          </div>

          <label class="label d-block">Lot No</label>
          <input type="text" v-model="form.lot" class="input" @keyup="save" />

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">In Service Date</label>
              <DatePicker v-model="form.assetServiceDate" @handler="save" />

              <label class="label d-block mt-2">Create Date</label>
              <DatePicker v-model="form.assetCreateDate" @handler="save" />

              <label class="label d-block mt-2">Project</label>
              <ClientOnly>
                <SelectBox v-model="form.projectId" :options="getOptions?.['projects']?.records || [{id: form.projectId, Name: form.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_project', 'projects')" @change="save" :loading="loading?.['projects'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Guarantee Date</label>
              <DatePicker v-model="form.guaranteeDate" @handler="save" />

              <label class="label d-block mt-2">Revaluation Date</label>
              <DatePicker v-model="form.assetRevalDate" @handler="save" />

              <label class="label d-block mt-2">Activity</label>
              <ClientOnly>
                <SelectBox v-model="form.activityId" :options="getOptions?.['activities']?.records || [{id: form.activityId, Name: form.activity}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_activity', 'activities')" @change="save" :loading="loading?.['activities'] ?? true" />
              </ClientOnly>
            </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>
            </div>
            <div class="column is-half">
              <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')" :loading="loading?.['users'] ?? true" @change="save" />
              </ClientOnly>

              <label class="label d-block mt-2">Address</label>
              <input type="text" class="input" readonly />
            </div>
          </div>

          <label class="label d-block mt-2">Location comment</label>
          <input type="text" v-model="form.locationComment" class="input" @keyup="save" />

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Last Maintenance</label>
              <DatePicker v-model="form.lastMaintenanceDate" @handler="save" />

              <label class="label d-block mt-2">Last Unit</label>
              <input type="text" v-model="form.lastMaintenanceUnit" class="input" @keyup="save" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Next Maintenance</label>
              <DatePicker v-model="form.nextMaintenenceDate" @handler="save" />

              <label class="label d-block mt-2">Next Unit</label>
              <input type="text" v-model="form.nextMaintenenceUnit" class="input" @keyup="save" />
            </div>
          </div>

          <label class="label d-block mt-2">Last Note</label>
          <input type="text" v-model="form.lastMaintenanceNote" class="input" @keyup="save" />

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Asset Status</label>
              <select v-model="form.assetStatusId" class="select" disabled @change="save">
                <option value="NW">New</option>
                <option value="CO">Completed</option>
                <option value="DR">Drafted</option>
                <option value="VO">Void</option>
              </select>
            </div>
            <div v-if="form.isDisposed" class="column is-half">
              <label class="label d-block mt-2">Asset Disposal Date</label>
              <DatePicker v-model="form.assetDisposalDate" @handler="save" />
            </div>
            <div v-else class="column is-half">
              <label class="label d-block mt-2">Activation Date</label>
              <DatePicker v-model="form.assetActivationDate" @handler="save" />
            </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.isDisposed" class="checkInput" id="isDisposed" :checked="form.isDisposed" @change="save">
              <label class="checkLabel" for="isDisposed">Disposed</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isOwned" class="checkInput" id="isOwned" :checked="form.isOwned" @change="save">
              <label class="checkLabel" for="isOwned">Owned</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isDepreciate" class="checkInput" id="isDepreciated" :checked="form.isDepreciated" @change="save">
              <label class="checkLabel" for="isDepreciated">Depreciated</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isFullyDepreciated" class="checkInput" id="isFullyDepreciated" :checked="form.isFullyDepreciated" @change="save">
              <label class="checkLabel" for="isFullyDepreciated">Fully Depreciated</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.isInPosession" class="checkInput" id="isInPosession" :checked="form.isInPosession" @change="save">
              <label class="checkLabel" for="isInPosession">In Posession</label>
            </div>
          </div>
        </div>
      </div>

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