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

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()

const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

const isOpen = ref(false)

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

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  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: '',
  partnerId: '',
  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 retrieve = async () => {
  const res = await $fetch('/api/requests/requests/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      uid: res?.uid || '',
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      isActive: res?.IsActive ?? true,
      documentNo: res?.DocumentNo || '',
      requestAmt: res?.RequestAmt || 0,
      summary: res?.Summary || '',
      isEscalated: res?.IsEscalated ?? false,
      isEMailWhenDue: res?.IsEMailWhenDue ?? false,
      dateLastAction: res?.DateLastAction || date.now('date'),
      processed: res?.Processed ?? false,
      isSelfService: res?.IsSelfService ?? false,
      isInvoiced: res?.IsInvoiced ?? false,
      qtySpent: res?.QtySpent || 0,
      qtyInvoiced: res?.QtyInvoiced || 0,
      priority: res?.Priority?.identifier || '',
      priorityId: res?.Priority?.id || '',
      dueType: res?.DueType?.identifier || '',
      dueTypeId: res?.DueType?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_ID?.id || '',
      nextAction: res?.NextAction?.identifier || '',
      nextActionId: res?.NextAction?.id || '',
      requestType: res?.R_RequestType_ID?.identifier || '',
      requestTypeId: res?.R_RequestType_ID?.id || '',
      group: res?.R_Group_ID?.identifier || '',
      groupId: res?.R_Group_ID?.id || '',
      category: res?.R_Category_ID?.identifier || '',
      categoryId: res?.R_Category_ID?.id || '',
      status: res?.R_Status_ID?.identifier || '',
      statusId: res?.R_Status_ID?.id || '',
      resolution: res?.R_Resolution_ID?.identifier || '',
      resolutionId: res?.R_Resolution_ID?.id || '',
      priorityUser: res?.PriorityUser?.identifier || '',
      priorityUserId: res?.PriorityUser?.id || '',
      confidentialType: res?.ConfidentialType?.identifier || '',
      confidentialTypeId: res?.ConfidentialType?.id || '',
      confidentialTypeEntry: res?.ConfidentialTypeEntry?.identifier || '',
      confidentialTypeEntryId: res?.ConfidentialTypeEntry?.id || '',
      role: res?.AD_Role_ID?.identifier || '',
      roleId: res?.AD_Role_ID?.id || '',
      dateNextAction: date.now(''),
      standardResponse: res?.R_StandardResponse_ID?.identifier || '',
      standardResponseId: res?.R_StandardResponse_ID?.id || '',
      mailText: res?.R_MailText_ID?.identifier || '',
      mailTextId: res?.R_MailText_ID?.id || '',
      result: res?.Result || '',
      lastResult: res?.LastResult || '',
      taskStatusId: res?.TaskStatus?.id || '',
      activity: res?.C_Activity_ID?.identifier || '',
      activityId: res?.C_Activity_ID?.id || '',
      qtyPlan: res?.QtyPlan || 0,
      startTime: res?.StartTime || date.now(''),
      startDate: res?.StartDate || date.now(''),
      endTime: res?.EndTime || date.now(''),
      endDate: res?.EndDate || date.now(''),
      asset: res?.A_Asset_ID?.identifier || '',
      assetId: res?.A_Asset_ID?.id || '',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      invoice: res?.C_Invoice_ID?.identifier || '',
      invoiceId: res?.C_Invoice_ID?.id || '',
      payment: res?.C_Payment_ID?.identifier || '',
      paymentId: res?.C_Payment_ID?.id || '',
      inOut: res?.M_InOut_ID?.identifier || '',
      inOutId: res?.M_InOut_ID?.id || '',
      product: res?.M_Product_ID?.identifier || '',
      productId: res?.M_Product_ID?.id || '',
      productSpent: res?.M_ProductSpent_ID?.identifier || '',
      productSpentId: res?.M_ProductSpent_ID?.id || '',
      rma: res?.M_RMA_ID?.identifier || '',
      rmaId: res?.M_RMA_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false

    /*for(let record of ['update_notification']) {
      const response = await $fetch('/api/requests/requests/'+route.params.id+'/'+record.replaceAll('_', '-'), {
        headers: useRequestHeaders(['cookie'])
      })
      if(response) {
        let newData = []
        if(record === 'update_notification') {
          newData = response.records.map(item => {
            return {
              id: item.uid,
              user: item.AD_User_ID.identifier,
              userId: item.AD_User_ID.id,
              isActive: item.IsActive,
              isSelfService: item.IsSelfService,
            }
          })
        }

        detailRecord.value[record] = newData
      }
    }*/
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.documentNo == (lastRecord.value?.DocumentNo || '') &&
    form.value.requestAmt == (lastRecord.value?.RequestAmt || 0) &&
    form.value.summary == (lastRecord.value?.Summary || '') &&
    form.value.isEscalated == (lastRecord.value?.IsEscalated ?? false) &&
    form.value.isEMailWhenDue == (lastRecord.value?.IsEMailWhenDue ?? false) &&
    //form.value.dateLastAction == (lastRecord.value?.DateLastAction || date.now('date')) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.isInvoiced == (lastRecord.value?.IsInvoiced ?? false) &&
    form.value.qtySpent == (lastRecord.value?.QtySpent || 0) &&
    form.value.qtyInvoiced == (lastRecord.value?.QtyInvoiced || 0) &&
    form.value.priorityId == (lastRecord.value?.Priority?.id || '') &&
    form.value.dueTypeId == (lastRecord.value?.DueType?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.nextActionId == (lastRecord.value?.NextAction?.id || '') &&
    form.value.requestTypeId == (lastRecord.value?.R_RequestType_ID?.id || '') &&
    form.value.groupId == (lastRecord.value?.R_Group_ID?.id || '') &&
    form.value.categoryId == (lastRecord.value?.R_Category_ID?.id || '') &&
    form.value.statusId == (lastRecord.value?.R_Status_ID?.id || '') &&
    form.value.resolutionId == (lastRecord.value?.R_Resolution_ID?.id || '') &&
    form.value.priorityUserId == (lastRecord.value?.PriorityUser?.id || '') &&
    form.value.confidentialTypeId == (lastRecord.value?.ConfidentialType?.id || '') &&
    form.value.confidentialTypeEntryId == (lastRecord.value?.ConfidentialTypeEntry?.id || '') &&
    form.value.roleId == (lastRecord.value?.AD_Role_ID?.id || '') &&
    //form.value.dateNextAction === date.now('') &&
    form.value.standardResponseId == (lastRecord.value?.R_StandardResponse_ID?.id || '') &&
    form.value.mailTextId == (lastRecord.value?.R_MailText_ID?.id || '') &&
    form.value.result == (lastRecord.value?.Result || '') &&
    form.value.lastResult == (lastRecord.value?.LastResult || '') &&
    form.value.taskStatusId == (lastRecord.value?.TaskStatus?.id || '') &&
    form.value.activityId == (lastRecord.value?.C_Activity_ID?.id || '') &&
    form.value.qtyPlan == (lastRecord.value?.QtyPlan || 0) &&
    //form.value.startTime == (lastRecord.value?.StartTime || date.now('')) &&
    //form.value.startDate == (lastRecord.value?.StartDate || date.now('')) &&
    //form.value.endTime == (lastRecord.value?.EndTime || date.now('')) &&
    //form.value.endDate == (lastRecord.value?.EndDate || date.now('')) &&
    form.value.assetId == (lastRecord.value?.A_Asset_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.orderId == (lastRecord.value?.C_Order_ID?.id || '') &&
    form.value.invoiceId == (lastRecord.value?.C_Invoice_ID?.id || '') &&
    form.value.paymentId == (lastRecord.value?.C_Payment_ID?.id || '') &&
    form.value.inOutId == (lastRecord.value?.M_InOut_ID?.id || '') &&
    form.value.productId == (lastRecord.value?.M_Product_ID?.id || '') &&
    form.value.productSpentId == (lastRecord.value?.M_ProductSpent_ID?.id || '') &&
    form.value.rmaId == (lastRecord.value?.M_RMA_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/requests/requests/${route.params.id}/duplicate`)
}

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('/requests/requests')
  }
}

const save = async (record) => {
  form.value = record
  setNoEdit()
  if(!noEdit.value) {
    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/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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,
      product: form.value.product,
      productId: form.value.productId,
      productSpent: form.value.productSpent,
      productSpentId: form.value.productSpentId,
      rma: form.value.rma,
      rmaId: form.value.rmaId,
      campaign: form.value.campaign,
      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
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/requests/requests/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
    } 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 showAttachment = ref(false)

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

const data = ref(null)
const error = ref(null)
const pending = ref(false)
let groupedByUpdated = ref(null)

const fetchData = async () => {
  pending.value = true
  const { data: fetchedData, error: fetchError } = await useFetch('/api/changelog/' + route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })

  // console.log(fetchedData._value);

  groupedByUpdated = fetchedData._value.reduce((acc, item) => {
    const updatedKey = item.Updated;
    if (!acc[updatedKey]) {
      acc[updatedKey] = [];
    }
    acc[updatedKey].push(item);
    return acc;
  }, {});
  // console.log(groupedByUpdated);

  console.log('YOUNES')
  console.log(fetchedData)
  console.log(groupedByUpdated)
  // data.value = fetchedData.value
  data.value = groupedByUpdated
  error.value = fetchError.value
  pending.value = false
}

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>Edit 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 === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" class="button" :class="(form.dueTypeId === '' || form.confidentialTypeEntryId === '' || form.salesRepId === '' || form.confidentialTypeId === '' || form.requestTypeId === '' || form.requestAmt === '' || form.summary === '' || form.priorityId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" 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' : ''">Attachment</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</button>

          <UButton label="History" @click="isOpen = true;fetchData()" />

          <USlideover v-model="isOpen" :overlay="false">
            <div class="p-4 flex-1 scrollover historyslidein">
              <Placeholder class="h-full" />

              <div class="timeline">
                <header class="timeline-header">
                  <span class="tag is-medium is-primary">Start</span>
                </header>

                <div v-if="error">{{ error.message }}</div>
                <div v-else-if="pending">Loading...</div>
                {{data}}

                <div class="timeline-header">
                  <span class="tag is-medium is-primary">End</span>
                </div>
              </div>

            </div>
          </USlideover>

        </template>
      </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>
        <RequestsRequestDetailRecord action="edit" :info="form" tab="request_history" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="R_Request" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>