<template>
  <view class="app-container pb-20">
    <TopBar title="当班人员" show-back />
    
    <!-- 筛选 -->
    <view class="bg-white px-4 py-3">
      <uni-segmented-control 
        :current="currentIndex" 
        :values="teams.map(t => t.label)"
        style-type="text"
        active-color="#4f8ef7"
        @clickItem="onTabChange"
      />
    </view>

    <!-- 当班人员列表 -->
    <view class="px-4 mt-3">
      <view v-if="loading" class="py-10 text-center">
        <text class="text-gray-400">加载中...</text>
      </view>
      
      <view v-else-if="filteredStaff.length === 0">
        <EmptyState message="暂无当班人员" />
      </view>
      
      <uni-list v-else border>
        <uni-list-item 
          v-for="staff in filteredStaff" 
          :key="staff.staffId"
          :title="staff.name"
          :note="(staff.phone || '') + ' | ' + (staff.teamName || '未分配班组')"
          :right-text="getStatusText(staff.status)"
        >
          <template #header>
            <view class="w-10 h-10 rounded-full bg-blue-50 flex items-center justify-center mr-3">
              <text class="uni-icons uniui-person-filled text-blue-500"></text>
            </view>
          </template>
        </uni-list-item>
      </uni-list>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import TopBar from '../../components/common/TopBar.vue'
import EmptyState from '../../components/common/EmptyState.vue'
import UniSegmentedControl from '../../components/uni-segmented-control/uni-segmented-control.vue'
import UniList from '../../components/uni-list/uni-list.vue'
import UniListItem from '../../components/uni-list/uni-list-item.vue'
import { getStaffList } from '../../api/staff'

const loading = ref(false)
const staffList = ref<any[]>([])
const currentIndex = ref(0)

const teams = [
  { value: 'all', label: '全部' },
  { value: '一班', label: '工程一班' },
  { value: '二班', label: '工程二班' },
  { value: '三班', label: '工程三班' },
]

const filteredStaff = computed(() => {
  const filter = teams[currentIndex.value].value
  if (filter === 'all') return staffList.value.filter(s => s.status === 'on_duty' || s.status === 'working')
  return staffList.value.filter(s => (s.status === 'on_duty' || s.status === 'working') && s.teamName?.includes(filter))
})

function onTabChange(index: number) {
  currentIndex.value = index
}

function getStatusText(status: string) {
  const map: Record<string, string> = {
    on_duty: '在岗',
    working: '施工中',
  }
  return map[status] || status
}

onMounted(async () => {
  loading.value = true
  try {
    const res = await getStaffList()
    staffList.value = res.rows || []
  } catch (error) {
    console.error('获取人员列表失败:', error)
  } finally {
    loading.value = false
  }
})
</script>
