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

const props = defineProps({
  modelValue: Object,
  tab: String
})

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
//const warehouses = useCookie('logship_warehouses')
//const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_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 || '',
  documentNo: props.modelValue.documentNo || '',
  movementDate: props.modelValue.movementDate || date.now('date'),
  approvalAmt: props.modelValue.approvalAmt || 0,
  chargeAmt: props.modelValue.chargeAmt || 0,
  freightAmt: props.modelValue.freightAmt || 0,
  description: props.modelValue.description || '',
  poReference: props.modelValue.poReference || '',
  isActive: props.modelValue.isActive ?? true,
  isApproved: props.modelValue.isApproved ?? false,
  warehouse: props.modelValue.warehouse || '',
  warehouseId: props.modelValue.warehouseId || '',
  warehouseTo: props.modelValue.warehouseTo || '',
  warehouseToId: props.modelValue.warehouseToId || '',
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || '',
  shipper: props.modelValue.shipper || '',
  shipperId: props.modelValue.shipperId || '',
  salesRep: props.modelValue.salesRep || user.value?.Name || '',
  salesRepId: props.modelValue.salesRepId || user.value?.id || userId.value || '',
  user: props.modelValue.user || '',
  userId: props.modelValue.userId || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  partnerLocation: props.modelValue.partnerLocation || '',
  partnerLocationId: props.modelValue.partnerLocationId || '',
  freightCostRule: props.modelValue.freightCostRule || '',
  freightCostRuleId: props.modelValue.freightCostRuleId || '',
  priorityRule: props.modelValue.priorityRule || '',
  priorityRuleId: props.modelValue.priorityRuleId || '',
  deliveryRule: props.modelValue.deliveryRule || '',
  deliveryRuleId: props.modelValue.deliveryRuleId || '',
  deliveryViaRule: props.modelValue.deliveryViaRule || '',
  deliveryViaRuleId: props.modelValue.deliveryViaRuleId || '',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  docStatus: props.modelValue.docStatus || 'Draft',
  docStatusId: props.modelValue.docStatusId || 'DR',
  processed: props.modelValue.processed ?? false,
  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 === 'locations' && res?.records?.[0]) {
      form.value.partnerLocationId = String(res.records[0].id || '')
      form.value.partnerLocation = res.records[0].Name || ''
    }
    if(key === 'users' && res?.records?.[0]) {
      form.value.userId = String(res.records[0].id || '')
      form.value.user = res.records[0].Name || ''
    }
    if(key === 'from_warehouses' && res?.records?.[0]) {
      form.value.warehouseId = String(res.records[0].id || '')
      form.value.warehouse = res.records[0].Name || ''
    }
    if(key === 'locations' && form.value.partnerId && url !== 'partners/partners/'+form.value.partnerId+'/locations' && Number(res?.records?.length || 0) === 0) {
      setOptions('partners/partners/'+form.value.partnerId+'/locations', 'locations')
    }
  }
  loading.value[key] = false
}

