import { Component, Prop } from 'vue-property-decorator';
import Vue from 'vue';
import { ConditionType } from '@components/common/base-search-bar/index';
import { i18n } from '@plugins/i18n';
import ServicesSearchBar from './components/search-bar.vue';
import get from 'lodash/get';
import { pushRoute } from '@utils/routes';
import {
  SettingsForService,
  SettingsForServiceApi,
} from '@openapi/registry-service';
import { notifyError } from '@utils/notify';

const settingsForServiceApi = new SettingsForServiceApi();
@Component({
  components: {
    ServicesSearchBar,
  },
})
class AdditionalSettings extends Vue {
  @Prop() searchQuery: ServiceSearchQuery | undefined;

  private loading = false;
  private sortByDefault = 'modified';

  model = {
    loading: false,
    pagination: {
      descending:
        this.$route.query.descending === undefined
          ? true
          : this.$route.query.descending === 'true',
      rowsPerPage: this.$route.query.rowsPerPage
        ? Number(this.$route.query.rowsPerPage)
        : 10,
      sortBy: this.$route.query.sortBy
        ? this.$route.query.sortBy
        : this.sortByDefault,
      rowsNumber: 0,
      page: this.$route.query.page ? Number(this.$route.query.page) : 1,
    },
    settings: [] as SettingsForService[],
    visibleColumns: ['shortName'],
    query: '',
  };

  queryString = '';

  fulltextString = '';

  attributes = [
    {
      attribute: 'description',
      attributeName: i18n.t('services.description'),
      conditionType: ConditionType.string,
      value: '',
    },
  ];

  private measureList: any = [];

  private get stateColorMapSet() {
    return this.$store.getters[
      'registryService/additionalSettings/stateColorMapSet'
    ];
  }

  private get columns() {
    return [
      {
        align: 'left',
        field: (i: any) => i,
        formatField: 'shortName',
        handler: (item: any, options: any) => {
          pushRoute(
            this.$router,
            {
              name: 'cards',
              params: {
                id: item.id,
                path: 'additional-settings',
              },
              query: {
                active: 'basic',
                components: this.$store.getters[
                  'cardComponents/additionalSettings/components'
                ],
              },
            },
            options?.targetBlank
          );
        },
        label: this.$t('services.shortName'),
        name: 'shortName',
        style: 'white-space: normal;',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        field: 'petitionType',
        label: this.$t('services.petitionType'),
        name: 'petitionType',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        field: 'state',
        label: this.$t('services.state'),
        name: 'state',
        style: 'white-space: pre-wrap',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        field: (val: any) =>
          this.measureList?.find(
            (measure: any) => measure.id === val.socialSupportMeasureId
          )?.name,
        label: this.$t('additionalSettings.socialSupportMeasure'),
        name: 'socialSupportMeasureId',
        style: 'white-space: pre-wrap',
        required: true,
        sortable: true,
      },
    ];
  }

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

  private saveData(): void {
    const query = [];

    if (this.queryString) {
      query.push(`(${this.queryString})`);
    }
  }

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

    const pagination = {
      sort: '',
    };

    if (this.sort) {
      pagination.sort = this.sort;
    }
    this.fetch();
  }

  private pending = 0;

  private async fetch(q?: ServiceQuery) {
    if (typeof q !== 'undefined') {
      this.queryString = q?.query || '';
      this.fulltextString = q?.fulltext || '';
    }

    if (this.pending) {
      this.pending++;
      return;
    }

    this.pending = 1;
    this.model.loading = true;

    await settingsForServiceApi
      .pagingSettingsForServicePage(
        this.model.pagination.page,
        this.model.pagination.rowsPerPage,
        this.queryString,
        this.fulltextString,
        `${this.model.pagination.descending ? '-' : '+'}${
          this.model.pagination.sortBy
        }`
      )
      .then(({ data }) => {
        if (typeof data.totalRows !== 'undefined' && data.records) {
          this.model.pagination.rowsNumber = data.totalRows;
          this.model.settings = data.records;
          let measureList = data.records
            ?.filter((e) => e.socialSupportMeasureId)
            .map((e) => e.socialSupportMeasureId);

          measureList = measureList.filter(
            (e, i) => measureList.indexOf(e) === i
          );
          measureList.map((id) =>
            this.$store
              .dispatch(
                'registryService/additionalSettings/getSocialSupportMeasure',
                id
              )
              .then((measures) => {
                this.measureList.push(measures);
              })
              .catch((err) => {
                notifyError(err.message.toString());
              })
          );
        }
      })

      .catch((err) => {
        notifyError(err.message.toString());
      })
      .finally(() => {
        this.model.loading = false;
      });

    if (this.pending > 1) {
      this.pending = 0;
      await this.fetch();

      return;
    }
    this.pending = 0;
  }
}

export default AdditionalSettings;

declare interface ServiceQuery {
  query: string;
  fulltext: string;
}

export interface ServiceSearchQuery {
  status: string;
  search: string;
}
