import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import get from 'lodash/get';

@Component({})
export default class Solutions extends Vue {
  @Prop() searchQuery: SolutionSearchQuery;

  @Watch('solutionsRowsNumber', {
    immediate: true,
  })
  private solutionsRowsNumberHandler(val: number): void {
    this.model.pagination.rowsNumber = val;
  }

  @Watch('inputSearch')
  private inputSearchHandler(): void {
    this.init();
  }

  private sortByDefault = 'modified';

  model = {
    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,
    },
    visibleColumns: ['name'],
    query: '',
  };

  // @ts-ignore
  inputSearch = this.searchQuery.search ?? '';

  private get columns() {
    return [
      {
        align: 'left',
        field: (val: any) => val,
        formatField: 'name',
        handler: (id: any) => {
          this.$router.push({
            name: 'cards',
            params: {
              id,
              path: 'solutions',
            },
            query: {
              active: 'basic',
              components: this.$store.getters[
                'cardComponents/solutions/components'
              ],
            },
          });
        },
        handlerField: 'id',
        icon: 'work_outline',
        label: this.$t('solutions.name'),
        name: 'name',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        field: 'description',
        label: this.$t('solutions.description'),
        name: 'description',
        required: true,
        sortable: true,
      },
      {
        align: 'left',
        field: 'roles',
        label: this.$t('solutions.roles'),
        formatField: 'name',
        name: 'roles',
        icon: 'o_group',
        required: true,
        sortable: true,
      },
    ];
  }

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

  created() {
    if (!this.$route.query.filter) {
      this.init();
    }
  }

  private create() {
    this.$router.push({
      name: 'solutions-create',
    });
  }

  private setQuery(q?: string) {
    this.model.query = q || '';
    this.init();
  }

  private async init(val: any = null): Promise<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;
    }

    const pagination = {
      page: this.model.pagination.page,
      rowsPerPage: this.model.pagination.rowsPerPage,
      sort: '',
    };

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

    const arrQuery = [this.model.query];

    const query = arrQuery
      .filter((filter: string | null) => !!filter)
      .join(' and ');

    const fulltext =
      this.inputSearch.length > 0
        ? `name=searchprefix='${this.inputSearch}' or description=searchprefix='${this.inputSearch}'`
        : '';

    const solutions = await this.$store.dispatch(
      'idm/solutions/dispatchSolutions',
      {
        page: pagination.page,
        perPage: pagination.rowsPerPage,
        query,
        fulltext,
        expand: 'roles',
      }
    );

    this.model.pagination.rowsNumber = solutions.totalRows;
  }

  private get solutionsRecords() {
    return this.$store.getters['idm/solutions/solutionsRecords'];
  }

  private get solutionsLoading() {
    return this.$store.getters['idm/solutions/solutionsLoading'];
  }
}

export interface SolutionSearchQuery {
  search: string;
}
