<template>
  <div class="relative-position">
    <base-message
      @show-overlay="isShowOverlay = true"
      @hide-overlay="isShowOverlay = false"
      v-if="!isShowEditForm"
      :text="task.text"
      :class="{ 'bg-yellow-1': isNoteType }"
    >
      <template #title>
        <div class="flex full-width">
          <div :class="{ 'text-negative': !isFinishedTasks && isUntil }">
            {{ title }}
          </div>
        </div>
      </template>
      <template #subtitle v-if="!isOwnTask">
        <div class="flex no-wrap items-center">
          <ui-user-avatar :user="creatorManager" size="16px" class="q-mr-xs">
            <q-tooltip>{{ creatorManager | userFullName }}</q-tooltip>
          </ui-user-avatar>
          <span class="text-small">{{ subtitleText }}</span>
        </div>
      </template>
      <template #left-panel>
        <q-icon
          v-if="isNoteType"
          name="la la-sticky-note"
          color="warning"
          size="32px"
          :class="{ 'no-pointer-events': !isOwnTask }"
        />
        <task-status-toggle
          @toggle-status="toggleStatus"
          v-else
          :task="task"
          :manager="currentManager"
          :class="{ 'no-pointer-events': !currentUserIsPerformer }"
        />
      </template>
      <template v-if="!isNoteType" #right-panel>
        <task-manager-avatars
          @click="isShowManagersSelect = true"
          :selected-uids="candidateUids"
        />
        <task-level-menu @change="setLevel" :current-level="task.level" />
      </template>
      <template #after-text>
        <order-info v-if="task.orderName" :task="task" />
        <task-files
          v-if="task.attachments.length > 0"
          :files="task.attachments"
        />
        <comment-form :task="task" />
        <task-comments
          v-if="task.comments.length > 0"
          :comments="task.comments"
          :current-manager="currentManager"
        />
      </template>
      <template #overlay v-if="hasControls">
        <task-controls
          @edit="isShowEditForm = true"
          @cancel="isShowEditForm = false"
          @remove="removeTask"
          :task="task"
          :manager="currentManager"
        />
      </template>
    </base-message>
    <edit-task-form
      @save="hideEditForm"
      @cancel="hideEditForm"
      v-else
      :task="task"
    />
    <task-manager-select
      v-if="isShowManagersSelect"
      @select-current-manager="selectCurrentManager"
      @close="isShowManagersSelect = false"
      @set-uids="setCandidates"
      :uids="candidateUids"
    />
  </div>
</template>

<script lang="ts">
import { Component, Inject, Prop, Vue } from 'vue-property-decorator'
import { Task, TaskType } from '@/widgets/tasks/types/Task'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { getPrettyTime } from '@/widgets/tasks/helpers/TaskDateHelper'
import { UserService } from '@/services'
import { ManagerModule } from '@/widgets/tasks/modules/ManagerModule'
import { Manager } from '@/types/Manager'
import { RouteNames } from '@/widgets/tasks/router/routeNames'
import { NotifyHelper } from '@/helpers'
import DateHelper from '@/helpers/DateHelper'
import UiUserAvatar from '@/lib-components/UiUserAvatar.vue'
import TaskLevel from '@/widgets/tasks/components/tasks/task/TaskLevel.vue'
import TaskStatusToggle from '@/widgets/tasks/components/tasks/task/TaskStatusToggle.vue'
import TaskControls from '@/widgets/tasks/components/tasks/task/TaskControls.vue'
import UiInputMaterial from '@/lib-components/form/UiInputMaterial.vue'
import EditTaskForm from '@/widgets/tasks/components/form/EditTaskForm.vue'
import TaskFiles from '@/widgets/tasks/components/common/TaskFiles.vue'
import TaskEditHelper from '@/widgets/tasks/helpers/TaskEditHelper'
import CommentForm from '@/widgets/tasks/components/tasks/task/CommentForm.vue'
import TaskComments from '@/widgets/tasks/components/tasks/task/TaskComments.vue'
import BaseMessage from '@/widgets/base/components/message/BaseMessage.vue'
import OrderInfo from '@/widgets/tasks/components/tasks/task/OrderInfo.vue'
import TaskManagerAvatars from '@/widgets/tasks/components/common/TaskManagerAvatars.vue'
import TaskManagerSelect from '@/widgets/tasks/components/common/TaskManagerSelect.vue'
import TaskLevelMenu from '@/widgets/tasks/components/form/TaskLevelMenu.vue'
import { TaskUserModule } from '@/widgets/tasks/modules/TaskUserModule'
import { QIcon, QTooltip } from 'quasar'

