<template>
  <widget-page
    @load="loadOnScroll"
    :disable="!messages.length || disableScroll"
    :is-loading="isLoading"
  >
    <widget-search-input
      v-model="searchQuery"
      @cancel="cancel"
      label="Поиск по клиенту или задаче"
    />
    <widget-page-state
      v-if="!searchQuery"
      icon="la la-search"
      title="Введите запрос"
    />
    <widget-page-state
      @submit="showAll"
      v-if="searchQuery && !messages.length && !isLoading"
      icon="la la-search"
      has-btn
      :title="emptyResultText"
      submit-label="Все сообщения"
    />
    <search-messages v-if="messages.length" :messages="messages" />
  </widget-page>
</template>

<script lang="ts">
import { Component, Inject, Vue, Watch } from 'vue-property-decorator'
import { FoundMessage } from '@/widgets/messages/types/Message'
import WidgetPage from '@/widgets/base/components/widget-page/WidgetPage.vue'
import WidgetSearchInput from '@/widgets/base/components/widget-page/WidgetSearchInput.vue'
import WidgetPageState from '@/widgets/base/components/widget-page/WidgetPageState.vue'
import MessageModule from '@/widgets/messages/modules/MessageModule'
import SearchMessages from '@/widgets/messages/components/search/SearchMessages.vue'
import { hashNavRoutes } from '@/widgets/messages/router/hashRoutes'

@Component({
  components: {
    SearchMessages,
    WidgetPageState,
    WidgetSearchInput,
    WidgetPage,
  },
})
export default class SearchPage extends Vue {
  @Inject('MessageModule')
  messageModule!: MessageModule

  isLoading = false
  disableScroll = false

  get searchQuery(): string {
    const params = hashNavRoutes.search.match(this.$route.hash)

    return params ? (params.query ?? '') : ''
  }

  set searchQuery(value: string) {
    this.$router.replace({
      hash: hashNavRoutes.search.compile({ query: value }),
    })
  }

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

  get messages(): FoundMessage[] {
    return this.messageModule.foundMessages
  }

  async searchMessages(ids: number[], withPaginate?: boolean) {
    this.isLoading = true
    const messages = await this.messageModule.searchMessages({
      query: this.searchQuery,
      withPaginate,
      ids,
    })
    this.isLoading = false

    return messages
  }

  async loadOnScroll(index: number, done: Function) {
    const messages = await this.searchMessages(
      this.messages.map(m => m.id),
      true
    )

    this.disableScroll = messages.length === 0

    done()
  }

  showAll() {
    this.$router.push({ hash: hashNavRoutes.index.compile() })
  }

  @Watch('searchQuery', { immediate: true })
  search() {
    if (!this.searchQuery) {
      return this.messageModule.setFoundMessages([])
    }

    this.disableScroll = false
    this.searchMessages([])
  }

  cancel() {
    this.$router.push({ hash: hashNavRoutes.index.compile() })
  }
}
</script>
