import { notifierRegistryComputed } from '@state/modules/notifier-registry';
import { VueClass } from 'vue-class-component/lib/declarations';
import Vue from 'vue';
import { Component, Watch } from 'vue-property-decorator';
import { Mixins } from '@utils/mixin';
import { convertDateFromBackendFormat } from '@utils/format-date';
import { EnvelopesApi } from '@openapi/notifier-registry';
import get from 'lodash/get';
import { notifyError } from '@utils/notify';
import { pushRoute } from '@utils/routes';
import { USER_SCOPES } from '@constants/entities/Scope';

const EnvelopesInjection: VueClass<Vue> = Vue.extend({
  computed: {
    ...notifierRegistryComputed,
  },
});

@Component({
  methods: {
    get,
  },
})
export default class Envelopes extends Mixins(EnvelopesInjection) {
  @Watch('envelopesRowsNumber', {
    immediate: true,
  })
  private envelopesRowsNumberHandler(val: number): void {
    this.model.pagination.rowsNumber = val;
  }

  private sortByDefault = 'createDate';

  private envelopesService = new EnvelopesApi();

  private model: any = {
    dialog: {
      envelope: null,
      value: false,
    },
    pagination: {
      descending:
        this.$route.query.descending === undefined
          ? true
          : this.$route.query.descending === 'true',
      page: this.$route.query.page ? Number(this.$route.query.page) : 1,
      rowsNumber: 0,
      rowsPerPage: this.$route.query.rowsPerPage
        ? Number(this.$route.query.rowsPerPage)
        : 10,
      sortBy: this.$route.query.sortBy
        ? this.$route.query.sortBy
        : this.sortByDefault,
    },
    /* visibleColumns: [
      'title',
      'body',
      'recipient.address',
      'linkOnTemplate',
      'orgRecipient',
      'createDate',
    ], */
  };

  private get visibleColumns(): any[] {
    const allColumns = [
      'title',
      'body',
      'recipient.address',
      'linkOnTemplate',
      'orgRecipient',
      'createDate',
    ];

    return allColumns.map((column) => {
      if (column === 'linkOnTemplate') {
        if (
          this.$AC.haveOneOfScope([
            USER_SCOPES.ALLOCATE_PERMISSION_SPEC,
            USER_SCOPES.ALLOCATE_PERMISSION_REG,
            USER_SCOPES.ORGANIZATION_ADMIN,
            USER_SCOPES.REGION_ADMIN,
          ])
        ) {
          return column;
        }
      } else {
        return column;
      }
    });
  }

  private get sort(): string {
    return `${this.model.pagination.descending ? '-' : '+'}${
      this.model.pagination.sortBy
    }`;
  }

  private get email(): string {
    const currentUser = this.$store.getters['oidcClient/currentUser'];
    return currentUser.email;
  }

  private get columns(): any[] {
    return [
      {
        field: 'id',
        label: this.$t('envelopes.id'),
        name: 'id',
      },
      {
        align: 'left',
        field: 'title',
        isHTML: true,
        label: 'Тема сообщения',
        name: 'title',
        sortable: true,
      },
      {
        align: 'left',
        field: (val: any) => val,
        format: (val: any) => {
          const stringBody: any = get(val, 'body');
          const body =
            stringBody && typeof stringBody === 'string'
              ? `${stringBody.slice(0, 80)}...`
              : '';
          return body;
        },
        isHTML: true,
        label: this.$t('envelopes.content'),
        name: 'body',
        sortable: true,
      },
      {
        name: 'recipient.address',
        field: 'recipient.address',
        label: 'Получатель',
        align: 'left',
      },
      {
        name: 'linkOnTemplate',
        label: 'Шаблон уведомления',
        align: 'center',
      },
      {
        name: 'orgRecipient',
        label: 'Организация получателя',
        field: 'messageContext.nameOrganization',
        align: 'left',
      },
      {
        align: 'right',
        field: (val: any) => val,
        format: (val: any) => {
          const createDate = val.createDate
            ? convertDateFromBackendFormat(val.createDate)
            : '';
          let result = createDate;

          if (createDate && !val.checked) {
            result = `<b>${createDate}</b>`;
          }

          return result;
        },
        isHTML: true,
        label: this.$t('envelopes.createdBy'),
        name: 'createDate',
        sortable: true,
      },
    ];
  }

  private created(): void {
    this.init();
  }

  private init(val?: any): void {
    if (
      get(
        {
          val,
        },
        'val.pagination'
      )
    ) {
      this.model.pagination.descending = val.pagination.descending;
      this.model.pagination.page = val.pagination.page;
      this.model.pagination.rowsPerPage = val.pagination.rowsPerPage;
      this.model.pagination.sortBy =
        val.pagination.sortBy === null
          ? this.sortByDefault
          : val.pagination.sortBy;
    }

    this.$store.dispatch('notifierRegistry/dispatchEnvelopes', {
      opts: {
        page: this.model.pagination.page - 1,
        size: 100,
        sort: this.sort,
        email: this.email,
      },
    });
  }

  private rowsHandler(row: any): void {
    if (row.checked) {
      this.model.dialog.envelope = row;
      this.model.dialog.value = true;
    } else {
      this.envelopesService
        .updateEnvelope1([
          {
            id: row.id,
            checked: true,
          },
        ])
        .then(() => {
          this.model.dialog.envelope = row;
          this.init();
          this.model.dialog.value = true;
        })
        .catch((e: any) => {
          notifyError(e.message.toString());
        });
    }
  }

  goTo(id: string): void {
    console.log(id);
    pushRoute(this.$router, {
      name: 'cards',
      params: {
        path: 'notifications',
        id: id,
      },
      query: {
        components: 'index,settings,data',
        active: 'settings',
      },
    });
  }

  deleteEnvelope(id: string): void {
    this.envelopesService
      .deleteEnvelope1(id)
      .then(() => {
        this.init();
      })
      .catch((e: any) => {
        notifyError(e.message.toString());
      })
      .finally(() => {
        this.model.dialog.value = false;
      });
  }
}
