<template>
  <base-message-form
    @save="saveTask"
    @cancel="cancel"
    @change-type="model.type = $event"
    :loading="isLoading"
    :types="types"
    :current-type="model.type"
    submit-text="Сохранить"
  >
    <template #flash>
      <q-slide-transition>
        <ui-flash
          @close="errors = {}"
          v-if="errorsAsArray.length > 0"
          :items="errorsAsArray"
        />
      </q-slide-transition>
    </template>
    <template #title>
      <span class="text-h4">{{ types[model.type] }}</span>
    </template>
    <template v-if="isTaskType" #after-title>
      <task-manager-avatars
        @click="isShowManagersSelect = true"
        :selected-uids="model.candidateUids"
        class="q-mr-sm"
      />
      <task-level-menu
        @change="model.level = $event"
        :current-level="model.level"
      />
    </template>
    <template #body>
      <template v-if="isTaskType">
        <categories-select v-model="model.categoryId" :errors="errors" />
        <client-form
          @set-client-id="model.clientId = $event"
          @set-order-name="model.orderName = $event"
          :order-name="model.orderName"
          :client-id="model.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="model.text"
        autogrow
        label="Опишите задачу"
        name="text"
        autocomplete
        :errors="errors"
      />
      <date-picker
        v-model="executeUntilDate"
        v-if="isTaskType"
        hide-preview-picker
      />
      <file-attach-btn @change="setFiles" class="q-mt-md" />
      <task-files :files="model.attachments" is-editable />
      <new-task-files :files="files" />
    </template>
    <task-manager-select
      v-if="isShowManagersSelect"
      @select-current-manager="selectCurrentManager"
      @close="isShowManagersSelect = false"
      @set-uids="setCandidates"
      :uids="model.candidateUids"
    />
  </base-message-form>
</template>

<script lang="ts">
import { Component, Emit, Inject, Prop, Vue } from 'vue-property-decorator'
import { Task, TaskType } from '@/widgets/tasks/types/Task'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { Order } from '@/widgets/base/types/Order'
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 Client from '@/widgets/base/types/Client'
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 { Manager } from '@/types/Manager'
import { Category } from '@/widgets/tasks/types/Category'
import UiFlash from '@/lib-components/UiFlash.vue'
import { ResponseErrors, User } from '@/types'
import TaskLevelMenu from '@/widgets/tasks/components/form/TaskLevelMenu.vue'
import clone from 'clone-deep'
import DateHelper from '@/helpers/DateHelper'
import { NotifyHelper } from '@/helpers'
import TaskFiles from '@/widgets/tasks/components/common/TaskFiles.vue'
import BaseMessageForm from '@/widgets/base/components/message/BaseMessageForm.vue'
import ClientForm from '@/widgets/base/components/client-form/ClientForm.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'
import { QSlideTransition } from 'quasar'

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

  @Inject('TaskUserModule')
  userModule!: TaskUserModule

  @Prop({ type: Object, required: true })
  task!: Task

  isShowManagersSelect = false
  isLoading = false
  model: Task = {
    ...clone(this.task),
    candidateUids: this.task.performerUid
      ? [this.task.performerUid]
      : this.task.candidateUids,
  }

  types = {
    [this.model.type]: this.model.type === TaskType.task ? 'Задача' : 'Заметка',
  }

  errors: ResponseErrors = {}

  category: Category | null = null
  performer: Manager | null = null
  client: Client | null = null
  files: File[] = []

  orders: Order[] = []
  executeUntilDate = DateHelper.getDateFromTimestamp(this.model.executeUntil)

  get isTaskType(): boolean {
    return TaskType.task.toString() === this.model.type.toString()
  }

  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
  }

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

  setCandidates(uids: string[]) {
    if (uids.length === 0) {
      this.model.performerUid = ''
    }

    this.model.candidateUids = uids
  }

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

  saveTask() {
    this.isLoading = true

    this.taskModule
      .updateTask({
        ...this.model,
        files: this.files,
        executeUntil: Math.floor(this.executeUntilDate.getTime() / 1000),
      })
      .then(() => {
        NotifyHelper.success('Задача обновлена')
        this.save()
      })
      .finally(() => (this.isLoading = false))
  }

  @Emit()
  cancel() {
    return true
  }

  @Emit()
  save() {
    return true
  }
}
</script>
