<template>
  <view class="app-container task-page pb-16">
    <TaskListView ref="taskListRef" :role="role" />
    <!-- #ifdef H5 || APP-PLUS -->
    <AppTabBar />
    <!-- #endif -->
  </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 { safeHideTabBar } from '@/utils'
import TaskListView from '@/components/task/TaskListView.vue'
// #ifdef H5 || APP-PLUS
import AppTabBar from '@/components/common/AppTabBar.vue'
// #endif

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

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

function loadTasks() {
  if (authStore.userRole === 'construction') {
    return taskStore.fetchMyTasks()
  }
  return taskStore.fetchTasks()
}

onLoad(() => {
  loadTasks()
})

onShow(() => {
  loadTasks()
  // #ifdef H5 || APP-PLUS
  safeHideTabBar({ animation: false, repeat: 10 })
  // #endif
  // #ifdef MP-WEIXIN
  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)
  // #endif
})

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

<style scoped>
.task-page {
  background-color: #f6fbf9;
}
</style>
