<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const url = useRequestURL()
const router = useRouter()
const route = useRoute()

const activeSave = useActiveSave()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

definePageMeta({
  middleware: ['auth', 'org']
})

//const clients = useCookie('logship_clients')
const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
//const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
//const warehouses = useCookie('logship_warehouses')
//const warehouse = useCookie('logship_warehouse')
//const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

const requestParam = ref({})
const window = (from) => {
  if(windowParam.value?.[from] && url.pathname.endsWith('windows/requests-requests-create')) {
    requestParam.value = windowParam.value?.[from] || {}
  }
  
  return requestParam.value
}

const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  isActive: true,
  documentNo: '',
  requestAmt: 0,
  summary: '',
  isEscalated: false,
  isEMailWhenDue: false,
  dateLastAction: date.now('date'),
  processed: false,
  isSelfService: false,
  isInvoiced: false,
  qtySpent: 0,
  qtyInvoiced: 0,
  priority: '',
  priorityId: '',
  dueType: '',
  dueTypeId: '',
  salesRep: user.value?.Name ?? '',
  salesRepId: user.value?.id ?? userId.value ?? '',
  partner: window('partners')?.data?.name || '',
  partnerId: window('partners')?.data?.id || '',
  user: '',
  userId: '',
  nextAction: '',
  nextActionId: '',
  requestType: '',
  requestTypeId: '',
  group: '',
  groupId: '',
  category: '',
  categoryId: '',
  status: '',
  statusId: '',
  resolution: '',
  resolutionId: '',
  priorityUser: '',
  priorityUserId: '',
  confidentialType: '',
  confidentialTypeId: '',
  confidentialTypeEntry: '',
  confidentialTypeEntryId: '',
  role: '',
  roleId: '',
  dateNextAction: date.now(''),
  standardResponse: '',
  standardResponseId: '',
  mailText: '',
  mailTextId: '',
  result: '',
  lastResult: '',
  taskStatusId: '',
  activityId: '',
  qtyPlan: 0,
  startTime: date.now(''),
  startDate: date.now(''),
  endTime: date.now(''),
  endDate: date.now(''),
  asset: '',
  assetId: '',
  project: '',
  projectId: '',
  order: '',
  orderId: '',
  invoice: '',
  invoiceId: '',
  payment: '',
  paymentId: '',
  inOut: '',
  inOutId: '',
  product: '',
  productId: '',
  productSpent: '',
  productSpentId: '',
  rma: '',
  rmaId: '',
  campaign: '',
  campaignId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    router.push(window('partners')?.path || '/requests/requests')
  }
}

const save = async (record) => {
  form.value = record
  
  if(form.value.dueTypeId !== '' && form.value.confidentialTypeEntryId !== '' && form.value.salesRepId !== '' && form.value.confidentialTypeId !== '' && form.value.requestTypeId !== '' && form.value.requestAmt !== '' && form.value.summary !== '' && form.value.priorityId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/requests/requests/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      requestAmt: form.value.requestAmt,
      summary: form.value.summary,
      isEscalated: form.value.isEscalated,
      isEMailWhenDue: form.value.isEMailWhenDue,
      dateLastAction: new Date(form.value.dateLastAction).toJSON().replace('.000Z', 'Z'),
      processed: form.value.processed,
      isSelfService: form.value.isSelfService,
      isInvoiced: form.value.isInvoiced,
      qtySpent: form.value.qtySpent,
      qtyInvoiced: form.value.qtyInvoiced,
      priorityId: form.value.priorityId,
      dueTypeId: form.value.dueTypeId,
      salesRepId: form.value.salesRepId,
      partnerId: form.value.partnerId,
      userId: form.value.userId,
      nextActionId: form.value.nextActionId,
      requestTypeId: form.value.requestTypeId,
      groupId: form.value.groupId,
      categoryId: form.value.categoryId,
      statusId: form.value.statusId,
      resolutionId: form.value.resolutionId,
      priorityUserId: form.value.priorityUserId,
      confidentialTypeId: form.value.confidentialTypeId,
      confidentialTypeEntryId: form.value.confidentialTypeEntryId,
      roleId: form.value.roleId,
      dateNextAction: new Date(form.value.dateNextAction).toJSON().replace('.000Z', 'Z'),
      standardResponseId: form.value.standardResponseId,
      mailTextId: form.value.mailTextId,
      result: form.value.result,
      lastResult: form.value.lastResult,
      taskStatusId: form.value.taskStatusId,
      activityId: form.value.activityId,
      qtyPlan: form.value.qtyPlan,
      startTime: new Date(form.value.startTime).toJSON().replace('.000Z', 'Z'),
      startDate: new Date(form.value.startDate).toJSON().replace('.000Z', 'Z'),
      endTime: new Date(form.value.endTime).toJSON().replace('.000Z', 'Z'),
      endDate: new Date(form.value.endDate).toJSON().replace('.000Z', 'Z'),
      assetId: form.value.assetId,
      projectId: form.value.projectId,
      orderId: form.value.orderId,
      invoiceId: form.value.invoiceId,
      paymentId: form.value.paymentId,
      inOutId: form.value.inOutId,
      productId: form.value.productId,
      productSpentId: form.value.productSpentId,
      rmaId: form.value.rmaId,
      campaignId: form.value.campaignId,
    }
  })

  if(Number(res.status) === 200) {
    /*for(let [key, items] of Object.entries(entries)) {
      for(let entry of items) {
        if(entry.id) {
          let body = {}
          if(key === 'update_notification') {
            body = {
              id: entry.id,
              userId: entry.userId,
              isActive: entry.isActive,
              isSelfService: entry.isSelfService
            }
          }

          await $fetch(`/api/requests/requests/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'update_notification') {
            body = {
              organizationId: record.organizationId,
              requestTypeId: res.id,
              userId: entry.userId,
              isActive: entry.isActive,
              isSelfService: entry.isSelfService
            }
          }

          await $fetch(`/api/requests/requests/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    windowFrom.value = ''
    windowParam.value = {}
    form.value.alert.processing = false
    activeSave.value = false

    if(saveType === 'preview') {
      router.push('/requests/requests/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/requests/requests/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Home'},
  { link: '/requests/requests', text: 'Requests'},
  { link: '#', text: 'Add Request', active: true}
]))

const tab = ref(route.query?.tab || 'basic')
const tabs = computed(() => ([
  { value: 'basic', text: 'Basic'},
  { value: 'action', text: 'Action'},
  { value: 'reference', text: 'Reference'},
  { value: 'history', text: 'History'}
]))

const openOtherTab = () => {
  if(tab.value === 'basic') {
    tab.value = 'action'
  } else if(tab.value === 'action') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'history'
  }
}
</script>

<template>
  <Head>
    <Title>Add Request</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.dueTypeId === '' || form.confidentialTypeEntryId === '' || form.salesRepId === '' || form.confidentialTypeId === '' || form.requestTypeId === '' || form.requestAmt === '' || form.summary === '' || form.priorityId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <button v-if="tab !== 'status'" type="button" @click="openOtherTab" class="button">Next</button>
      </div>
      <div>
        <div class="d-flex gap-10px">
          <button v-if="activeSave" type="button" @click="activeSave = false; back();" class="button">
            <span class="tf-icon ti ti-square-x ti-xs me-1 color-inherit"></span> Abort
          </button>
          <button type="button" @click="back" class="button">
            <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
          </button>
        </div>
      </div>
    </div>
    
    <div class="banner">
      <div class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <RequestsRequestForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <RequestsRequestDetailRecord action="create" :info="form" tab="request_history" />
      </div>
    </div>
  </NuxtLayout>
</template>