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

const windowFrom = useWindowFrom()

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

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

const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_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 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 === 'users' && res?.records?.[0]) {
      form.value.userId = String(res.records[0].id || '')
      form.value.user = res.records[0].Name || ''
    }
  }
  loading.value[key] = false
}

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 || '',
  requestAmt: props.modelValue.requestAmt || 0,
  summary: props.modelValue.summary || '',
  isEscalated: props.modelValue.isEscalated ?? false,
  isEMailWhenDue: props.modelValue.isEMailWhenDue ?? false,
  dateLastAction: props.modelValue.dateLastAction || date.now('date'),
  processed: props.modelValue.processed ?? false,
  isSelfService: props.modelValue.isSelfService ?? false,
  isInvoiced: props.modelValue.isInvoiced ?? false,
  qtySpent: props.modelValue.qtySpent || 0,
  qtyInvoiced: props.modelValue.qtyInvoiced || 0,
  priority: props.modelValue.priority || '',
  priorityId: props.modelValue.priorityId || '',
  dueType: props.modelValue.dueType || '',
  dueTypeId: props.modelValue.dueTypeId || '',
  salesRep: props.modelValue.salesRep || user.value?.Name || '',
  salesRepId: props.modelValue.salesRepId || user.value?.id || userId.value || '',
  partner: props.modelValue.partner || '',
  partnerId: props.modelValue.partnerId || '',
  user: props.modelValue.user || '',
  userId: props.modelValue.userId || '',
  nextAction: props.modelValue.nextAction || '',
  nextActionId: props.modelValue.nextActionId || '',
  requestType: props.modelValue.requestType || '',
  requestTypeId: props.modelValue.requestTypeId || '',
  group: props.modelValue.group || '',
  groupId: props.modelValue.groupId || '',
  category: props.modelValue.category || '',
  categoryId: props.modelValue.categoryId || '',
  status: props.modelValue.status || '',
  statusId: props.modelValue.statusId || '',
  resolution: props.modelValue.resolution || '',
  resolutionId: props.modelValue.resolutionId || '',
  priorityUser: props.modelValue.priorityUser || '',
  priorityUserId: props.modelValue.priorityUserId || '',
  confidentialType: props.modelValue.confidentialType || '',
  confidentialTypeId: props.modelValue.confidentialTypeId || '',
  confidentialTypeEntry: props.modelValue.confidentialTypeEntry || '',
  confidentialTypeEntryId: props.modelValue.confidentialTypeEntryId || '',
  role: props.modelValue.role || '',
  roleId: props.modelValue.roleId || '',
  dateNextAction: props.modelValue.dateNextAction || date.now(''),
  standardResponse: props.modelValue.standardResponse || '',
  standardResponseId: props.modelValue.standardResponseId || '',
  mailText: props.modelValue.mailText || '',
  mailTextId: props.modelValue.mailTextId || '',
  result: props.modelValue.result || '',
  lastResult: props.modelValue.lastResult || '',
  taskStatusId: props.modelValue.taskStatusId || '',
  qtyPlan: props.modelValue.qtyPlan || '',
  startTime: props.modelValue.startTime || date.now(''),
  startDate: props.modelValue.startDate || date.now(''),
  endTime: props.modelValue.endTime || date.now(''),
  endDate: props.modelValue.endDate || date.now(''),
  processing: props.modelValue.processing ?? false,
  asset: props.modelValue.asset || '',
  assetId: props.modelValue.assetId || '',
  project: props.modelValue.project || '',
  projectId: props.modelValue.projectId || '',
  order: props.modelValue.order || '',
  orderId: props.modelValue.orderId || '',
  invoice: props.modelValue.invoice || '',
  invoiceId: props.modelValue.invoiceId || '',
  payment: props.modelValue.payment || '',
  paymentId: props.modelValue.paymentId || '',
  inOut: props.modelValue.inOut || '',
  inOutId: props.modelValue.inOutId || '',
  product: props.modelValue.product || '',
  productId: props.modelValue.productId || '',
  productSpent: props.modelValue.productSpent || '',
  productSpentId: props.modelValue.productSpentId || '',
  rma: props.modelValue.rma || '',
  rmaId: props.modelValue.rmaId || '',
  campaign: props.modelValue.campaign || '',
  campaignId: props.modelValue.campaignId || '',
  alert: {
    status: props.modelValue.alert.status || '',
    message: props.modelValue.alert.message || '',
    processing: props.modelValue.alert.processing ?? false,
  }
})

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

