<template>
  <view
    class="task-card clickable"
    hover-class="scale-down"
    :hover-start-time="0"
    :hover-stay-time="150"
    :class="{ 'is-emergency': isEmergency }"
    @click="$emit('click', String((task as any).id ?? (task as any).taskId ?? ''))"
  >
    <!-- 顶部：项目名/标签 + 状态 -->
    <view class="task-header">
      <view class="flex items-center gap-2 min-w-0">
        <text class="project-name truncate">{{ projectNameText }}</text>
        <view v-if="coopTagText" class="tag coop-tag">{{ coopTagText }}</view>
        <view v-if="isEmergency" class="tag emergency-tag">应急</view>
        <view v-else-if="urgentText" class="tag" :class="urgentClass">{{ urgentText }}</view>
      </view>
      <StatusTag :status="task.status" />
    </view>

    <!-- 信息行 -->
    <view class="info-list">
      <view class="info-row">
        <text class="uni-icons uniui-gear-filled info-icon"></text>
        <text class="info-text">{{ serviceTypeText }}</text>
      </view>
      <view class="info-row">
        <text class="uni-icons uniui-calendar-filled info-icon"></text>
        <text class="info-text">服务时间：{{ serviceTimeText }}</text>
      </view>
      <view class="info-row">
        <text class="uni-icons uniui-location-filled info-icon"></text>
        <text class="info-text truncate">{{ task.address || '暂无地址' }}</text>
      </view>
    </view>

    <!-- 当前步骤 + 流程进度 -->
    <view class="step-box">
      <view class="step-box-header">
        <text class="step-box-label">当前步骤</text>
        <text class="step-box-value" :style="{ color: stepColor }">{{ currentStepLabel }}</text>
      </view>
      <view class="flow-progress">
        <view
          v-for="(step, i) in flowSteps"
          :key="i"
          class="flow-step"
          :class="{ 'completed': step.completed, 'active': step.active }"
        >
          <view class="step-icon">
            <text v-if="step.completed" class="uni-icons uniui-checkmarkempty step-check"></text>
            <text v-else-if="step.active" class="uni-icons uniui-reload step-spinner"></text>
            <text v-else class="step-number-text">×</text>
          </view>
          <text class="step-label">{{ step.label }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import StatusTag from '../common/StatusTag.vue'
import type { Task } from '@/types'
import { formatDate, getConstructionTypeText, getCooperationTypeText } from '@/utils'
import { getTaskPhotos, type TaskPhoto } from '@/api/file'
import {
  FLOW_STEPS,
  RECORD_STEPS,
  isRecordStepComplete,
  completedRecordStepCount,
  computeCurrentStepIndex,
  getFlowStepState,
} from '@/constants/sop'

const props = defineProps<{
  task: Task
}>()

defineEmits<{
  click: [taskId: string]
}>()

const taskId = computed(() => Number((props.task as any).id ?? (props.task as any).taskId ?? 0))

const isEmergency = computed(() => (props.task.taskType || props.task.type) === 'emergency')

const projectNameText = computed(() => {
  return props.task.projectName || (props.task as any).taskName || '未命名任务'
})

const coopTagText = computed(() => {
  return getCooperationTypeText(props.task.coopType || (props.task as any).cooperationType)
})

const urgentText = computed(() => {
  if (props.task.urgent === 'high' || props.task.urgent === 'very_urgent' || props.task.urgencyLevel === 'high') return '加急'
  return ''
})

const urgentClass = computed(() => {
  return 'urgent-tag'
})

const serviceTypeText = computed(() => {
  const raw = props.task.serviceType || (props.task as any).constructionType
  return raw ? getConstructionTypeText(raw) : '施工服务'
})

const serviceTimeText = computed(() => {
  const date = props.task.serviceDate || props.task.scheduleDate || props.task.planDate || ''
  const time = props.task.serviceTime || props.task.scheduleTime || ''
  if (date && time) return `${date} ${time}`
  if (date) return date
  if ((props.task as any).expectedArrivalTime) return formatDate((props.task as any).expectedArrivalTime, 'MM-DD HH:mm')
  return '待定'
})

const photos = ref<TaskPhoto[]>([])
const photoLoading = ref(false)

const completedRecordStepCountValue = computed(() => completedRecordStepCount(photos.value))

/** 当前进行到的步骤索引（与任务详情页顶部流程条完全对齐） */
const currentStepIndex = computed(() => computeCurrentStepIndex(props.task, photos.value))

const currentStepLabel = computed(() => {
  if (props.task.status === 'completed') return '已完成'
  if (props.task.status === 'cancelled') return '已取消'
  if (props.task.status === 'rejected') return '已拒绝'
  const idx = currentStepIndex.value
  return FLOW_STEPS[idx - 1]?.title || '待确认'
})

const stepColor = computed(() => {
  const status = props.task.status
  if (status === 'completed') return '#10b981'
  if (status === 'cancelled' || status === 'rejected') return '#ef4444'
  return '#3b82f6'
})

/** 每个流程步骤的状态（与任务详情页 getFlowStepState 对齐，支持非连续完成） */
const flowSteps = computed(() => {
  return FLOW_STEPS.map((s, i) => {
    const uiStep = i + 1
    const state = getFlowStepState(props.task, photos.value, uiStep)
    return {
      label: s.title,
      completed: state === 'completed',
      active: state === 'current',
    }
  })
})

async function loadPhotos() {
  if (!taskId.value) return
  if (props.task.status === 'completed' || props.task.status === 'cancelled' || props.task.status === 'rejected') return
  photoLoading.value = true
  try {
    photos.value = await getTaskPhotos(taskId.value)
  } catch (e) {
    console.error('加载任务照片失败', e)
  } finally {
    photoLoading.value = false
  }
}

onMounted(() => {
  loadPhotos()
})

watch(() => props.task, () => {
  loadPhotos()
}, { deep: false })
</script>

<style scoped>
.task-card {
  background: #ffffff;
  border-radius: 24rpx;
  padding: 32rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  transition: transform 0.15s ease;
}
.task-card.is-emergency {
  border-left: 8rpx solid #ef4444;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
}
.project-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #333333;
  line-height: 1.4;
  max-width: 60%;
}
.tag {
  display: inline-flex;
  align-items: center;
  padding: 4rpx 12rpx;
  border-radius: 6rpx;
  font-size: 22rpx;
  line-height: 1;
  flex-shrink: 0;
}
.coop-tag {
  background: #f3e8ff;
  color: #9333ea;
}
.emergency-tag {
  background: #fef2f2;
  color: #dc2626;
}
.urgent-tag {
  background: #fff7ed;
  color: #ea580c;
}

