<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="flex justify-end mb-3">
        <view class="toggle-all-btn" @click="toggleAllSections">
          <text class="uni-icons" :class="allExpanded ? 'uniui-arrow-up' : 'uniui-arrow-down'"></text>
          <text class="toggle-all-text">{{ allExpanded ? '一键收起' : '一键展示' }}</text>
        </view>
      </view>

      <!-- 基本信息卡片 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3" @click="basicExpanded = !basicExpanded">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">基本信息</text>
          <StatusTag :status="task.status" />
          <view v-if="canUrge" class="urge-btn ml-2" hover-class="urge-btn-hover" :hover-start-time="0" :hover-stay-time="120" @click.stop="handleUrge">
            <text class="uni-icons uniui-notification urge-icon mr-1"></text>
            <text class="urge-text">催单</text>
          </view>
          <text
            class="uni-icons uniui-arrow-down text-gray-400 text-sm transition-transform ml-2"
            :class="basicExpanded ? 'rotate-180' : ''"
          ></text>
        </view>
        <view v-if="basicExpanded" class="gap-y-3">
          <view class="flex items-start">
            <text class="uni-icons uniui-flag-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">任务名称</text>
            <text class="text-sm text-gray-800 flex-1">{{ taskName }}</text>
          </view>
          <view v-if="task.taskNo" class="flex items-start">
            <text class="uni-icons uniui-list field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">任务编号</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.taskNo }}</text>
          </view>
          <view v-if="task.faultLocation" class="flex items-start">
            <text class="uni-icons uniui-location-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">故障位置</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.faultLocation }}</text>
          </view>
          <view class="flex items-start">
            <text class="uni-icons uniui-gear-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">施工类型</text>
            <text class="text-sm text-gray-800 flex-1">{{ constructionTypeText }}</text>
          </view>
          <view class="flex items-start">
            <text class="uni-icons uniui-calendar-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">服务时间</text>
            <text class="text-sm text-gray-800 flex-1">{{ serviceTimeText }}</text>
          </view>
          <view v-if="task.createBy" class="flex items-start">
            <text class="uni-icons uniui-person-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">申请人</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.createBy }}</text>
          </view>
          <view v-if="task.createTime" class="flex items-start">
            <text class="uni-icons uniui-calendar-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">申请时间</text>
            <text class="text-sm text-gray-800 flex-1">{{ formatDate(task.createTime, 'YYYY-MM-DD HH:mm') }}</text>
          </view>
          <view v-if="urgencyText" class="flex items-start">
            <text class="uni-icons uniui-flag-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">紧急程度</text>
            <text class="text-sm flex-1" :class="task.urgencyLevel === 'very_urgent' ? 'text-red-500' : 'text-gray-800'">{{ urgencyText }}</text>
          </view>
        </view>
      </view>

      <!-- 项目信息卡片 -->
      <view v-if="project" class="glass-card p-4">
        <view class="section-head-inner mb-3" @click="projectExpanded = !projectExpanded">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">项目信息</text>
          <text
            class="uni-icons uniui-arrow-down text-gray-400 text-sm transition-transform"
            :class="projectExpanded ? 'rotate-180' : ''"
          ></text>
        </view>
        <view v-if="projectExpanded" class="gap-y-3">
          <view class="flex items-start">
            <text class="uni-icons uniui-home-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">项目名称</text>
            <text class="text-sm text-gray-800 flex-1">{{ project.projectName }}</text>
          </view>
          <view v-if="project.cooperationType" class="flex items-start">
            <text class="uni-icons uniui-info-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">合作类型</text>
            <text class="text-sm text-gray-800 flex-1">{{ coopTypeText }}</text>
          </view>
          <view v-if="projectAddress" class="flex items-start">
            <text class="uni-icons uniui-location-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">项目地址</text>
            <text class="text-sm text-gray-800 flex-1">{{ projectAddress }}</text>
          </view>
          <view v-if="project.primaryContactName" class="flex items-start">
            <text class="uni-icons uniui-person-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">联系人</text>
            <view class="flex-1 flex items-center justify-between">
              <text class="text-sm text-gray-800">{{ project.primaryContactName }}</text>
              <text
                v-if="project.primaryContactPhone"
                class="text-sm text-blue-500"
                @click="callPhone(project.primaryContactPhone)"
              >{{ project.primaryContactPhone }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 故障详情卡片 -->
      <view v-if="geoLocationText || faultMedia.length > 0" class="glass-card p-4">
        <view class="section-head-inner mb-3" @click="faultExpanded = !faultExpanded">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">故障详情</text>
          <text
            class="uni-icons uniui-arrow-down text-gray-400 text-sm transition-transform"
            :class="faultExpanded ? 'rotate-180' : ''"
          ></text>
        </view>
        <view v-if="faultExpanded" class="gap-y-3">
          <view v-if="geoLocationText" class="flex items-start">
            <text class="uni-icons uniui-location-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">地理位置</text>
            <text class="text-sm link-text flex-1" @click="openMap">{{ geoLocationText }}（点击查看地图）</text>
          </view>
          <view v-if="faultMedia.length > 0" class="flex items-start">
            <text class="uni-icons uniui-image-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">故障图片</text>
            <view class="flex-1 flex flex-wrap gap-2">
              <image
                v-for="(url, index) in faultMedia"
                :key="index"
                :src="url"
                class="w-16 h-16 rounded-lg bg-gray-100"
                mode="aspectFill"
                @click="previewMedia(index)"
              />
            </view>
          </view>
        </view>
      </view>

      <!-- 施工信息卡片 -->
      <view class="glass-card p-4">
        <view class="section-head-inner mb-3" @click="constructionExpanded = !constructionExpanded">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">施工信息</text>
          <text
            class="uni-icons uniui-arrow-down text-gray-400 text-sm transition-transform"
            :class="constructionExpanded ? 'rotate-180' : ''"
          ></text>
        </view>
        <view v-if="constructionExpanded" class="gap-y-3">
          <view v-if="faultDescText" class="flex items-start">
            <text class="uni-icons uniui-info-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">故障描述</text>
            <text class="text-sm text-gray-800 flex-1">{{ faultDescText }}</text>
          </view>
          <view v-if="task.constructionFacility" class="flex items-start">
            <text class="uni-icons uniui-gear-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">施工设施</text>
            <text class="text-sm text-gray-800 flex-1">{{ getFacilityTypeText(task.constructionFacility) }}</text>
          </view>
          <view v-if="task.serviceMethod" class="flex items-start">
            <text class="uni-icons uniui-settings-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">服务方式</text>
            <text class="text-sm text-gray-800 flex-1">{{ getServiceMethodText(task.serviceMethod) }}</text>
          </view>
          <view v-if="extra.suggestedVehicle" class="flex items-start">
            <text class="uni-icons uniui-gear-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">建议出车</text>
            <text class="text-sm text-gray-800 flex-1">{{ getSuggestedVehicleText(extra.suggestedVehicle) }}</text>
          </view>
          <view v-if="task.waterDistance" class="flex items-start">
            <text class="uni-icons uniui-map-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">取水距离</text>
            <text class="text-sm text-gray-800 flex-1">{{ getWaterDistanceText(task.waterDistance) }}</text>
          </view>
          <view v-if="task.outletNormal !== undefined && task.outletNormal !== null" class="flex items-start">
            <text class="uni-icons uniui-info-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">化粪池排口</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.outletNormal === 1 ? '正常' : '异常' }}</text>
          </view>
          <view v-if="task.assistantInfo" class="flex items-start">
            <text class="uni-icons uniui-person-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">施工助力</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.assistantInfo }}</text>
          </view>
          <view v-if="task.estimatedWorkload" class="flex items-start">
            <text class="uni-icons uniui-info-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">预计作业量</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.estimatedWorkload }}</text>
          </view>
          <view v-if="task.estimatedDuration" class="flex items-start">
            <text class="uni-icons uniui-calendar-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">预计工时</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.estimatedDuration }}</text>
          </view>
          <view v-if="task.acceptanceRequirement" class="flex items-start">
            <text class="uni-icons uniui-checkmarkempty field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">验收要求</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.acceptanceRequirement }}</text>
          </view>
          <view v-if="task.acceptanceMethod" class="flex items-start">
            <text class="uni-icons uniui-checkmarkempty field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">验收方式</text>
            <text class="text-sm text-gray-800 flex-1">{{ getAcceptanceMethodText(task.acceptanceMethod) }}</text>
          </view>
          <view v-if="partyAContacts.length > 0" class="flex items-start">
            <text class="uni-icons uniui-person-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">甲方当事人</text>
            <view class="flex-1">
              <view
                v-for="(contact, index) in partyAContacts"
                :key="index"
                class="flex items-center justify-between py-1"
              >
                <text class="text-sm text-gray-800">{{ contact.name }} {{ contact.phone }}</text>
                <button
                  v-if="contact.phone"
                  class="phone-circle"
                  hover-class="phone-btn-hover" :hover-start-time="0" :hover-stay-time="120"
                  @click="callPhone(contact.phone)"
                >
                  <text class="uni-icons uniui-phone-filled phone-icon"></text>
                </button>
              </view>
            </view>
          </view>
          <view v-if="task.remark" class="flex items-start">
            <text class="uni-icons uniui-info-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">备注</text>
            <view class="remark-value flex-1"><text class="text-sm">{{ task.remark }}</text></view>
          </view>
        </view>
      </view>

      <!-- 审核操作卡片（待审核状态显示） -->
      <view v-if="isPendingAudit && !isMonthPlanTask" class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title">审核操作</text>
        </view>
        <view v-if="!showArrangeForm">
          <text class="hint-text mb-4 block">请确认该任务是否可以执行，然后进行后续安排。</text>
          <view class="flex gap-3">
            <view class="action-btn action-btn-reject" hover-class="action-btn-hover" :hover-start-time="0" :hover-stay-time="120" @click="rejectTask">驳回</view>
            <view class="action-btn action-btn-confirm" hover-class="action-btn-hover" :hover-start-time="0" :hover-stay-time="120" @click="confirmTask">确认</view>
          </view>
        </view>
        <view v-else>
          <text class="hint-text hint-gold mb-4 block">任务已确认，请安排班组和车辆</text>
          <view class="form-group mb-4">
            <text class="form-label">调度班组</text>
            <picker mode="selector" :range="teamOptions" range-key="label" :value="selectedTeamIndex" @change="onTeamChange">
              <view class="form-input flex items-center justify-between">
                <text :class="selectedTeamLabel ? 'text-gray-800' : 'text-gray-400'">{{ selectedTeamLabel || '请选择班组' }}</text>
              </view>
            </picker>
          </view>
          <view class="form-group mb-4">
            <text class="form-label">调度车辆</text>
            <picker mode="selector" :range="vehicleOptions" range-key="label" :value="selectedVehicleIndex" @change="onVehicleChange">
              <view class="form-input flex items-center justify-between">
                <text :class="selectedVehicleLabel ? 'text-gray-800' : 'text-gray-400'">{{ selectedVehicleLabel || '请选择车辆' }}</text>
              </view>
            </picker>
          </view>
          <view class="form-group mb-4">
            <text class="form-label">审核备注（可选）</text>
            <textarea v-model="auditRemark" class="form-textarea" placeholder="请输入审核备注..."></textarea>
          </view>
          <view class="flex gap-3">
            <view class="action-btn action-btn-back" hover-class="action-btn-hover" :hover-start-time="0" :hover-stay-time="120" @click="showArrangeForm = false">返回</view>
            <view class="action-btn action-btn-primary" hover-class="action-btn-hover" :hover-start-time="0" :hover-stay-time="120" @click="arrangeTeam">安排</view>
          </view>
        </view>
      </view>

      <!-- 待安排操作卡片（approved 状态显示） -->
      <view v-if="task.status === 'approved' && !isMonthPlanTask" class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title">安排班组</text>
        </view>
        <text class="hint-text hint-gold mb-4 block">任务已审核通过，请安排班组和车辆</text>
        <view class="form-group mb-4">
          <text class="form-label">调度班组</text>
          <picker mode="selector" :range="teamOptions" range-key="label" :value="selectedTeamIndex" @change="onTeamChange">
            <view class="form-input flex items-center justify-between">
              <text :class="selectedTeamLabel ? 'text-gray-800' : 'text-gray-400'">{{ selectedTeamLabel || '请选择班组' }}</text>
            </view>
          </picker>
        </view>
        <view class="form-group mb-4">
          <text class="form-label">调度车辆</text>
          <picker mode="selector" :range="vehicleOptions" range-key="label" :value="selectedVehicleIndex" @change="onVehicleChange">
            <view class="form-input flex items-center justify-between">
              <text :class="selectedVehicleLabel ? 'text-gray-800' : 'text-gray-400'">{{ selectedVehicleLabel || '请选择车辆' }}</text>
            </view>
          </picker>
        </view>
        <view class="form-group mb-4">
          <text class="form-label">审核备注（可选）</text>
          <textarea v-model="auditRemark" class="form-textarea" placeholder="请输入审核备注..."></textarea>
        </view>
        <view class="action-btn action-btn-primary" hover-class="action-btn-hover" :hover-start-time="0" :hover-stay-time="120" @click="arrangeTeam">安排</view>
      </view>

      <!-- 驳回原因（已驳回状态显示） -->
      <view v-if="task.status === 'rejected'" class="glass-card p-4">
        <view class="section-head-inner mb-3">
          <view class="section-bar mr-2"></view>
          <text class="section-title">驳回原因</text>
        </view>
        <view class="reject-box">
          <text class="reject-text">{{ task.auditRemark || '任务不符合执行条件，已驳回' }}</text>
        </view>
      </view>

      <!-- 调度信息（已安排状态显示） -->
      <view v-if="isDispatched" class="glass-card p-4">
        <view class="section-head-inner mb-3" @click="dispatchExpanded = !dispatchExpanded">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">调度信息</text>
          <text
            class="uni-icons uniui-arrow-down text-gray-400 text-sm transition-transform"
            :class="dispatchExpanded ? 'rotate-180' : ''"
          ></text>
        </view>
        <view v-if="dispatchExpanded" class="gap-y-3">
          <view class="flex items-start">
            <text class="uni-icons uniui-staff-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">执行班组</text>
            <text class="text-sm text-gray-800 flex-1">{{ dispatchedTeamName }}</text>
          </view>
          <view class="flex items-start">
            <text class="uni-icons uniui-gear-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">调度车辆</text>
            <text class="text-sm text-gray-800 flex-1">{{ dispatchedVehicleName }}</text>
          </view>
          <view v-if="auditOperator" class="flex items-start">
            <text class="uni-icons uniui-person-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">审核人</text>
            <text class="text-sm text-gray-800 flex-1">{{ auditOperator }}</text>
          </view>
          <view v-if="task.auditTime" class="flex items-start">
            <text class="uni-icons uniui-calendar-filled field-icon mr-2"></text><text class="text-gray-500 text-sm w-24">审核时间</text>
            <text class="text-sm text-gray-800 flex-1">{{ formatDate(task.auditTime, 'YYYY-MM-DD HH:mm') }}</text>
          </view>
        </view>
      </view>

      <!-- 处理记录 -->
      <view v-if="timelineRecords.length > 0" class="glass-card p-4">
        <view class="section-head-inner mb-3" @click="timelineExpanded = !timelineExpanded">
          <view class="section-bar mr-2"></view>
          <text class="section-title flex-1">处理记录</text>
          <text
            class="uni-icons uniui-arrow-down text-gray-400 text-sm transition-transform"
            :class="timelineExpanded ? 'rotate-180' : ''"
          ></text>
        </view>
        <view v-if="timelineExpanded">
          <Timeline :records="timelineRecords" />
        </view>
      </view>
    </view>

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

