<template>
  <view class="sub-page">
    <TopBar title="任务详情" show-back />

    <view v-if="loading" class="py-10 text-center">
      <text class="empty-text">加载中...</text>
    </view>

    <view v-else-if="task" class="px-4 pt-3">
      <!-- 任务状态卡片 -->
      <view class="glass-card p-4">
        <view class="flex justify-between items-start mb-3">
          <view class="flex-1 min-w-0 mr-2">
            <text class="notice-title">{{ taskTitle }}</text>
            <view class="mt-2 flex items-center">
              <StatusTag :status="task.status" />
              <text v-if="isEmergency" class="emergency-tag ml-2">应急</text>
            </view>
          </view>
          <text class="meta-text flex-shrink-0">{{ task.taskNo }}</text>
        </view>
        <view v-if="task.address" class="meta-line mb-2">
          <text class="uni-icons uniui-location-filled meta-icon mr-2"></text>
          <text class="meta-value flex-1">{{ task.address }}</text>
        </view>
        <view class="meta-line">
          <text class="uni-icons uniui-clock-filled meta-icon mr-2"></text>
          <text class="meta-value">{{ serviceTimeText }}</text>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">基本信息</text>
        </view>
        <view class="info-row">
          <text class="info-label">服务类型</text>
          <text class="info-value">{{ constructionTypeText }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">客户名称</text>
          <text class="info-value">{{ customerName }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">联系电话</text>
          <view class="flex items-center">
            <text class="info-value mr-2">{{ customerPhone || '-' }}</text>
            <button
              v-if="customerPhone"
              class="phone-circle"
              @click="callPhone(customerPhone)"
            >
              <text class="uni-icons uniui-phone-filled phone-icon"></text>
            </button>
          </view>
        </view>
        <view class="info-row">
          <text class="info-label">项目地址</text>
          <text class="info-value info-value-left">{{ task.address || '-' }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">预约时间</text>
          <text class="info-value">{{ serviceTimeText }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">紧急程度</text>
          <text class="info-value" :class="isEmergency ? 'urgent-text' : 'normal-text'">
            {{ urgencyText }}
          </text>
        </view>
      </view>

      <!-- 服务点信息 -->
      <view v-if="servicePoints.length > 0" class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">服务点信息</text>
        </view>
        <view
          v-for="(point, index) in servicePoints"
          :key="index"
          class="point-row"
        >
          <view class="flex justify-between items-center mb-2">
            <text class="point-name">{{ point.name }}</text>
            <text v-if="point.serviceType" class="type-tag">{{ point.serviceType }}</text>
          </view>
          <view v-if="point.address" class="flex items-center">
            <text class="uni-icons uniui-location-filled meta-icon mr-1"></text>
            <text class="meta-text">{{ point.address }}</text>
          </view>
        </view>
      </view>

      <!-- 处理记录 -->
      <view class="glass-card">
        <view class="section-head">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">处理记录</text>
        </view>
        <view class="pb-3 px-2">
          <Timeline :records="timelineRecords" />
        </view>
      </view>
    </view>

    <EmptyState v-else message="任务不存在" />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { useTaskStore } from '@/stores/task'
import TopBar from '@/components/common/TopBar.vue'
import StatusTag from '@/components/common/StatusTag.vue'
import EmptyState from '@/components/common/EmptyState.vue'
import Timeline from '@/components/common/Timeline.vue'
import type { TimelineRecord } from '@/components/common/Timeline.vue'
import { getTaskDetail } from '@/api/task'
import { getProjectDetail } from '@/api/project'
import { formatDate } from '@/utils'
import type { ServicePoint } from '@/types'

const taskStore = useTaskStore()

const task = ref<any>(null)
const project = ref<any>(null)
const loading = ref(false)

const extra = computed(() => {
  if (!task.value?.extraData) return {} as any
  try {
    return JSON.parse(task.value.extraData)
  } catch {
    return {} as any
  }
})

const taskTitle = computed(() => {
  const t = task.value
  if (!t) return ''
  return t.taskName || extra.value.projectName || t.faultLocation || '未命名任务'
})

const isEmergency = computed(() => {
  const t = task.value
  if (!t) return false
  return t.taskType === 'emergency' || ['urgent', 'very_urgent'].includes(t.urgencyLevel)
})

const urgencyText = computed(() => {
  const map: Record<string, string> = { normal: '普通', urgent: '紧急', very_urgent: '特急' }
  const level = task.value?.urgencyLevel
  return level ? map[level] || level : '普通'
})

const constructionTypeText = computed(() => {
  const t = task.value
  if (!t) return '-'
  const map: Record<string, string> = { dredge: '疏通', clean: '清掏', inspect: '排查', repair: '维修', emergency: '应急' }
  return t.constructionType || (t.taskType ? map[t.taskType] || t.taskType : '-')
})

const serviceTimeText = computed(() => {
  const t = task.value
  if (!t) return '待定'
  const date = t.planDate || ''
  const rangeMap: Record<string, string> = { morning: '上午', afternoon: '下午', evening: '晚上' }
  const range = rangeMap[t.planTimeRange] || t.planTimeRange || ''
  return date || range ? `${date} ${range}`.trim() : '待定'
})

const customerName = computed(() => {
  return project.value?.customerName || extra.value.customerName || project.value?.primaryContactName || '-'
})

const customerPhone = computed(() => {
  return project.value?.customerPhone || extra.value.customerPhone || project.value?.primaryContactPhone || ''
})

const servicePoints = computed<ServicePoint[]>(() => {
  const raw = project.value?.servicePoints
  if (!raw) return []
  try {
    const list = typeof raw === 'string' ? JSON.parse(raw) : raw
    return Array.isArray(list) ? list : []
  } catch {
    return []
  }
})

const timelineRecords = computed<TimelineRecord[]>(() => {
  const logs: any[] = task.value?.logList || []
  return logs.map(log => ({
    action: log.operation || log.action || '状态更新',
    time: log.createTime ? formatDate(log.createTime, 'YYYY-MM-DD HH:mm') : '',
    operator: log.operatorName || '系统',
    role: log.operatorRole || roleFromOperationType(log.operationType),
  }))
})

function roleFromOperationType(type: string): string {
  const map: Record<string, string> = {
    create: 'sales',
    audit: 'dispatch',
    dispatch: 'dispatch',
    urge: 'sales',
    cancel: 'sales',
  }
  return map[type] || 'construction'
}

function callPhone(phone: string) {
  if (!phone) return
  uni.makePhoneCall({ phoneNumber: phone })
}

onLoad((options) => {
  if (options?.id) {
    loadDetail(Number(options.id))
  } else if (taskStore.currentTask) {
    // 兼容未携带 id 的入口：使用列表中已加载的任务数据
    task.value = taskStore.currentTask
    loadProject(taskStore.currentTask.projectId)
  }
})

async function loadDetail(taskId: number) {
  loading.value = true
  try {
    const res: any = await getTaskDetail(taskId)
    task.value = res
    loadProject(res?.projectId)
  } catch (e) {
    console.error('加载任务详情失败', e)
  } finally {
    loading.value = false
  }
}

function loadProject(projectId: number | string | undefined) {
  if (!projectId) return
  getProjectDetail(projectId)
    .then(p => { project.value = p })
    .catch(() => {})
}
</script>

<style scoped>
.sub-page {
  max-width: 430px;
  margin: 0 auto;
  min-height: 100vh;
  background-color: #f6fbf9;
  padding-bottom: 24px;
}

.glass-card {
  background-color: rgba(255, 255, 255, 0.85);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  border: 1px solid rgba(164, 216, 152, 0.35);
  border-radius: 24px;
  box-shadow: 0 18px 50px -12px rgba(54, 143, 111, 0.28);
  overflow: hidden;
  margin-bottom: 12px;
}

.notice-title {
  display: block;
  font-size: 17px;
  font-weight: 700;
  color: #1f2937;
  line-height: 1.4;
}

.emergency-tag {
  padding: 2px 10px;
  border-radius: 999px;
  font-size: 11px;
  font-weight: 600;
  color: #ef4444;
  background-color: rgba(239, 68, 68, 0.1);
}

.meta-line {
  display: flex;
  align-items: center;
}

.meta-icon {
  font-size: 14px;
  color: #9ca3af;
}

.meta-text {
  font-size: 12px;
  color: #9ca3af;
}

.meta-value {
  font-size: 13px;
  color: #4b5563;
}

.section-head {
  display: flex;
  align-items: center;
  padding: 16px 16px 12px;
}

.section-bar {
  width: 4px;
  height: 16px;
  border-radius: 2px;
  background: linear-gradient(180deg, #368f6f 0%, #5ab8d0 100%);
}

.section-title {
  font-size: 16px;
  font-weight: 700;
  color: #1f2937;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  border-top: 1px solid rgba(164, 216, 152, 0.18);
}

.info-label {
  font-size: 13px;
  color: #9ca3af;
  flex-shrink: 0;
  margin-right: 12px;
}

.info-value {
  font-size: 13px;
  color: #1f2937;
  text-align: right;
}

.info-value-left {
  flex: 1;
}

.urgent-text {
  color: #ef4444;
  font-weight: 600;
}

.normal-text {
  color: #368f6f;
}

.point-row {
  padding: 13px 16px;
  border-top: 1px solid rgba(164, 216, 152, 0.18);
}

.point-name {
  font-size: 14px;
  font-weight: 600;
  color: #1f2937;
}

.type-tag {
  padding: 2px 10px;
  border-radius: 999px;
  font-size: 11px;
  font-weight: 600;
  color: #368f6f;
  background-color: rgba(164, 216, 152, 0.24);
}

.phone-circle {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(164, 216, 152, 0.24);
}

.phone-icon {
  font-size: 13px;
  color: #368f6f;
}

.empty-text {
  font-size: 13px;
  color: #9ca3af;
}
</style>
