<template>
  <widget-layout :is-loading="isLoading">
    <template #bar>
      <tasks-bar :order-name="orderName" />
    </template>
  </widget-layout>
</template>

<script lang="ts">
import { Component, Prop, Provide, Vue } from 'vue-property-decorator'
import { getModule } from 'vuex-module-decorators'
import { ManagerModule } from '@/widgets/tasks/modules/ManagerModule'
import { TaskModule } from '@/widgets/tasks/modules/TaskModule'
import { CategoryModule } from '@/widgets/tasks/modules/CategoryModule'
import WidgetLayout from '@/widgets/base/components/widget-layout/WidgetLayout.vue'
import TasksBar from '@/widgets/tasks/components/bar/TasksBar.vue'
import { TaskUserModule } from '@/widgets/tasks/modules/TaskUserModule'
import { Manager } from '@/types/Manager'
import AuthService from '@/widgets/tasks/http/services/AuthService'
import { BaseWidgetLayout } from '@/widgets/base/BaseWidgetLayout'
import { TasksRouteNames } from '@/widgets'

@Component({
  components: { TasksBar, WidgetLayout },
})
export default class TasksLayout extends BaseWidgetLayout {
  @Provide('ManagerModule')
  managerModule: ManagerModule = getModule(ManagerModule, this.$store)

  @Provide('TaskModule')
  taskModule: TaskModule = getModule(TaskModule, this.$store)

  @Provide('TaskUserModule')
  userModule: TaskUserModule = getModule(TaskUserModule, this.$store)

  @Provide('CategoryModule')
  categoryModule: CategoryModule = getModule(CategoryModule, this.$store)

  @Prop(String)
  orderName?: string

  isLoading = false

  async created() {
    this.isLoading = true

    if (this.orderName) {
      this.taskModule.setOrderName(this.orderName)

      if (this.$route.params.orderName !== this.orderName) {
        await this.$router.push({
          name: TasksRouteNames.orderTasks,
          params: { orderName: this.orderName },
        })
      }
    }

    await AuthService.getAuthToken()

    await Promise.all([
      this.userModule.loadUser(),
      this.managerModule.loadManagers(),
      this.categoryModule.loadCategories(),
      this.categoryModule.loadCounting(),
    ])

    this.isLoading = false

    const user = this.userModule.user as Manager

    if (user) {
      await this.taskModule.initWebsocket(user)
      await this.categoryModule.initWebsocket(user)
    }
  }
}
</script>