.info-list {
  margin-bottom: 24rpx;
}
.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 12rpx;
}
.info-row:last-child {
  margin-bottom: 0;
}
.info-icon {
  color: #9ca3af;
  font-size: 24rpx;
  margin-right: 16rpx;
  width: 40rpx;
  text-align: center;
}
.info-text {
  font-size: 26rpx;
  color: #666666;
  flex: 1;
}

.step-box {
  background: #eff6ff;
  border-radius: 16rpx;
  padding: 24rpx;
}
.step-box-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}
.step-box-label {
  font-size: 24rpx;
  color: #6b7280;
}
.step-box-value {
  font-size: 24rpx;
  font-weight: 500;
  color: #3b82f6;
}

.flow-progress {
  display: flex;
  justify-content: space-between;
  position: relative;
  padding: 0 6rpx;
}
.flow-progress::before {
  content: '';
  position: absolute;
  top: 15rpx;
  left: 24rpx;
  right: 24rpx;
  height: 3rpx;
  background: #dbeafe;
}
.flow-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  z-index: 1;
  position: relative;
  flex: 1;
  min-width: 0;
}
.step-icon {
  width: 30rpx;
  height: 30rpx;
  border-radius: 50%;
  background: #dbeafe;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 8rpx;
}
.flow-step.completed .step-icon {
  background: #3b82f6;
  color: #ffffff;
}
.flow-step.active .step-icon {
  background: #3b82f6;
  color: #ffffff;
  box-shadow: 0 0 0 8rpx rgba(59, 130, 246, 0.3);
}
.step-check {
  font-size: 20rpx;
  color: #ffffff;
}
.step-spinner {
  font-size: 18rpx;
  color: #ffffff;
}
.step-number-text {
  font-size: 18rpx;
  color: #93c5fd;
}
.step-label {
  font-size: 18rpx;
  color: #9ca3af;
  text-align: center;
  transform: scale(0.9);
}
.flow-step.completed .step-label,
.flow-step.active .step-label {
  color: #3b82f6;
  font-weight: 500;
}

.scale-down {
  transform: scale(0.96);
  transition: transform 0.15s ease;
}
</style>
