<template>
  <view class="app-container pb-24">
    <TopBar title="任务详情" show-back />

    <view v-if="task" class="px-4 py-4">
      <!-- 基本信息卡片 -->
      <view class="card p-4 mb-4">
        <view class="flex items-center justify-between mb-4">
          <view class="flex-1 min-w-0 mr-3">
            <text class="text-base font-semibold text-gray-800 block truncate">{{ task.projectName }}</text>
          </view>
          <StatusTag :status="task.status" />
        </view>

        <view class="gap-y-3">
          <view class="flex items-start">
            <text class="text-gray-500 text-sm w-24">任务名称</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.projectName }}</text>
          </view>
          <view v-if="task.faultLocation" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">故障位置</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.faultLocation }}</text>
          </view>
          <view v-if="task.serviceType" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">施工类型</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.serviceType }}</text>
          </view>
          <view v-if="task.facilityType" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">设施类型</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.facilityType }}</text>
          </view>
          <view class="flex items-start">
            <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.applicant" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">申请人</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.applicant }}</text>
          </view>
          <view v-if="task.applyTime" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">申请时间</text>
            <text class="text-sm text-gray-800 flex-1">{{ formatDate(task.applyTime, 'YYYY-MM-DD HH:mm') }}</text>
          </view>
          <view v-if="task.address" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">项目地址</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.address }}</text>
          </view>
          <view class="flex items-start">
            <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>
      </view>

      <!-- 项目信息 -->
      <view class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">项目信息</text>
        <view class="gap-y-3">
          <view v-if="task.customerName" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">客户名称</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.customerName }}</text>
          </view>
          <view v-if="task.customerPhone" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">客户电话</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.customerPhone }}</text>
          </view>
          <view v-if="task.coopType" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">合作类型</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.coopType }}</text>
          </view>
          <view v-if="task.serviceMode" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">服务方式</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.serviceMode }}</text>
          </view>
          <view v-if="task.acceptType" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">验收方式</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.acceptType }}</text>
          </view>
        </view>
      </view>

      <!-- 施工信息 -->
      <view v-if="task.faultDesc || task.estimatedQuantity || task.estimatedHours || task.constructionHelp" class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">施工信息</text>
        <view class="gap-y-3">
          <view v-if="task.faultDesc" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">故障描述</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.faultDesc }}</text>
          </view>
          <view v-if="task.estimatedQuantity" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">预估方量</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.estimatedQuantity }}</text>
          </view>
          <view v-if="task.estimatedHours" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">预估工时</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.estimatedHours }}</text>
          </view>
          <view v-if="task.constructionHelp" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">施工协助</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.constructionHelp }}</text>
          </view>
          <view v-if="task.waterSource" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">水源情况</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.waterSource }}</text>
          </view>
          <view v-if="task.septicTank" class="flex items-start">
            <text class="text-gray-500 text-sm w-24">化粪池情况</text>
            <text class="text-sm text-gray-800 flex-1">{{ task.septicTank }}</text>
          </view>
        </view>
      </view>

      <!-- 甲方联系人 -->
      <view v-if="partyAContacts.length > 0" class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">甲方联系人</text>
        <view class="gap-y-3">
          <view
            v-for="(contact, index) in partyAContacts"
            :key="index"
            class="flex items-center justify-between p-3 bg-surface rounded-lg"
          >
            <view>
              <text class="text-sm text-gray-800">{{ contact.name }}</text>
            </view>
            <view class="flex items-center">
              <text class="text-sm text-gray-600 mr-3">{{ contact.phone }}</text>
              <button class="w-8 h-8 bg-primary-light rounded-full flex items-center justify-center" @click="callPhone(contact.phone)">
                <text class="uni-icons uniui-phone-filled text-primary"></text>
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 任务进度时间线 -->
      <view class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">任务进度</text>
        <view class="gap-y-4">
          <view v-for="(record, index) in task.timeline" :key="index" class="flex items-start">
            <view class="flex flex-col items-center mr-3">
              <view class="w-3 h-3 rounded-full" :class="index === 0 ? 'bg-green-500' : 'bg-blue-500'"></view>
              <view v-if="index < task.timeline.length - 1" class="w-px h-8 bg-gray-200 mt-1"></view>
            </view>
            <view class="flex-1 pb-2">
              <text class="text-sm font-medium text-gray-800">{{ record.action }}</text>
              <view class="flex justify-between mt-1">
                <text class="text-xs text-gray-500">{{ record.operator }} · {{ getRoleText(record.role) }}</text>
                <text class="text-xs text-gray-400">{{ formatDate(record.time, 'MM-DD HH:mm') }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 审核操作卡片（待审核状态显示） -->
      <view v-if="task.status === 'pending'" class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">审核操作</text>
        <view v-if="!showArrangeForm">
          <text class="text-sm text-gray-500 mb-4 block">请确认该任务是否可以执行，然后进行后续安排。</text>
          <view class="flex gap-3">
            <button class="flex-1 py-3 bg-red-500 text-white rounded-lg text-sm font-medium" @click="rejectTask">驳回</button>
            <button class="flex-1 py-3 bg-green-500 text-white rounded-lg text-sm font-medium" @click="confirmTask">确认</button>
          </view>
        </view>
        <view v-else>
          <text class="text-sm text-yellow-600 mb-4 block">任务已确认，请安排班组和车辆</text>
          <view class="form-group mb-4">
            <text class="form-label">调度班组</text>
            <picker mode="selector" :range="teamOptions" :value="selectedTeamIndex" @change="onTeamChange">
              <view class="form-input flex items-center justify-between">
                <text :class="selectedTeam ? 'text-gray-800' : 'text-gray-400'">{{ selectedTeam || '请选择班组' }}</text>
                <text class="text-gray-400"></text>
              </view>
            </picker>
          </view>
          <view class="form-group mb-4">
            <text class="form-label">调度车辆</text>
            <picker mode="selector" :range="vehicleOptions" :value="selectedVehicleIndex" @change="onVehicleChange">
              <view class="form-input flex items-center justify-between">
                <text :class="selectedVehicle ? 'text-gray-800' : 'text-gray-400'">{{ selectedVehicle || '请选择车辆' }}</text>
                <text class="text-gray-400"></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">
            <button class="flex-1 py-3 bg-gray-200 text-gray-700 rounded-lg text-sm font-medium" @click="showArrangeForm = false">返回</button>
            <button class="flex-1 py-3 bg-blue-500 text-white rounded-lg text-sm font-medium" @click="arrangeTeam">安排</button>
          </view>
        </view>
      </view>

      <!-- 待排班操作卡片（confirmed状态显示） -->
      <view v-if="task.status === 'confirmed'" class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">安排班组</text>
        <text class="text-sm text-yellow-600 mb-4 block">任务已确认，请安排班组和车辆</text>
        <view class="form-group mb-4">
          <text class="form-label">调度班组</text>
          <picker mode="selector" :range="teamOptions" :value="selectedTeamIndex" @change="onTeamChange">
            <view class="form-input flex items-center justify-between">
              <text :class="selectedTeam ? 'text-gray-800' : 'text-gray-400'">{{ selectedTeam || '请选择班组' }}</text>
              <text class="text-gray-400"></text>
            </view>
          </picker>
        </view>
        <view class="form-group mb-4">
          <text class="form-label">调度车辆</text>
          <picker mode="selector" :range="vehicleOptions" :value="selectedVehicleIndex" @change="onVehicleChange">
            <view class="form-input flex items-center justify-between">
              <text :class="selectedVehicle ? 'text-gray-800' : 'text-gray-400'">{{ selectedVehicle || '请选择车辆' }}</text>
              <text class="text-gray-400"></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>
        <button class="w-full py-3 bg-blue-500 text-white rounded-lg text-sm font-medium" @click="arrangeTeam">安排</button>
      </view>

      <!-- 驳回原因（已驳回状态显示） -->
      <view v-if="task.status === 'rejected'" class="card p-4 mb-4">
        <text class="text-base font-semibold text-gray-800 mb-4 block">驳回原因</text>
        <view class="p-3 bg-red-50 rounded-lg">
          <text class="text-sm text-red-600">{{ task.rejectReason || '任务不符合执行条件，已驳回' }}</text>
        </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 { useTaskStore } from '../../stores/task'
import { useAuthStore } from '../../stores/auth'
import { formatDate, getTypeText, getRoleText, showToast, showModal } from '../../utils'
import { updateTask } from '../../api/task'

const taskStore = useTaskStore()
const authStore = useAuthStore()

const task = computed(() => taskStore.currentTask)
const showArrangeForm = ref(false)
const selectedTeam = ref('')
const selectedVehicle = ref('')
const auditRemark = ref('')

const teamOptions = ['一班组', '二班组', '三班组', '应急组']
const vehicleOptions = ['浙A·12345 清洁车', '浙A·67890 垃圾清运车', '浙A·11111 高压清洗车', '浙A·33333 清洁车']

const selectedTeamIndex = computed(() => teamOptions.indexOf(selectedTeam.value))
const selectedVehicleIndex = computed(() => vehicleOptions.indexOf(selectedVehicle.value))

const serviceTimeText = computed(() => {
  if (!task.value) return '待定'
  const date = task.value.serviceDate || task.value.scheduleDate || ''
  const time = task.value.serviceTime || task.value.scheduleTime || ''
  return date || time ? `${date} ${time}`.trim() : '待定'
})

const partyAContacts = computed(() => {
  if (!task.value) return []
  return task.value.partyAContacts || []
})

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

onLoad((options) => {
  if (options?.id) {
    taskStore.setCurrentTask(options.id)
  }
})

function onTeamChange(e: any) {
  selectedTeam.value = teamOptions[e.detail.value]
}

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

async function confirmTask() {
  showArrangeForm.value = true
}

async function rejectTask() {
  const res = await showModal({
    title: '确认驳回',
    content: '确定要驳回该任务吗？'
  })
  if (res.confirm && task.value) {
    try {
      await updateTask(Number(task.value.id), { status: 'rejected' } as any)
      showToast('任务已驳回')
    } catch {
      showToast('操作失败')
    }
  }
}

async function arrangeTeam() {
  if (!selectedTeam.value) {
    showToast('请选择班组')
    return
  }
  if (!selectedVehicle.value) {
    showToast('请选择车辆')
    return
  }
  if (task.value) {
    try {
      await updateTask(Number(task.value.id), { status: 'scheduled' } as any)
      showToast('排班安排成功')
      showArrangeForm.value = false
    } catch {
      showToast('操作失败')
    }
  }
}
</script>

<style scoped>
.form-group {
  margin-bottom: 16px;
}

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