<template>
  <view class="app-container">
    <TaskListView ref="taskListRef" :role="role" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad, onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { useAuthStore } from '@/stores/auth'
import { useTaskStore } from '@/stores/task'
import TaskListView from '@/components/task/TaskListView.vue'

const authStore = useAuthStore()
const taskStore = useTaskStore()
const taskListRef = ref<InstanceType<typeof TaskListView> | null>(null)

const role = computed(() => (authStore.userRole as 'sales' | 'dispatch' | 'construction') || 'sales')

onLoad(() => {
  taskStore.fetchTasks()
})

onShow(() => {
  taskStore.fetchTasks()
  const pages = getCurrentPages()
  const page = pages[pages.length - 1] as any
  const role = authStore.userRole
  const index = role === 'dispatch' ? 2 : 1
  page?.getTabBar?.()?.setSelected?.(index)
})

onPullDownRefresh(async () => {
  await taskStore.fetchTasks()
  uni.stopPullDownRefresh()
})
</script>