<script setup lang="ts">
import { computed, ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
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 { useAuthStore } from '../../stores/auth'
import {
  formatDate,
  showToast,
  getConstructionTypeText,
  getFacilityTypeText,
  getServiceMethodText,
  getSuggestedVehicleText,
  getWaterDistanceText,
  getAcceptanceMethodText,
  getCooperationTypeText,
  formatTaskLogAction,
  getTaskLogRole,
} from '../../utils'
import { getTaskDetail, approveTask, rejectTaskAudit, dispatchTask, urgeTask } from '../../api/task'
import { getProjectDetail } from '../../api/project'
import { getTeamSimpleList } from '../../api/team'
import { getVehicleSimpleList } from '../../api/vehicle'
import { getSchedulesByDate } from '../../api/schedule'

const authStore = useAuthStore()

const task = ref<any>(null)
const project = ref<any>(null)
const loading = ref(false)
const submitting = ref(false)
const taskId = ref<number>(0)

const showArrangeForm = ref(false)
const auditRemark = ref('')
const timelineExpanded = ref(true)
const basicExpanded = ref(true)
const projectExpanded = ref(true)
const faultExpanded = ref(true)
const constructionExpanded = ref(true)
const dispatchExpanded = ref(true)

const allExpanded = computed(() => {
  return basicExpanded.value && projectExpanded.value && faultExpanded.value &&
    constructionExpanded.value && dispatchExpanded.value && timelineExpanded.value
})
const allTeams = ref<Array<{ value: number; label: string }>>([])
const allVehicles = ref<Array<{ value: number; label: string }>>([])
const scheduledTeamInfo = ref<Record<number, { vehicleIds: number[]; shiftTypes: string[] }>>({})
const selectedTeamId = ref<number | undefined>(undefined)
const selectedVehicleId = ref<number | undefined>(undefined)

const shiftTypeText: Record<string, string> = {
  day: '白班',
  night: '夜班',
  month_plan: '月计划',
  emergency: '应急',
}

const isMonthPlanTask = computed(() => task.value?.planId != null)

const teamOptions = computed(() => {
  const keys = Object.keys(scheduledTeamInfo.value)
  const base = allTeams.value.map((item) => ({ ...item }))
  if (keys.length === 0) return base
  return base
    .filter((t) => scheduledTeamInfo.value[t.value])
    .map((t) => {
      const info = scheduledTeamInfo.value[t.value]
      const shiftLabels = info?.shiftTypes.map((st) => shiftTypeText[st] || st).join('/')
      return {
        ...t,
        label: shiftLabels ? `${t.label} (${shiftLabels})` : t.label,
      }
    })
})

const vehicleOptions = computed(() => {
  const teamId = selectedTeamId.value
  const info = teamId ? scheduledTeamInfo.value[teamId] : null
  if (!info || info.vehicleIds.length === 0) return allVehicles.value.map((item) => ({ ...item }))
  return allVehicles.value
    .filter((v) => info.vehicleIds.includes(v.value))
    .map((item) => ({ ...item }))
})

const selectedTeamIndex = computed(() => teamOptions.value.findIndex(t => t.value === selectedTeamId.value))
const selectedVehicleIndex = computed(() => vehicleOptions.value.findIndex(v => v.value === selectedVehicleId.value))
const selectedTeamLabel = computed(() => teamOptions.value.find(t => t.value === selectedTeamId.value)?.label || '')
const selectedVehicleLabel = computed(() => vehicleOptions.value.find(v => v.value === selectedVehicleId.value)?.label || '')

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

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

function toggleAllSections() {
  const next = !allExpanded.value
  basicExpanded.value = next
  projectExpanded.value = next
  faultExpanded.value = next
  constructionExpanded.value = next
  dispatchExpanded.value = next
  timelineExpanded.value = next
}

const isPendingAudit = computed(() => ['auditing', 'pending'].includes(task.value?.status))
const isDispatched = computed(() => ['assigned', 'in_progress', 'completed'].includes(task.value?.status))
const canUrge = computed(() => task.value && !['completed', 'cancelled'].includes(task.value.status))

const taskName = computed(() => {
  if (!task.value) return ''
  return task.value.taskName || task.value.serviceContent || task.value.faultLocation || taskTypeText(task.value.taskType) || '未命名任务'
})

const constructionTypeText = computed(() => {
  if (!task.value) return ''
  const raw = task.value.constructionType || taskTypeText(task.value.taskType)
  return raw ? getConstructionTypeText(raw) : '-'
})

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

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

const coopTypeText = computed(() => {
  return getCooperationTypeText(project.value?.cooperationType)
})

const projectAddress = computed(() => {
  if (!project.value) return ''
  const p = project.value
  return [p.province, p.city, p.district, p.street, p.detailAddress || p.address].filter(Boolean).join('') || p.address || ''
})

const faultDescText = computed(() => {
  if (!task.value) return ''
  const parts = [task.value.faultType, task.value.customerWords].filter(Boolean)
  return parts.join('；')
})

const geoLocationText = computed(() => {
  if (extra.value.geoLocation) return extra.value.geoLocation
  if (extra.value.latitude && extra.value.longitude) return `${extra.value.latitude}, ${extra.value.longitude}`
  return ''
})

const faultMedia = computed<string[]>(() => {
  const photos = extra.value.photos || extra.value.faultPhotos || extra.value.media
  if (!photos) return []
  if (Array.isArray(photos)) return photos
  return String(photos).split(',').filter(Boolean)
})

const partyAContacts = computed<Array<{ name: string; phone: string }>>(() => {
  const list = extra.value.partyAContacts || extra.value.partyA
  if (!list) return []
  if (Array.isArray(list)) return list
  return []
})

const dispatchedTeamName = computed(() => {
  if (!task.value?.dispatchTeamId) return '未安排'
  return allTeams.value.find(t => t.value === Number(task.value.dispatchTeamId))?.label || `班组#${task.value.dispatchTeamId}`
})

const dispatchedVehicleName = computed(() => {
  if (!task.value?.dispatchVehicleId) return '未安排'
  return allVehicles.value.find(v => v.value === Number(task.value.dispatchVehicleId))?.label || `车辆#${task.value.dispatchVehicleId}`
})

const auditOperator = computed(() => {
  const logs: any[] = task.value?.logList || []
  const auditLog = logs.find((l: any) => l.operationType === 'audit')
  return auditLog?.operatorName || auditLog?.operator || auditLog?.createBy || ''
})

function taskTypeText(type: string): string {
  const map: Record<string, string> = {
    dredge: '疏通', repair: '维修', clean: '清掏', inspect: '检查', emergency: '应急',
    '疏通': '疏通', '维修': '维修', '清掏': '清掏', '检查': '检查', '应急': '应急',
  }
  return type ? map[type] || type : ''
}

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

function openMap() {
  const lat = Number(extra.value.latitude)
  const lng = Number(extra.value.longitude)
  if (!lat || !lng) return
  uni.openLocation({ latitude: lat, longitude: lng, name: task.value?.faultLocation || '故障位置' })
}

function previewMedia(index: number) {
  uni.previewImage({ urls: faultMedia.value, current: index })
}

onLoad((options) => {
  if (options?.id) {
    taskId.value = Number(options.id)
    loadDetail()
  }
})

async function loadDetail() {
  loading.value = true
  try {
    const res: any = await getTaskDetail(taskId.value)
    task.value = res
    if (res?.projectId) {
      getProjectDetail(res.projectId).then(p => { project.value = p }).catch(() => {})
    }
    if (allTeams.value.length === 0) {
      getTeamSimpleList().then(list => { allTeams.value = list }).catch(() => {})
    }
    if (allVehicles.value.length === 0) {
      getVehicleSimpleList().then(list => { allVehicles.value = list }).catch(() => {})
    }
    if (res?.planDate) {
      loadScheduleInfo(res.planDate)
    }
  } catch (e) {
    console.error('加载任务详情失败', e)
    showToast('加载任务详情失败')
  } finally {
    loading.value = false
  }
}

async function loadScheduleInfo(planDate: string) {
  try {
    const res = await getSchedulesByDate(planDate)
    const schedules: any[] = res || []
    const map: Record<number, { vehicleIds: number[]; shiftTypes: string[] }> = {}
    schedules.forEach((s) => {
      if (s.teamId) {
        const existing = map[s.teamId] || { vehicleIds: [], shiftTypes: [] }
        const vehicleIds = (s.vehicleIds || '')
          .split(',')
          .map((id: string) => Number(id.trim()))
          .filter((id: number) => !isNaN(id) && id > 0)
        existing.vehicleIds = Array.from(new Set([...existing.vehicleIds, ...vehicleIds]))
        if (s.shiftType && !existing.shiftTypes.includes(s.shiftType)) {
          existing.shiftTypes.push(s.shiftType)
        }
        map[s.teamId] = existing
      }
    })
    scheduledTeamInfo.value = map
  } catch (error) {
    console.error('加载当天排班失败', error)
  }
}

function auditUser() {
  return {
    auditUserId: authStore.userInfo?.id,
    auditUserName: authStore.userInfo?.name,
  }
}

function onTeamChange(e: any) {
  const team = teamOptions.value[Number(e.detail.value)]
  selectedTeamId.value = team?.value
  const info = team?.value ? scheduledTeamInfo.value[team.value] : null
  if (info?.vehicleIds?.length) {
    selectedVehicleId.value = info.vehicleIds[0]
  } else {
    selectedVehicleId.value = undefined
  }
}

function onVehicleChange(e: any) {
  selectedVehicleId.value = vehicleOptions.value[Number(e.detail.value)]?.value
}

async function confirmTask() {
  submitting.value = true
  try {
    await approveTask(taskId.value, { ...auditUser() })
    showToast('审核通过，请安排班组和车辆')
    showArrangeForm.value = true
  } catch (e) {
    console.error('审核通过失败', e)
  } finally {
    submitting.value = false
  }
}

async function rejectTask() {
  const res = await new Promise<any>((resolve) => {
    uni.showModal({
      title: '驳回任务',
      editable: true,
      placeholderText: '请输入驳回原因（可选）',
      confirmText: '确认驳回',
      success: resolve,
      fail: () => resolve({ confirm: false }),
    })
  })
  if (!res.confirm) return
  submitting.value = true
  try {
    await rejectTaskAudit(taskId.value, { remark: res.content || '', ...auditUser() })
    showToast('任务已驳回')
    await loadDetail()
  } catch (e) {
    console.error('驳回失败', e)
  } finally {
    submitting.value = false
  }
}

async function arrangeTeam() {
  if (!selectedTeamId.value) {
    showToast('请选择班组')
    return
  }
  if (!selectedVehicleId.value) {
    showToast('请选择车辆')
    return
  }
  submitting.value = true
  try {
    await dispatchTask(taskId.value, {
      teamId: selectedTeamId.value,
      vehicleId: selectedVehicleId.value,
      remark: auditRemark.value,
      ...auditUser(),
    })
    showToast('安排成功')
    showArrangeForm.value = false
    auditRemark.value = ''
    await loadDetail()
  } catch (e) {
    console.error('安排失败', e)
  } finally {
    submitting.value = false
  }
}

async function handleUrge() {
  if (!taskId.value) return
  const res = await new Promise<any>((resolve) => {
    uni.showModal({
      title: '催单',
      editable: true,
      placeholderText: '请输入催单原因',
      confirmText: '确认催单',
      cancelText: '取消',
      success: resolve,
      fail: () => resolve({ confirm: false }),
    })
  })
  if (!res.confirm) return
  try {
    await urgeTask(
      taskId.value,
      res.content || '用户催单',
      authStore.userInfo?.id ? Number(authStore.userInfo.id) : 0,
      authStore.userInfo?.name || ''
    )
    uni.showToast({ title: '催单成功', icon: 'success' })
    loadDetail()
  } catch (error) {
    console.error('催单失败', error)
  }
}
</script>

<style scoped>
/* 字段行统一间距 */
.glass-card .gap-y-3 > .flex.items-start {
  margin-bottom: 20rpx;
}
.glass-card .gap-y-3 > .flex.items-start:last-child {
  margin-bottom: 0;
}

/* 字段图标 */
.field-icon {
  font-size: 24rpx;
  color: #9ca3af;
  width: 32rpx;
  text-align: center;
  line-height: 1;
}

/* 字段标签：加宽以容纳图标和长标签 */
.glass-card .text-gray-500.text-sm.w-24 {
  width: 180rpx !important;
  color: #6b7280 !important;
  line-height: 1.5;
}

/* 字段值 */
.glass-card .text-sm.text-gray-800.flex-1,
.glass-card .text-sm.flex-1 {
  color: #1f2937;
  line-height: 1.5;
}

/* 地图链接 */
.link-text {
  color: #368f6f;
  text-decoration: underline;
}

/* 备注 */
.remark-value {
  padding: 16rpx;
  border-radius: 12rpx;
  background-color: rgba(239, 68, 68, 0.06);
  color: #dc2626;
}

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

.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;
}