@Component({
  components: {
    QTooltip,
    QIcon,
    TaskLevelMenu,
    TaskManagerSelect,
    TaskManagerAvatars,
    OrderInfo,
    TaskComments,
    CommentForm,
    EditTaskForm,
    UiInputMaterial,
    TaskControls,
    TaskStatusToggle,
    TaskLevel,
    TaskFiles,
    UiUserAvatar,
    BaseMessage,
  },
})
export default class TaskListItem extends Vue {
  @Prop({ type: Object, required: true })
  task!: Task

  @Inject('TaskUserModule')
  userModule!: TaskUserModule

  @Inject('TaskModule')
  taskModule!: TaskModule

  @Inject('ManagerModule')
  managerModule!: ManagerModule

  isShowOverlay = false
  isShowEditForm = false
  isShowManagersSelect = false

  get candidateUids(): string[] {
    return this.task.candidateUids.length
      ? this.task.candidateUids
      : this.task.performerUid
      ? [this.task.performerUid]
      : []
  }

  get title(): string {
    return getPrettyTime(this.task, this.isSearch, this.isUntil)
  }

  get subtitleText() {
    return `${UserService.getUserFullName(
      this.creatorManager
    )}, ${DateHelper.format(this.task.createdAt)}`
  }

  get creatorManager(): Manager {
    return this.managerModule.getManagerByUid(this.task.creatorUid)
  }

  get currentManager(): Manager {
    return this.userModule.user as Manager
  }

  get isOwnTask(): boolean {
    const user = this.userModule.user as Manager

    return user.id === this.task.creatorUid
  }

  get currentUserIsPerformer(): boolean {
    const user = this.userModule.user as Manager

    return user.id === this.task.performerUid
  }

  get isSearch(): boolean {
    return this.$route.name === RouteNames.search
  }

  get isEditable(): boolean {
    return TaskEditHelper.isEditAllowed(this.task, this.currentManager)
  }

  get hasControls(): boolean {
    return this.isEditable && this.isShowOverlay
  }

  get isNoteType(): boolean {
    return this.task.type === TaskType.note
  }

  get isUntil() {
    const currentDate = new Date()
    const targetDate = DateHelper.getDateFromTimestamp(this.task.executeUntil)

    return currentDate.getTime() > targetDate.getTime()
  }

  get isFinishedTasks(): boolean {
    return this.$route.name === RouteNames.finishedTasks
  }

  selectCurrentManager() {
    this.task.candidateUids = [this.currentManager.id]
    this.isShowManagersSelect = false
    this.saveTask()
  }

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

    this.task.candidateUids = uids
    this.saveTask()
  }

  setLevel(level: number) {
    this.task.level = level
    this.saveTask()
  }

  private saveTask() {
    this.taskModule
      .updateTask(this.task)
      .catch(() => NotifyHelper.serverError())
  }

  hideEditForm() {
    this.isShowEditForm = false
    this.isShowOverlay = false
  }

  removeTask() {
    this.taskModule.removeTask(this.task.id)
  }

  toggleStatus(task: Task) {
    if (this.$route.name === RouteNames.finishedTasks) {
      if (!task.finishedAt) {
        this.taskModule.removeTaskFromList(task.id)
      }
    } else {
      if (task.finishedAt) {
        this.taskModule.removeTaskFromList(task.id)
      }
    }
  }
}
</script>
