<template>
  <TemplateContainer size="xl" class="dashboard-listing">
    <filters-container :id="filterId" :filters="filters" />

    <table-listing
      id="dashboard-listing"
      endpoint="content/p_and_p,p_and_p_france"
      :filter-id="filterId"
      :items-per-page="20"
      :headers="headers"
      :rows="rows"
      pagination="infiniteScroll"
      :filters="{
        sort: 'published_at:desc'
      }"
      :fields="fields"
      :actions="actions"
      :search-in="contents"
    />
  </TemplateContainer>
</template>

<script>
import { markRaw } from 'vue'

import { Link } from 'inside-collection/components'
import TemplateContainer from '@inside-commons/components/lib/TemplateContainer'
import StatusUi from '../ui/StatusUi'
import ReferencesList from './sub-components/ReferencesList'

import workflowStatus from '@inside-workflows/mixins/workflow-status'

import { formatHref } from '@inside-library/helpers/Langs'

export default {
  name: 'DashboardListing',
  $_i18nRootPath: 'customs.dashboard.LISTING',
  components: {
    Link,
    TemplateContainer,
    ReferencesList
  },
  mixins: [workflowStatus],
  props: {
    contents: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      filterId: 'dashboard-filters'
    }
  },
  computed: {
    fields() {
      return [
        'title',
        'published_at',
        'content_type',
        'admin',
        'workflow',
        'slug',
        'status',
        {
          brands: {
            fields: ['title', 'uuid', 'total'],
            filters: { langcode: this.$_currentLang }
          }
        },
        {
          countries: {
            fields: ['title', 'uuid', 'total'],
            filters: { langcode: this.$_currentLang }
          }
        },
        { authors: ['firstname', 'lastname'] }
      ]
    },
    filters() {
      return [
        {
          modelName: 'search',
          type: 'text',
          placeholder: this.$_tr('filters.search')
        },
        {
          modelName: 'brands',
          type: 'selectbox',
          fetch: true,
          label: this.$_tr('filters.brands'),
          reference: 'brands',
          filters: {
            sort: 'title:asc'
          },
          fields: ['title', 'uuid'],
          objectLabelKey: 'title',
          objectValueKey: 'uuid'
        },
        {
          modelName: 'countries',
          type: 'selectbox',
          fetch: true,
          label: this.$_tr('filters.countries'),
          reference: 'countries',
          filters: {
            sort: 'title:asc'
          },
          fields: ['title', 'uuid'],
          objectLabelKey: 'title',
          objectValueKey: 'uuid'
        },
        {
          modelName: 'status',
          type: 'selectbox',
          label: this.$_tr('filters.workflow'),
          filterOn: 'workflow.status',
          inputData: (() => {
            return Object.keys(workflowStatus.status)
              .map(item => {
                const workflow = {
                  value: item[0],
                  label: this.$_statusName(item[0])
                }
                return workflow
              })
              .filter(data => data.value !== '3')
          })(),
          callback: value => {
            return value
              ? {
                  workflow: { 'status:eq': value[0] }
                }
              : {}
          }
        }
      ]
    },
    headers() {
      return [
        {
          value: this.$_tr('cols.title'),
          sortable: true,
          key: 'title'
        },
        {
          value: this.$_tr('cols.author')
        },
        {
          value: this.$_tr('cols.brands'),
          key: 'brands'
        },
        {
          value: this.$_tr('cols.countries'),
          key: 'countries'
        },
        {
          value: this.$_tr('cols.type'),
          key: 'content_type'
        },
        {
          value: this.$_tr('cols.workflowStatus'),
          key: 'workflow_status'
        },
        {
          value: this.$_tr('cols.publicationStatus'),
          key: 'publication_status'
        },
        {}
      ]
    },
    rows() {
      return fields => [
        {
          id: 'title',
          class: 'title',
          value: fields.title,
          ...(this.isAlive(fields, 'slug.0')
            ? {
                tag: markRaw(Link),
                data: {
                  href: this.redirection(fields),
                  inline: false
                }
              }
            : {
                tag: 'p'
              })
        },
        {
          id: 'authors',
          tag: 'p',
          value: this.$_username(fields.authors)
        },
        ...(this.getCheckedData(fields.brands, 'data', []).length ===
        this.getCheckedData(fields.brands, 'total')
          ? [
              {
                id: 'brands',
                tag: 'p',
                value: this.$_tr('all')
              }
            ]
          : [
              {
                id: 'brands',
                class: 'brands',
                tag: markRaw(ReferencesList),
                data: { list: this.getCheckedData(fields, 'brands.data', []) }
              }
            ]),
        ...(this.getCheckedData(fields.countries, 'data', []).length ===
        this.getCheckedData(fields.countries, 'total')
          ? [
              {
                id: 'countries',
                tag: 'p',
                value: this.$_tr('all')
              }
            ]
          : [
              {
                id: 'countries',
                class: 'countries',
                tag: markRaw(ReferencesList),
                data: {
                  list: this.getCheckedData(fields, 'countries.data', [])
                }
              }
            ]),
        {
          id: 'type',
          tag: 'p',
          value: this.$_tr(`types.${fields.content_type}`)
        },
        {
          id: 'workflow_status',
          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 this.$_statusName(fields.workflow.status)
              }

              return '-'
            })()
          }
        },
        {
          id: 'publication_status',
          tag: markRaw(StatusUi),
          class: (() => {
            return `status--${fields.status ? '1' : '3'}`
          })(),
          data: {
            status: (() => {
              return fields.status
                ? this.$_tr('item.published')
                : this.$_tr('item.unpublished')
            })()
          }
        }
      ]
    },
    actions() {
      return [
        {
          id: 'edit',
          icon: 'edit',
          tag: 'router-link',
          hideIf: (data, vm) => {
            const canUpdate = vm.getCheckedData(data, [
              'admin',
              'permission',
              'update'
            ])
            return !canUpdate
          },
          data: fields => ({
            to: `/edit/${fields.content_type}/${fields.uuid}`,
            target: '_blank'
          })
        },
        {
          id: 'access',
          trPath: 'customs.dashboard.LISTING.actions.access',
          icon: 'eye-on',
          tag: markRaw(Link),
          hideIf: () => false,
          data: fields => {
            return {
              href: this.redirection(fields),
              inline: false,
              target: '_blank'
            }
          }
        },
        'delete'
      ]
    }
  },
  methods: {
    redirection(fields) {
      return formatHref(
        {
          name: fields.content_type === 'p_and_p' ? 'PPPage' : 'PPFrenchPage',
          params: {
            slug: fields.slug[0]
          }
        },
        this.$_currentLang
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-listing {
  :deep(.status--0) {
    color: var(--color-invalid);
  }

  :deep(.status--1) {
    color: var(--color-valid);
  }

  :deep(.status--2) {
    color: var(--color-warn);
  }

  :deep(.status--3) {
    color: var(--color-invalid);
  }

  :deep(.title) {
    text-decoration: none;
  }
}
</style>