.section-head-inner {
  display: flex;
  align-items: center;
}

.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;
}

.hint-text {
  font-size: 13px;
  color: #9ca3af;
}

.hint-gold {
  color: #b7791f;
}

.link-text {
  color: #368f6f;
  text-decoration: underline;
}

.reject-box {
  padding: 24rpx;
  border-radius: 16rpx;
  background-color: rgba(239, 68, 68, 0.08);
}

.reject-text {
  font-size: 13px;
  color: #dc2626;
  line-height: 1.6;
}

.action-btn {
  flex: 1;
  padding: 11px 0;
  border-radius: 12px;
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  color: #ffffff;
}

.action-btn-hover {
  opacity: 0.88;
  transform: scale(0.98);
}

.action-btn-reject {
  background: linear-gradient(135deg, #ef4444 0%, #f87171 100%);
}

.action-btn-confirm {
  background: linear-gradient(135deg, #368f6f 0%, #4ba98a 100%);
}

.action-btn-primary {
  background: linear-gradient(135deg, #368f6f 0%, #4ba98a 100%);
}

.action-btn-back {
  color: #6b7280;
  background-color: #f3f4f6;
}

.urge-btn {
  display: flex;
  align-items: center;
  padding: 8rpx 20rpx;
  border-radius: 999px;
  background: linear-gradient(135deg, #fee2e2 0%, #fecaca 100%);
}

.urge-btn-hover {
  opacity: 0.88;
  transform: scale(0.96);
}

.urge-icon {
  font-size: 13px;
  color: #ef4444;
}

.urge-text {
  font-size: 12px;
  font-weight: 600;
  color: #ef4444;
}

.phone-circle {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  flex-shrink: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(164, 216, 152, 0.24);
  box-shadow: 0 2px 6px rgba(54, 143, 111, 0.12);
}

.phone-btn-hover {
  opacity: 0.8;
  transform: scale(0.92);
}

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

.transition-transform {
  transition: transform 0.2s ease;
}

.rotate-180 {
  transform: rotate(180deg);
}

.toggle-all-btn {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 12px;
  background-color: #ffffff;
  border: 1px solid #e5e7eb;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
}

.toggle-all-text {
  font-size: 12px;
  color: #666666;
  margin-left: 3px;
}

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

.form-group {
  margin-bottom: 16px;
}

.form-label {
  display: block;
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 8px;
}

.form-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  font-size: 14px;
  background: #fff;
}

.form-textarea {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  font-size: 14px;
  color: #333;
  background: #fff;
  min-height: 80px;
}
</style>
