<template>
  <div>
    <base-message-form
      @save="createNewTask"
      @cancel="cancel"
      @change-type="currentType = parseInt($event)"
      :loading="isLoading"
      :types="types"
      :current-type="currentType.toString()"
      class="q-ma-sm"
      submit-text="Создать"
    >
      <template #flash>
        <q-slide-transition>
          <ui-flash
            @close="errors = {}"
            v-if="errorsAsArray.length > 0"
            :items="errorsAsArray"
          />
        </q-slide-transition>
      </template>
      <template #after-title v-if="isTaskType">
        <task-manager-avatars
          @click="isShowManagersSelect = true"
          :selected-uids="candidateUids"
          class="q-mr-sm"
        />
        <task-level-menu @change="level = $event" :current-level="level" />
      </template>
      <template #body>
        <template v-if="isTaskType">
          <categories-select v-model="categoryId" :errors="errors" />
          <client-form
            @set-client-id="clientId = $event"
            @set-order-name="orderName = $event"
            :order-name="orderName"
            :client-id="clientId"
            :search-clients-fn="searchClientFn"
            :get-client-by-order="getClientByOrderName"
            :get-orders-by-client="getOrdersByClientId"
            :get-client-by-id-fn="getClientById"
            :errors="errors"
          />
        </template>
        <ui-input-material
          v-model="text"
          autogrow
          label="Опишите задачу"
          type="autocomplete"
          name="text"
          :errors="errors"
        />
        <date-picker
          @show-preview="showPreview"
          v-model="executeUntilDate"
          v-if="isTaskType"
          :is-show-preview="isShowPreview"
        />
        <file-attach-btn @change="setFiles" class="q-mt-md" />
        <new-task-files :files="files" />
      </template>
      <task-manager-select
        v-if="isShowManagersSelect"
        @select-current-manager="selectCurrentManager"
        @close="isShowManagersSelect = false"
        @set-uids="candidateUids = $event"
        :uids="candidateUids"
      />
    </base-message-form>
  </div>
</template>

<script lang="ts">
import { Component, Emit, Inject, Vue } from 'vue-property-decorator'
import { date, QSlideTransition } from 'quasar'
import { TaskType } from '@/widgets/tasks/types/Task'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { ResponseErrors, User } from '@/types'
import { NotifyHelper } from '@/helpers'
import CategoriesSelect from '@/widgets/tasks/components/form/CategoriesSelect.vue'
import UiInputMaterial from '@/lib-components/form/UiInputMaterial.vue'
import ClientService from '@/widgets/tasks/http/services/ClientService'
import DatePicker from '@/widgets/tasks/components/form/date-picker/DatePicker.vue'
import FileAttachBtn from '@/widgets/base/components/message-form/FileAttachBtn.vue'
import NewTaskFiles from '@/widgets/tasks/components/form/NewTaskFiles.vue'
import { CreateNoteDto } from '@/widgets/tasks/http/dto/CreateNoteDto'
import { CreateTaskDto } from '@/widgets/tasks/http/dto/CreateTaskDto'
import UiFlash from '@/lib-components/UiFlash.vue'
import TaskLevelMenu from '@/widgets/tasks/components/form/TaskLevelMenu.vue'
import BaseMessageForm from '@/widgets/base/components/message/BaseMessageForm.vue'
import ClientForm from '@/widgets/base/components/client-form/ClientForm.vue'
import UiUserAvatar from '@/lib-components/UiUserAvatar.vue'
import ManagerAvatars from '@/widgets/base/components/manager-avatars/ManagerAvatars.vue'
import TaskManagerAvatars from '@/widgets/tasks/components/common/TaskManagerAvatars.vue'
import TaskManagerSelect from '@/widgets/tasks/components/common/TaskManagerSelect.vue'
import { TaskUserModule } from '@/widgets/tasks/modules/TaskUserModule'

@Component({
  components: {
    QSlideTransition,
    TaskManagerSelect,
    TaskManagerAvatars,
    ManagerAvatars,
    UiUserAvatar,
    TaskLevelMenu,
    UiFlash,
    NewTaskFiles,
    FileAttachBtn,
    ClientForm,
    DatePicker,
    UiInputMaterial,
    CategoriesSelect,
    BaseMessageForm,
  },
})
export default class NewTaskForm extends Vue {
  @Inject('TaskModule')
  taskModule!: TaskModule

  @Inject('TaskUserModule')
  userModule!: TaskUserModule

  isShowPreview = false
  isLoading = false
  isShowManagersSelect = false
  errors: ResponseErrors = {}

  currentType = TaskType.task
  categoryId: number | null = null
  candidateUids: string[] = []
  clientId: number | null = null
  text = ''
  orderName = ''
  level = 0
  files: File[] = []
  executeUntilDate: Date = date.addToDate(new Date(), { minutes: 10 })

  created() {
    this.orderName = this.taskModule.orderName || ''
  }

  get types() {
    const types: Partial<{ [key in TaskType]: string }> = {
      [TaskType.task]: 'Задача',
    }

    if (this.orderName) {
      types[TaskType.note] = 'Заметка'
    }

    return types
  }

  get isTaskType(): boolean {
    return TaskType.task === this.currentType
  }

  get searchClientFn() {
    return ClientService.searchClients
  }

  get errorsAsArray(): string[] {
    return Object.values(this.errors)
  }

  get getClientById() {
    return ClientService.getClientById
  }

  get getClientByOrderName() {
    return ClientService.getClientByOrderName
  }

  get getOrdersByClientId() {
    return ClientService.getOrdersByClientId
  }

  showPreview(value: boolean) {
    this.isShowPreview = value
  }

  clear() {
    this.isShowPreview = false
    this.isLoading = false
    this.isShowManagersSelect = false
    this.errors = {}

    this.currentType = TaskType.task
    this.categoryId = null
    this.candidateUids = []
    this.clientId = null
    this.text = ''
    this.orderName = this.taskModule.orderName || ''
    this.level = 0
    this.files = []
    this.executeUntilDate = date.addToDate(new Date(), { minutes: 10 })
  }

  selectCurrentManager() {
    this.candidateUids = [(this.userModule.user as User).id]
    this.isShowManagersSelect = false
  }

  setFiles(files: File[]) {
    this.files = [...this.files, ...files]
  }

  createNewTask() {
    let payload: CreateTaskDto | CreateNoteDto

    if (this.currentType === TaskType.note) {
      payload = {
        text: this.text,
        files: this.files,
        type: TaskType.note,
      }
    } else {
      payload = {
        text: this.text,
        files: this.files,
        type: TaskType.task,
        categoryId: this.categoryId,
        clientId: this.clientId,
        orderName: this.orderName,
        level: this.level,
        candidateUids: this.candidateUids,
        executeUntil: Math.floor(this.executeUntilDate.getTime() / 1000),
      }
    }

    this.isLoading = true

    this.taskModule
      .createTask(payload)
      .then(task => {
        NotifyHelper.success('Задача сохранена')

        this.taskModule.addTaskToList(task)
        this.save()
      })
      .catch(error => {
        if (error.response.data.errors) {
          this.errors = error.response.data.errors
        } else {
          NotifyHelper.serverError()
        }
      })
      .finally(() => (this.isLoading = false))
  }

  @Emit()
  save() {
    this.clear()

    return true
  }

  @Emit()
  cancel() {
    this.clear()

    return true
  }
}
</script>
