<template>
  <view class="app-container pb-24">
    <TopBar :title="pageTitle" />

    <!-- 工具栏：搜索 + 新增 -->
    <view class="toolbar px-4 py-3 sticky top-0 z-40 flex items-center gap-2">
      <view class="search-box flex-1 min-w-0 flex items-center rounded-2xl px-4 py-2" :class="{ 'search-focus': focusedSearch }">
        <text class="uni-icons uniui-search search-icon mr-2 text-base"></text>
        <input
          class="flex-1 bg-transparent text-sm text-gray-800"
          placeholder="搜索项目/客户/故障位置"
          placeholder-class="search-ph"
          v-model="searchKeyword"
          confirm-type="search"
          @focus="focusedSearch = true"
          @blur="focusedSearch = false"
        />
      </view>
      <view
        v-if="config.publishPath && role !== 'dispatch'"
        class="add-btn w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0"
        hover-class="add-btn-hover"
        :hover-start-time="0"
        :hover-stay-time="120"
        @click="goToPublishTask"
      >
        <text class="uni-icons uniui-plusempty text-white text-xl"></text>
      </view>
    </view>

    <!-- 状态筛选标签（类似项目库） -->
    <scroll-view scroll-x class="filter-bar" :show-scrollbar="false" enhanced>
      <view class="flex items-center gap-2 px-4 py-3">
        <view
          v-for="(s, i) in filterStatuses"
          :key="s.value"
          class="filter-tab flex-shrink-0 rounded-full px-4 py-1.5 text-sm border"
          :class="i === currentFilterIndex ? 'filter-tab--active' : 'filter-tab--normal'"
          @click="onFilterTabClick(i)"
        >
          {{ s.label }}
        </view>
      </view>
    </scroll-view>

    <!-- 加载/空态 -->
    <view class="px-4 mt-3">
      <view v-if="taskStore.loading" class="py-10 text-center">
        <text class="loading-text">加载中...</text>
      </view>

      <view v-else-if="filteredTasks.length === 0">
        <EmptyState text="暂无任务" />
      </view>

      <!-- 销售端：任务卡片 -->
      <view v-else-if="role === 'sales'" class="gap-y-3">
        <SalesTaskCard
          v-for="task in filteredTasks"
          :key="taskIdOf(task)"
          :task="task"
          @click="goToDetail"
        />
      </view>

      <!-- 调度端：任务卡片 -->
      <view v-else-if="role === 'dispatch'" class="gap-y-3">
        <DispatchTaskCard
          v-for="task in filteredTasks"
          :key="taskIdOf(task)"
          :task="task"
          @click="goToDetail"
        />
      </view>

      <!-- 施工端：任务卡片 -->
      <view v-else class="gap-y-3">
        <ConstructionTaskCard
          v-for="task in filteredTasks"
          :key="taskIdOf(task)"
          :task="task"
          @click="goToDetail"
        />
      </view>
    </view>

  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useTaskStore } from '@/stores/task'
import TopBar from '@/components/common/TopBar.vue'
import SalesTaskCard from '@/components/task/SalesTaskCard.vue'
import DispatchTaskCard from '@/components/task/DispatchTaskCard.vue'
import ConstructionTaskCard from '@/components/task/ConstructionTaskCard.vue'
import EmptyState from '@/components/common/EmptyState.vue'

const props = defineProps<{
  role: 'sales' | 'dispatch' | 'construction'
}>()

const taskStore = useTaskStore()
const currentFilter = ref('all')
const searchKeyword = ref('')
const focusedSearch = ref(false)

const roleConfig: Record<string, { filterStatuses: { value: string; label: string }[]; detailPath: string; publishPath?: string }> = {
  sales: {
    filterStatuses: [
      { value: 'all', label: '全部' },
      { value: 'dispatching', label: '调度中' },
      { value: 'constructing', label: '施工中' },
      { value: 'completed', label: '已完成' },
      { value: 'emergency', label: '应急' },
    ],
    detailPath: '/subPackages/pages-common/taskDetail',
    publishPath: '/subPackages/pages-common/publishTask',
  },
  dispatch: {
    filterStatuses: [
      { value: 'all', label: '全部' },
      { value: 'auditing', label: '待审核' },
      { value: 'approved', label: '待安排' },
      { value: 'processing', label: '进行中' },
      { value: 'completed', label: '已完成' },
      { value: 'rejected', label: '已驳回' },
    ],
    detailPath: '/subPackages/pages-dispatch/taskDetail',
    publishPath: '/subPackages/pages-dispatch/publishTask',
  },
  construction: {
    filterStatuses: [
      { value: 'all', label: '全部' },
      { value: 'assigned', label: '待确认' },
      { value: 'in_progress', label: '进行中' },
      { value: 'completed', label: '已完成' },
      { value: 'cancelled', label: '已取消' },
    ],
    detailPath: '/subPackages/pages-construction/taskDetail',
  },
}

