<template>
  <div class="dashboard-listing-container">
    <DashboardBanner />

    <TemplateContainer size="xl">
      <FiltersContainer :id="filterId" :filters="filters" />

      <TableListing
        :id="listingId"
        :fields="fields"
        :filters="requestFilters"
        :filter-id="filterId"
        :items-per-page="15"
        :headers="headers"
        :rows="rows"
        :request-config="{ abortPrevious: true }"
        :search-in="['procedures']"
        :actions="actions"
        endpoint="content/procedures"
        empty-cell-value="-"
        loader-size="xxl"
      />
    </TemplateContainer>
  </div>
</template>

<script setup>
import { markRaw, computed } from 'vue'

import TemplateContainer from '@inside-commons/components/lib/TemplateContainer'
import FiltersContainer from '@inside-filters/displays/FiltersContainer'
import TableListing from '@inside-listings/components/TableListing'
import TitleCol from '../folders/TitleCol'
import DashboardBanner from '../common/DashboardBanner'
import StatusUi from '../common/StatusUi'
import FormattedReferences from '../../FormattedReferences'
import { Link } from 'inside-collection/components'
import { BaseText } from 'inside-collection/atoms'

import { fields, requestFilters } from './request'
import { getAppInstance } from '@inside-core/helpers/getAppInstance'
import { i18n } from '@inside-library/helpers/global-methods/langs'
import { formatHref, routeExists } from '@inside-library/helpers/Langs'
import { $_formatDate } from '@inside-library/helpers/global-methods/dates'

const app = getAppInstance()
const tr = i18n('customs.DASHBOARD.LISTING')

const props = defineProps({
  fetchedData: {
    type: Object
  }
})

const listingId = 'dashboard-corporate-procedures-listing'
const filterId = 'dashboard-corporate-procedures-filters'

const status = {
  0: 'declined',
  1: 'published',
  2: 'inProgress',
  3: 'unpublished',
  4: 'planned'
}

const getWorkflowStatusName = statusCode => {
  switch (statusCode) {
    case 0:
      return tr('status.inProgress')
    case 1:
      return tr('status.published')
    default:
      return '-'
  }
}

const rows = computed(() => {
  return fields => [
    {
      tag: markRaw(TitleCol),
      data: {
        listingId,
        title: fields.title,
        uuid: fields.uuid,
        isChild: fields.isChild
      }
    },
    {
      id: 'procedureCategory',
      tag: markRaw(BaseText),
      value: fields.procedures_categories?.title || '-'
    },
    {
      id: 'author',
      tag: markRaw(BaseText),
      value: app.config.globalProperties.$_username(fields.authors)
    },
    {
      id: 'workflow-step-1',
      tag: markRaw(StatusUi),
      class: (() => {
        const historiesNumber = fields.workflow?.histories?.length

        if (
          fields.workflow?.histories?.[historiesNumber - 1]?.[0] ||
          fields.workflow?.histories?.[historiesNumber - 1]?.[0]?.validated ===
            0
        ) {
          return `status--${
            fields.workflow?.histories?.[historiesNumber - 1]?.[0]
              ?.validated === 0
              ? 2
              : 1
          }`
        }
      })(),
      data: {
        status:
          fields.workflow?.status !== 0
            ? getWorkflowStatusName(
                fields.workflow?.histories?.[
                  fields.workflow?.histories?.length - 1 || 0
                ]?.[0]?.validated
              )
            : '-'
      }
    },
    {
      id: 'workflow-step-2',
      tag: markRaw(StatusUi),
      class: (() => {
        const historiesNumber = fields.workflow?.histories?.length

        if (
          fields.workflow?.histories?.[historiesNumber - 1]?.[1] ||
          fields.workflow?.histories?.[historiesNumber - 1]?.[1]?.validated ===
            0
        ) {
          return `status--${
            fields.workflow?.histories?.[historiesNumber - 1]?.[1]
              ?.validated === 0
              ? 2
              : 1
          }`
        }
      })(),
      data: {
        status:
          fields.workflow?.status !== 0
            ? getWorkflowStatusName(
                fields.workflow?.histories?.[
                  fields.workflow?.histories?.length - 1 || 0
                ]?.[1]?.validated
              )
            : '-'
      }
    },
    {
      id: 'workflowStatus',
      tag: markRaw(StatusUi),
      class: (() => {
        if (
          (fields.workflow && fields.workflow.status) ||
          fields?.workflow?.status === 0
        ) {
          return `status--${fields.workflow.status}`
        }
      })(),
      data: {
        status: (() => {
          if (
            (fields.workflow && fields.workflow.status) ||
            fields?.workflow?.status === 0
          ) {
            return tr(`status.${status[fields.workflow.status]}`)
          }

          return '-'
        })()
      }
    },
    {
      id: 'publicationStatus',
      tag: markRaw(StatusUi),
      class: (() => {
        return `status--${fields.status ? '1' : '3'}`
      })(),
      data: {
        status: (() => {
          return fields.status ? tr('item.published') : tr('item.unpublished')
        })()
      }
    },
    {
      value: $_formatDate(fields.published_at)
    }
  ]
})