const populateByPartner = (val, opt) => {
  form.value.partner = opt.Name || ''
  form.value.partnerId = opt.id || ''
  setOptions('partners/partners/'+opt.id+'/locations/ship', 'locations')
  setOptions('partners/partners/'+opt.id+'/users', 'users')
  //setOptions('partners/partners/'+opt.id+'/users/ship', 'users')
}

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="save">
    <div class="my-5 mx-5">
      <!--<AlertAction v-model='form.alert.status' :alert="form.alert" />-->

      <template v-if="tab === 'inventory'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="legend">
              <label class="label">Order Reference</label>
              <input type="text" v-model="form.poReference" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
            </div>

            <div class="columns is-desktop">
              <div class="column is-half">
                <div class="legend mt-2">
                  <label class="label">Document No</label>
                  <input type="text" v-model="form.documentNo" class="input" :readonly="form.docStatusId === 'CO'" @keyup="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Movement Date *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.movementDate" class="input" readonly />
                  <DatePicker v-else v-model="form.movementDate" @handler="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">From Warehouse</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.warehouse" class="input" readonly />
                  <ClientOnly v-else>
                    <!--<SelectBox v-model="form.warehouseId" :options="warehouses" @change="(val, opt) => {form.warehouse = opt.name; save();}" prop="name" dataprop="id" datatype="string" :size="5" />-->
                    <SelectBox v-model="form.warehouseId" :options="getOptions?.['from_warehouses']?.records || [{id: form.warehouseId, Name: form.warehouse}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="setOptions(`organizations/${form.organizationId}/warehouses${form.warehouseToId ? '?notWarehouse='+form.warehouseToId : ''}`, 'from_warehouses')" @change="(val, opt) => {form.warehouse = opt.name; save();}" :loading="loading?.['from_warehouses'] ?? true" />
                  </ClientOnly>
                </div>
              </div>
              <div class="column is-half">
                <div class="legend mt-2">
                  <label class="label">Sales Representative</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.salesRep" class="input" readonly />
                  <ClientOnly v-else>
                    <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 class="legend mt-2">
                  <label class="label">Document Type *</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.docType" class="input" readonly />
                  <ClientOnly v-else>
                    <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/MMM', 'doc_types')" @change="save" :loading="loading?.['doc_types'] ?? true" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">To Warehouse</label>
                  <input v-if="form.docStatusId === 'CO'" type="text" :value="form.warehouseTo" class="input" readonly />
                  <ClientOnly v-else>
                    <!--<SelectBox v-model="form.warehouseToId" :options="warehouses" @change="(val, opt) => {form.warehouseTo = opt.name; save();}" prop="name" dataprop="id" datatype="string" :size="5" />-->
                    <SelectBox v-model="form.warehouseToId" :options="getOptions?.['to_warehouses']?.records || [{id: form.warehouseToId, Name: form.warehouseTo}]" prop="Name" dataprop="id" datatype="string" :size="5" @load="setOptions(`organizations/${form.organizationId}/warehouses${form.warehouseId ? '?notWarehouse='+form.warehouseId : ''}`, 'to_warehouses')" @change="(val, opt) => {form.warehouseTo = opt.name; save();}" :loading="loading?.['to_warehouses'] ?? true" />
                  </ClientOnly>
                </div>
              </div>
            </div>

            <div class="legend mt-2">
              <label class="label">Description</label>
              <textarea v-model="form.description" class="input" :disabled="form.docStatusId === 'CO'" @keyup="save"></textarea>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Organization *</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.organization" class="input" readonly />
              <SelectBox v-else 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; setOptions(`organizations/${opt.id}/warehouses${form.warehouseToId ? '?notWarehouse='+form.warehouseToId : ''}`, 'from_warehouses'); form.warehouseTo = ''; form.warehouseToId = ''; save();}" :loading="loading?.['orgs'] ?? true" />
            </div>

            <div class="legend mt-2">
              <label class="label">Tenant *</label>
              <input type="text" class="input is-normal" :value="clientName" readonly />
            </div>

            <label class="label d-block mt-2 mb-2">Status</label>
            <div class="check">
              <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" :disabled="form.docStatusId === 'CO'" @change="save">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'delivery'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend">
              <label class="label">Business Partner</label>
              <input v-if="form.docStatusId === 'CO'" 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('partners/partners', 'partners')" :loading="loading?.['partners'] ?? true" @change="(val, opt) => {populateByPartner(val, opt); save();}" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Shipper</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.shipper" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.shipperId" :options="getOptions?.['shippers']?.records || [{id: form.projectId, Name: form.project}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_shipper', 'shippers')" @change="save" :loading="loading?.['shippers'] ?? true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Delivery Via</label>
              <select v-model="form.deliveryViaRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
                <option value="D">Delivery</option>
                <option value="P">Pickup</option>
                <option value="S">Shipper</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">Priority</label>
              <select v-model="form.priorityRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
                <option value="3">High</option>
                <option value="7">Low</option>
                <option value="5">Medium</option>
                <option value="9">Minor</option>
                <option value="1">Urgent</option>
              </select>
            </div>
          </div>
          <div class="column is-half">
            <div class="legend">
              <label class="label">Partner Location</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.partnerLocation" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.partnerLocationId" :options="getOptions?.['locations']?.records || [{id: form.partnerLocationId, Name: form.partnerLocation}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions((form.partnerId ? 'partners/partners/'+form.partnerId+'/locations/ship' : 'settings/locations'), 'locations')" @change="save" :loading="loading?.['locations'] ?? true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">User Contact</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.user" class="input" readonly />
              <ClientOnly v-else>
                <SelectBox v-model="form.userId" :options="getOptions?.['users']?.records || [{id: form.userId, Name: form.user}]" @click="setOptions((form.partnerId ? 'partners/partners/'+form.partnerId+'/users' : 'models/ad_user'), 'users')" @change="save" prop="Name" dataprop="id" datatype="string" :size="5" :loading="loading?.['users'] ?? true" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Delivery Rule</label>
              <select v-model="form.deliveryRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
                <option value="R">After Payment</option>
                <option value="A">Availability</option>
                <option value="L">Complete Line</option>
                <option value="O">Complete Order</option>
                <option value="F">Force</option>
                <option value="M">Manual</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">Freight Cost Rule</label>
              <select v-model="form.freightCostRuleId" class="select" :disabled="form.docStatusId === 'CO'" @change="save">
                <option value="C">Calculated</option>
                <option value="U">Customer Account</option>
                <option value="F">Fix price</option>
                <option value="I">Freight included</option>
              </select>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend">
              <label class="label">Project</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.project" class="input" readonly />
              <ClientOnly v-else>
                <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('projects', 'projects')" @change="save" :loading="loading?.['projects'] ?? true" />
              </ClientOnly>
            </div>
          </div>
          <div class="column is-half">
            <div class="legend">
              <label class="label">Campaign</label>
              <input v-if="form.docStatusId === 'CO'" type="text" :value="form.campaign" class="input" readonly />
              <ClientOnly v-else>
                <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('marketings/campaigns', 'campaigns')" @change="save" :loading="loading?.['campaigns'] ?? true" />
              </ClientOnly>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'status'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="legend">
              <label class="label">Document Status *</label>
              <select v-model="form.docStatusId" class="select" disabled>
                <option value="CO">Completed</option>
                <option value="DR">Drafted</option>
                <option value="VO">Void</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">Approval Amount</label>
              <input type="text" :value="form.approvalAmt" class="input" readonly />
            </div>
            
            <div class="legend mt-2">
              <label class="label">Date Received</label>
              <input type="text" class="input" readonly />
            </div>
          </div>
          <div class="column is-one-third">
            <label class="label d-block mt-2">Status</label>
            <div class="d-flex flexDirection-column px-3 gap-5px">
              <div class="check">
                <input type="checkbox" v-model="form.isApproved" class="checkInput" id="isApproved" :checked="form.isApproved" disabled>
                <label class="checkLabel" for="isApproved">Approved</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isInTransit" class="checkInput" id="isInTransit" :checked="form.isInTransit" disabled>
                <label class="checkLabel" for="isInTransit">In Transit</label>
              </div>
            </div>
          </div>
        </div>
      </template>

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