<template>
  <widget-page
    @load="infinityLoad"
    :disable="isDisableInfinity || !searchQuery"
    :is-loading="isInitialLoading"
  >
    <widget-search-input
      v-model="searchQuery"
      @cancel="toIndexRoute"
      label="Поиск по клиенту или задаче"
    />
    <widget-page-state
      v-if="!searchQuery"
      icon="la la-search"
      title="Введите запрос"
    />
    <widget-page-state
      v-if="searchQuery && !tasks.length && !isInitialLoading"
      icon="la la-search"
      :title="emptyResultText"
    />
    <task-list v-if="tasks.length && searchQuery" :tasks="tasks" />
  </widget-page>
</template>

<script lang="ts">
import { Component, Inject, Watch } from 'vue-property-decorator'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { LoadTasksPayload } from '@/widgets/tasks/http/dto/LoadTasksPayload'
import WidgetPage from '@/widgets/base/components/widget-page/WidgetPage.vue'
import WidgetPageState from '@/widgets/base/components/widget-page/WidgetPageState.vue'
import WidgetSearchInput from '@/widgets/base/components/widget-page/WidgetSearchInput.vue'
import TaskList from '@/widgets/tasks/components/tasks/TaskList.vue'
import BaseTasksPage from '@/widgets/tasks/pages/BaseTasksPage'

@Component({
  components: { TaskList, WidgetSearchInput, WidgetPageState, WidgetPage },
})
export default class SearchResultPage extends BaseTasksPage {
  @Inject('TaskModule')
  taskModule!: TaskModule

  initialPayload: LoadTasksPayload = { ids: [], searchQuery: this.searchQuery }

  get searchQuery(): string {
    return (this.$route.query.query || '') as string
  }

  set searchQuery(value: string) {
    this.initialPayload.searchQuery = value
    this.$router.replace({ query: { query: value } })
  }

  get emptyResultText(): string {
    return `По запросу  “${this.searchQuery}” ничего не найдено.`
  }

  activated() {
    this.taskModule.setTasks([])
    this.isInitialLoading = false

    if (this.searchQuery) {
      this.initialLoad()
    }
  }

  @Watch('$route')
  loadTasks() {
    if (this.searchQuery) {
      this.initialLoad()
    }
  }
}
</script>
