<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 || '',
  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 || '',
  description: props.modelValue.description || '',
  isActive: props.modelValue.isActive ?? true,
  movementDate: props.modelValue.movementDate || date.now('date'),
  processed: props.modelValue.processed ?? false,
  processedOn: props.modelValue.processedOn || 0,
  documentNo: props.modelValue.documentNo || '',
  productionQty: props.modelValue.productionQty || 0,
  datePromised: props.modelValue.datePromised || date.now('date'),
  isComplete: props.modelValue.isComplete ?? false,
  isUseProductionPlan: props.modelValue.isUseProductionPlan ?? false,
  product: props.modelValue.product || '',
  productId: props.modelValue.productId || '',
  isCreated: props.modelValue.isCreated || 'No',
  isCreatedId: props.modelValue.isCreatedId || 'N',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  locator: props.modelValue.locator || '',
  locatorId: props.modelValue.locatorId || '',
  docStatus: props.modelValue.docStatus || 'Draft',
  docStatusId: props.modelValue.docStatusId || 'DR',
  docType: props.modelValue.docType || '',
  docTypeId: props.modelValue.docTypeId || '',
  processing: props.modelValue.processing ?? false,
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || ''
  }
})

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 save = (saveType = '') => {
  form.value.processing = true
  emit('update:modelValue', form.value)
  if(props.modelValue.id) {
    emit('save', form.value, props.modelValue.id, saveType)
  } else {
    emit('save', form.value, '', saveType)
  }
}
</script>

<template>
  <form @submit.prevent="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">Document Type *</label>
              <ClientOnly>
                <SelectBox v-model="form.docTypeId" :options="getOptions?.['document_types']?.records || [{id: form.docTypeId, Name: form.docType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_doctype', 'document_types')" :loading="loading?.['document_types'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block">Document Number</label>
              <input type="text" v-model="form.documentNo" class="input" />
            </div>
          </div>

          <label class="label d-block mt-2">Name</label>
          <input type="text" v-model="form.name" class="input" />

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

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block mt-2">Date Promised</label>
              <DatePicker v-model="form.datePromised" />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Movement Date *</label>
              <DatePicker v-model="form.movementDate" />
            </div>
          </div>

          <div class="columns is-desktop">
            <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')" :loading="loading?.['products'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">Locator *</label>
              <ClientOnly>
                <SelectBox v-model="form.locatorId" :options="getOptions?.['locators']?.records || [{id: form.locatorId, Value: form.locator}]" prop="Value" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_locator', 'locators')" :loading="loading?.['locators'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Production Quantity *</label>
              <input type="text" v-model="form.productionQty" class="input" />
            </div>
            <div class="column is-half">
              <label class="label d-block">Records created *</label>
              <input type="text" :value="form.isCreated" class="input" readonly />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">BOM Formula</label>
              <input type="text" class="input" readonly />
            </div>
            <div class="column is-half">
              <div class="d-flex flexDirection-column gap-10px">
                <button type="button" class="button">Create/Update Production Lines</button>
                <button type="button" class="button">Document Action</button>
              </div>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <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')" :loading="loading?.['projects'] ?? true" />
              </ClientOnly>
            </div>
            <div class="column is-half">
              <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')" :loading="loading?.['campaigns'] ?? true" />
              </ClientOnly>
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Sales Order Line</label>
              <input type="text" class="input" readonly />
            </div>
            <div class="column is-half">
              <label class="label d-block">Business Partner</label>
              <input type="text" class="input" readonly />
            </div>
          </div>

          <div class="columns is-desktop">
            <div class="column is-half">
              <label class="label d-block">Shipment/Receipt Line</label>
              <input type="text" class="input" readonly />
            </div>
            <div class="column is-half">
              <label class="label d-block mt-2">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>

        </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">
              <label class="checkLabel" for="isActive">Active</label>
            </div>
            <div class="check">
              <input type="checkbox" v-model="form.processed" class="checkInput" id="processed" :checked="form.processed">
              <label class="checkLabel" for="processed">Processed</label>
            </div>
          </div>
        </div>
      </div>

    </div>
    <div class="m-3">
      <div class="d-flex gap-10px">
        <button type="submit" class="button" :class="(form.docTypeId === '' || form.productId === '' || form.locatorId === '' || form.productionQty === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit</button>
        <button type="button" @click="save('preview')" class="button" :class="(form.docTypeId === '' || form.productId === '' || form.locatorId === '' || form.productionQty === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Submit &amp; Preview</button>
        <button type="button" @click="save('changes')" class="button" :class="(form.docTypeId === '' || form.productId === '' || form.locatorId === '' || form.productionQty === '' || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save Changes</button>
      </div>
    </div>
  </form>
</template>