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

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

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

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  isActive: true,
  name: '',
  description: '',
  value: '',
  isSummary: false,
  tenant: client.value?.Name || '',
  tenantId: clientId.value || '',
  replicationStrategy: '',
  replicationStrategyId: '',
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/admin/organizations/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      uid: res?.uid || '',
      isActive: res?.IsActive ?? true,
      name: res?.Name || '',
      description: res?.Description || '',
      value: res?.Value || '',
      isSummary: res?.IsSummary ?? false,
      tenant: res?.AD_Client_ID?.identifier || '',
      tenantId: res?.AD_Client_ID?.id || '',
      replicationStrategy: res?.AD_ReplicationStrategy_ID?.identifier || '',
      replicationStrategyId: res?.AD_ReplicationStrategy_ID?.id || '',
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false

    /*for(let record of ['organization_info']) {
      const response = await $fetch('/api/admin/organizations/'+route.params.id+'/'+record.replaceAll('_', '-'), {
        headers: useRequestHeaders(['cookie'])
      })
      if(response) {
        let newData = []
        if(record === 'organization_info') {
          newData = response.records.map(item => {
            return {
              id: item.uid,
              isActive: item.IsActive,
              DUNS: item.DUNS,
              taxID: item.TaxID,
              tenant: item?.AD_Client_ID?.identifier || '',
              tenantId: item?.AD_Client_ID?.id || '',
              location: item?.C_Location_ID?.identifier || '',
              locationId: item?.C_Location_ID?.id || '',
              warehouse: item?.M_Warehouse_ID?.identifier || '',
              warehouseId: item?.M_Warehouse_ID?.id || '',
              orgType: item?.AD_OrgType_ID?.identifier || '',
              orgTypeId: item?.AD_OrgType_ID?.id || '',
              supervisor: item?.Supervisor_ID?.identifier || '',
              supervisorId: item?.Supervisor_ID?.id || '',
              parentOrg: item?.Parent_Org_ID?.identifier || '',
              parentOrgId: item?.Parent_Org_ID?.id || '',
              show: true
            }
          })
        }

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

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.isSummary == (lastRecord.value?.IsSummary ?? false) &&
    form.value.tenantId == (lastRecord.value?.AD_Client_ID?.id || '') &&
    form.value.replicationStrategyId == (lastRecord.value?.AD_ReplicationStrategy_ID?.id || '')
  ) ? true : false
}

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const duplicate = () => {
  //router.push(`/users/organizations/${route.params.id}/duplicate`)
  openTab(`/duplicate/organization-${route.params.id}`, `Organization: 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('/users/organizations')
    openTab(`/users/organizations`, `Organizations`)
  }
}

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/admin/organizations/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      isActive: form.value.isActive,
      name: form.value.name,
      description: form.value.description,
      value: form.value.value,
      isSummary: form.value.isSummary,
      replicationStrategyId: form.value.replicationStrategyId,
    }
  })

  if(Number(res.status) === 200 && res.id) {
    /*for(let [key, items] of Object.entries(entries)) {
      for(let entry of items) {
        if(entry.id) {
          let body = {}
          if(key === 'organization_info') {
            body = {
              id: entry.id,
              isActive: entry.isActive,
              DUNS: body.DUNS,
              taxID: body.taxID,
              locationId: entry.locationId,
              warehouseId: entry.warehouseId,
              orgTypeId: entry.orgTypeId,
              supervisorId: entry.supervisorId,
              parentOrgId: entry.parentOrgId,
            }
          }

          await $fetch(`/api/admin/organizations/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'PUT',
            headers: useRequestHeaders(['cookie']),
            body
          })
        } else {
          let body = {}
          if(key === 'organization_info') {
            body = {
              isActive: entry.isActive,
              DUNS: body.DUNS,
              taxID: body.taxID,
              locationId: entry.locationId,
              warehouseId: entry.warehouseId,
              orgTypeId: entry.orgTypeId,
              supervisorId: entry.supervisorId,
              parentOrgId: entry.parentOrgId,
            }
          }

          await $fetch(`/api/admin/organizations/${res.id}/${key.replaceAll('_', '-')}`, {
            method: 'POST',
            headers: useRequestHeaders(['cookie']),
            body
          })
        }
      }
    }*/
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      //router.push('/users/organizations/'+res.id+'/view')
      openTab(`/view/organization-${res.id}`, `Organization: View Details`)
    } 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 breadCrumb = computed(() => ([
  { link: '/users/users', text: 'Users'},
  { link: '/users/organizations', text: 'Organizations'},
  { link: '#', text: 'Edit Organization', active: true}
]))
</script>

<template>
  <Head>
    <Title>Edit Organization</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.name === '' || 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.name === '' || noEdit || form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</button>
        </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>
        <AdminOrganizationForm v-model="form" @save="save" />
      </div>
    </div>
  </NuxtLayout>
</template>