const filters = computed(() => {
  return [
    {
      modelName: 'search',
      type: 'text',
      placeholder: tr('filters.search')
    },
    {
      modelName: 'authors',
      type: 'selectbox',
      async: {
        contentType: 'users',
        fields: ['lastname', 'firstname', 'uuid'],
        filters: {
          'status:eq': 1,
          'is_maintenance:eq': 0
        }
      },
      reference: 'authors',
      label: tr('filters.authors'),
      labelCallback: fields => app.config.globalProperties.$_username(fields),
      objectValueKey: 'uuid'
    },
    {
      modelName: 'procedures_categories',
      type: 'selectbox',
      fetch: true,
      fields: ['uuid', 'title'],
      filters: { 'status:eq': 1, sort: 'title:asc' },
      reference: 'procedures_categories',
      label: tr('filters.proceduresCategories'),
      objectLabelKey: 'title',
      objectValueKey: 'uuid'
    },
    {
      modelName: 'status',
      type: 'selectbox',
      label: tr('filters.status'),
      filterOn: 'status',
      inputData: [
        {
          label: tr('status.published'),
          value: '1'
        },
        {
          label: tr('status.declined'),
          value: '0'
        },
        {
          label: tr('status.inProgress'),
          value: '2'
        }
      ],
      callback: value => {
        if (!value) return {}

        return {
          workflow: {
            'status:eq': value
          }
        }
      }
    }
  ]
})

const headers = computed(() => {
  return [
    {
      value: tr('cols.title'),
      sortable: true,
      key: 'title'
    },
    {
      value: tr('cols.procedureCategory')
    },
    {
      value: tr('cols.author')
    },
    {
      value: tr('cols.workflowStep1')
    },
    {
      value: tr('cols.workflowStep2')
    },
    {
      value: tr('cols.workflowStatus'),
      key: 'workflow_status'
    },
    {
      value: tr('cols.publicationStatus'),
      key: 'publication_status'
    },
    { value: tr('cols.publishedAt') }
  ]
})

const actions = computed(() => {
  return [
    {
      id: 'link',
      icon: 'eye-on',
      label: tr('actions.link'),
      callback: async (fields, vm) => {
        const method = vm.$_getRedirectionMethod('procedures')

        const redirectionParams = {
          data: fields,
          params: vm.$_getRedirectionParams('procedures')
        }

        if (method) {
          let redirection = method(redirectionParams)

          if (redirection instanceof Promise) {
            redirection.then(res => {
              redirection = res

              if (routeExists({ router: vm.$router, to: redirection })) {
                const url = vm.$router.resolve(
                  formatHref(redirection, vm.$_currentLang)
                ).href

                window.open(url, '_blank')
              }
            })
          } else {
            if (routeExists({ router: vm.$router, to: redirection })) {
              const url = vm.$router.resolve(
                formatHref(redirection, vm.$_currentLang)
              ).href

              window.open(url, '_blank')
            }
          }
        } else {
          vm.$router.push(`/${vm.getCheckedData(fields, ['slug', 0])}`)
        }
      }
    },
    {
      id: 'edit',
      icon: 'edit',
      tag: markRaw(Link),
      label: tr('actions.edit'),
      hideIf: (data, vm) => {
        const canUpdate = vm.getCheckedData(data, [
          'admin',
          'permission',
          'update'
        ])
        return !canUpdate
      },
      data: ({ content_type: content, uuid }) => ({
        href: {
          name: 'Edition',
          params: { content, uuid }
        },
        target: '_blank',
        inline: false
      })
    }
  ]
})
</script>

<style lang="scss" scoped>
@use '../common/dashboard.scss' as *;
</style>