watch(() => props.modelValue, () => {
  form.value = props.modelValue
  
  if(form.value.partnerId !== '' && windowFrom.value === 'partners') {
    populateByPartner('', {id: form.value.partnerId, Name: form.value.partner})
  }
})

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" />-->

      <template v-if="tab === 'basic'">
        <div class="columns is-desktop">
          <div class="column is-two-thirds">
            <div class="columns is-desktop">
              <div class="column is-one-third">
                <div class="legend">
                  <label class="label">Document No</label>
                  <input type="text" v-model="form.documentNo" class="input" @keyup="save" />
                </div>

                <div class="legend mt-2">
                  <label class="label">Group</label>
                  <ClientOnly>
                    <SelectBox v-model="form.groupId" :options="getOptions?.['request_groups']?.records || [{id: form.groupId, Name: form.group}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_group', 'request_groups')" :loading="loading?.['request_groups'] ?? true" @change="save" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Status</label>
                  <ClientOnly>
                    <SelectBox v-model="form.statusId" :options="getOptions?.['request_status']?.records || [{id: form.statusId, Name: form.status}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_status', 'request_status')" :loading="loading?.['request_status'] ?? true" @change="save" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">User Importance</label>
                  <select v-model="form.priorityUserId" class="select" @change="save">
                    <option value=""></option>
                    <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-one-third">
                <div class="legend">
                  <label class="label">Due Type *</label>
                  <select v-model="form.dueTypeId" class="select" @change="save">
                    <option value="5">Due</option>
                    <option value="3">Overdue</option>
                    <option value="7">Scheduled</option>
                  </select>
                </div>

                <div class="legend mt-2">
                  <label class="label">Category</label>
                  <ClientOnly>
                    <SelectBox v-model="form.categoryId" :options="getOptions?.['request_categories']?.records || [{id: form.categoryId, Name: form.category}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_category', 'request_categories')" :loading="loading?.['request_categories'] ?? true" @change="save" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Resolution</label>
                  <ClientOnly>
                    <SelectBox v-model="form.resolutionId" :options="getOptions?.['request_resolutions']?.records || [{id: form.resolutionId, Name: form.resolution}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_resolution', 'request_resolutions')" :loading="loading?.['request_resolutions'] ?? true" @change="save" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Confidentiality *</label>
                  <select v-model="form.confidentialTypeId" class="select" @change="save">
                    <option value="I">Internal</option>
                    <option value="C">Partner Confidential</option>
                    <option value="A">Public Information</option>
                  </select>
                </div>
              </div>
              <div class="column is-one-third">
                <div class="legend">
                  <label class="label">Request Type *</label>
                  <ClientOnly>
                    <SelectBox v-model="form.requestTypeId" :options="getOptions?.['request_types']?.records || [{id: form.requestTypeId, Name: form.requestType}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_requesttype', 'request_types')" :loading="loading?.['request_types'] ?? true" @change="save" />
                  </ClientOnly>
                </div>

                <div class="legend mt-2">
                  <label class="label">Related Request</label>
                  <input type="text" class="input" readonly />
                </div>

                <div class="legend mt-2">
                  <label class="label">Priority *</label>
                  <select v-model="form.priorityId" class="select" @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>

            <div class="legend mt-2">
              <label class="label">Summary *</label>
              <textarea v-model="form.summary" class="input" @keyup="save"></textarea>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Organization *</label>
              <input v-if="form.id !== ''" 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; save();}" :loading="loading?.['orgs'] ?? true" />
            </div>

            <div class="legend mt-2">
              <label class="label">Tenant *</label>
              <input type="text" :value="form.client || clientName" class="input" readonly />
            </div>

            <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.isActive" class="checkInput" id="isActive" :checked="form.isActive" :disabled="form.id === ''" @change="save">
                <label class="checkLabel" for="isActive">Active</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isInvoiced" class="checkInput" id="isInvoiced" :checked="form.isInvoiced" @change="save">
                <label class="checkLabel" for="isInvoiced">Invoiced</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isEscalated" class="checkInput" id="isEscalated" :checked="form.isEscalated" @change="save">
                <label class="checkLabel" for="isEscalated">Escalated</label>
              </div>
              <div class="check">
                <input type="checkbox" v-model="form.isSelfService" class="checkInput" id="isSelfService" :checked="form.isSelfService" @change="save">
                <label class="checkLabel" for="isSelfService">Self Service</label>
              </div>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'action'">
        <div class="columns is-desktop">
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">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')" :loading="loading?.['sales_reps'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Entry Confidentiality *</label>
              <select v-model="form.confidentialTypeEntryId" class="select" @change="save">
                <option value="I">Internal</option>
                <option value="C">Partner Confidential</option>
                <option value="A">Public Information</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">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')" :loading="loading?.['activities'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Quantity Used</label>
              <input type="text" v-model="form.qtySpent" class="input" @keyup="save" />
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Role</label>
              <ClientOnly>
                <SelectBox v-model="form.roleId" :options="getOptions?.['roles']?.records || [{id: form.roleId, Name: form.role}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/ad_role', 'roles')" :loading="loading?.['roles'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Standard Response</label>
              <ClientOnly>
                <SelectBox v-model="form.standardResponseId" :options="getOptions?.['standard_responses']?.records || [{id: form.standardResponseId, Name: form.standardResponse}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_standardresponse', 'standard_responses')" :loading="loading?.['standard_responses'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Task Status</label>
              <select v-model="form.taskStatusId" class="select" @change="save">
                <option value="0">0% Not Started</option>
                <option value="2">20% Started</option>
                <option value="4">40% Busy</option>
                <option value="6">60% Good Progress</option>
                <option value="8">80% Nearly Done</option>
                <option value="9">90% Finishing</option>
                <option value="A">95% Almost Done</option>
                <option value="C">99% Cleaning up</option>
                <option value="D">100% Complete</option>
              </select>
            </div>

            <div class="legend mt-2">
              <label class="label">Quantity Plan</label>
              <input type="text" v-model="form.qtyPlan" class="input" @keyup="save" />
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Date Next Action</label>
              <DateTimePicker v-model="form.dateNextAction" @handler="save()" />
            </div>

            <div class="legend mt-2">
              <label class="label">Mail Template</label>
              <ClientOnly>
                <SelectBox v-model="form.mailTextId" :options="getOptions?.['mail_texts']?.records || [{id: form.mailTextId, Name: form.mailText}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/r_mailtext', 'mail_texts')" :loading="loading?.['mail_texts'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Product Used</label>
              <ClientOnly>
                <SelectBox v-model="form.productSpentId" :options="getOptions?.['product_spents']?.records || [{id: form.productSpentId, Name: form.productSpent}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_product', 'product_spents')" :loading="loading?.['product_spents'] ?? true" @change="save" />
              </ClientOnly>
            </div>
          </div>
        </div>

        <div class="columns is-desktop">
          <div class="column is-half">
            <div class="legend mt-2">
              <label class="label">Start Time</label>
              <DateTimePicker v-model="form.startTime" @handler="save()" />
            </div>

            <div class="legend mt-2">
              <label class="label">Start Date</label>
              <DateTimePicker v-model="form.startDate" @handler="save()" />
            </div>
          </div>
          <div class="column is-half">
            <div class="legend mt-2">
              <label class="label">End Time</label>
              <DateTimePicker v-model="form.endTime" @handler="save()" />
            </div>

            <div class="legend mt-2">
              <label class="label">End Date</label>
              <DateTimePicker v-model="form.endDate" @handler="save()" />
            </div>
          </div>
        </div>
        
        <div class="legend mt-2">
          <label class="label">Result</label>
          <textarea v-model="form.result" class="input" @keyup="save"></textarea>
        </div>
      </template>
      <template v-else-if="tab === 'reference'">
        <div class="columns is-desktop">
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">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('models/c_bpartner', 'partners')" :loading="loading?.['partners'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Asset</label>
              <ClientOnly>
                <SelectBox v-model="form.assetId" :options="getOptions?.['assets']?.records || [{id: form.assetId, Name: form.asset}]" prop="Name" dataprop="id" datatype="string" :size="5" @click="setOptions('models/a_asset', 'assets')" :loading="loading?.['assets'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">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" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">RMA</label>
              <ClientOnly>
                <SelectBox v-model="form.rmaId" :options="getOptions?.['rma']?.records || [{id: form.rmaId, DocumentNo: form.rma}]" prop="DocumentNo" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_rma', 'rma')" :loading="loading?.['rma'] ?? true" @change="save" />
              </ClientOnly>
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">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>
            </div>

            <div class="legend mt-2">
              <label class="label">Order</label>
              <ClientOnly>
                <SelectBox v-model="form.orderId" :options="getOptions?.['orders']?.records || [{id: form.orderId, DocumentNo: form.order}]" prop="DocumentNo" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_order', 'orders')" :loading="loading?.['orders'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Payment</label>
              <ClientOnly>
                <SelectBox v-model="form.paymentId" :options="getOptions?.['payments']?.records || [{id: form.paymentId, DocumentNo: form.payment}]" prop="DocumentNo" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_payment', 'payments')" :loading="loading?.['payments'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Request Amount *</label>
              <input type="text" v-model="form.requestAmt" class="input" @keyup="save" />
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">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" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Invoice</label>
              <ClientOnly>
                <SelectBox v-model="form.invoiceId" :options="getOptions?.['invoices']?.records || [{id: form.invoiceId, DocumentNo: form.invoice}]" prop="DocumentNo" dataprop="id" datatype="string" :size="5" @click="setOptions('models/c_invoice', 'invoices')" :loading="loading?.['invoices'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">Shipment/Receipt</label>
              <ClientOnly>
                <SelectBox v-model="form.inOutId" :options="getOptions?.['in_outs']?.records || [{id: form.inOutId, DocumentNo: form.inOut}]" prop="DocumentNo" dataprop="id" datatype="string" :size="5" @click="setOptions('models/m_inout', 'in_outs')" :loading="loading?.['in_outs'] ?? true" @change="save" />
              </ClientOnly>
            </div>

            <div class="legend mt-2">
              <label class="label">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" @change="save" />
              </ClientOnly>
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="tab === 'history'">
        <div class="columns is-desktop">
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Table</label>
              <input type="text" class="input" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Last Result</label>
              <input type="text" class="input" :value="form.lastResult" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Updated</label>
              <input type="text" class="input" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Request Invoice</label>
              <input type="text" class="input" readonly />
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Date Last Action</label>
              <input type="text" :value="form.dateLastAction" class="input" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Created</label>
              <input type="text" class="input" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Updated By</label>
              <input type="text" class="input" readonly />
            </div>
          </div>
          <div class="column is-one-third">
            <div class="legend">
              <label class="label">Last Alert</label>
              <input type="text" class="input" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Created By</label>
              <input type="text" class="input" readonly />
            </div>

            <div class="legend mt-2">
              <label class="label">Change Request</label>
              <input type="text" class="input" readonly />
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>