const config = computed(() => roleConfig[props.role] || roleConfig.sales)
const filterStatuses = computed(() => config.value.filterStatuses)
const currentFilterIndex = computed(() => {
  const idx = filterStatuses.value.findIndex(s => s.value === currentFilter.value)
  return idx >= 0 ? idx : 0
})
const detailPath = computed(() => config.value.detailPath)

const pageTitle = computed(() => {
  if (props.role === 'sales') return '我的任务'
  if (props.role === 'dispatch') return '任务管理'
  return '我的任务'
})

const publishText = computed(() => {
  if (props.role === 'sales') return '发布'
  if (props.role === 'dispatch') return '新增'
  return '发布'
})

const filteredTasks = computed(() => {
  let list = taskStore.tasks
  if (currentFilter.value !== 'all') {
    if (currentFilter.value === 'dispatching') list = list.filter(t => ['confirmed', 'scheduled'].includes(t.status))
    else if (currentFilter.value === 'auditing') list = list.filter(t => ['auditing', 'pending'].includes(t.status))
    else if (currentFilter.value === 'approved') list = list.filter(t => (t.status as string) === 'approved')
    else if (currentFilter.value === 'processing') list = list.filter(t => ['scheduled', 'departed', 'arrived', 'constructing', 'assigned', 'in_progress'].includes(t.status))
    else if (currentFilter.value === 'emergency') list = list.filter(t => t.type === 'emergency')
    else list = list.filter(t => t.status === currentFilter.value)
  }
  const kw = searchKeyword.value.trim()
  if (kw) {
    list = list.filter(t =>
      [t.projectName, t.customerName, t.faultLocation, t.address]
        .filter(Boolean)
        .some(s => String(s).includes(kw))
    )
  }
  return list
})

function onFilterTabClick(index: number) {
  const item = filterStatuses.value[index]
  if (item) currentFilter.value = item.value
}

function taskIdOf(task: any): string {
  return String(task?.id ?? task?.taskId ?? '')
}

function goToDetail(taskId: string) {
  if (!taskId) return
  taskStore.setCurrentTask(taskId)
  uni.navigateTo({ url: `${detailPath.value}?id=${taskId}` })
}

function goToPublishTask() {
  if (!config.value.publishPath) return
  uni.navigateTo({ url: config.value.publishPath })
}

function refresh() {
  if (props.role === 'construction') {
    return taskStore.fetchMyTasks()
  }
  return taskStore.fetchTasks()
}

defineExpose({ refresh })
</script>

<style scoped>
/* 工具栏：云雾白磨砂条，底部浅绿分割线，衔接 TopBar 与卡片区 */
.toolbar {
  background-color: rgba(246, 251, 249, 0.88);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-bottom: 1px solid rgba(164, 216, 152, 0.28);
}

/* 搜索框：默认白底浅灰描边，聚焦时青山绿强调 */
.search-box {
  background-color: #ffffff;
  border: 1px solid #e5e7eb;
  transition: border-color 0.15s ease, box-shadow 0.15s ease, background-color 0.15s ease;
}
.search-focus {
  background-color: #ffffff;
  border-color: #368f6f;
  box-shadow: 0 0 0 3px rgba(164, 216, 152, 0.30);
}
.search-icon {
  color: #9ca3af;
}
.search-ph {
  color: #9ca3af;
}

/* 新增按钮：青山绿→流水青渐变 + 柔绿阴影 */
.add-btn {
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  box-shadow: 0 8px 18px -8px rgba(54, 143, 111, 0.55);
}
.add-btn-hover {
  opacity: 0.92;
  transform: scale(0.94);
}

.loading-text {
  color: #6b7280;
}

.filter-bar {
  background-color: rgba(246, 251, 249, 0.88);
  border-bottom: 1px solid rgba(164, 216, 152, 0.20);
  white-space: nowrap;
}
.filter-tab {
  transition: all 0.15s ease;
}
.filter-tab--normal {
  background-color: #ffffff;
  border-color: #e5e7eb;
  color: #4b5563;
}
.filter-tab--active {
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  border-color: transparent;
  color: #ffffff;
  box-shadow: 0 6px 14px -8px rgba(54, 143, 111, 0.6);
}
</style>
