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

    <view v-if="projectStore.loading" class="py-20 text-center">
      <text class="text-gray-400">加载中...</text>
    </view>

    <view v-else-if="!project" class="px-4 py-6">
      <EmptyState message="项目不存在" />
    </view>

    <view v-else class="px-4 py-4 gap-y-4">
      <!-- 项目状态卡片 -->
      <view class="card p-4">
        <view class="flex items-center justify-between mb-4">
          <view>
            <text class="text-lg font-bold text-gray-800">{{ project.name }}</text>
            <text class="text-xs text-gray-400 block mt-1">{{ formatDate(project.createTime, 'YYYY-MM-DD') }}</text>
          </view>
          <StatusTag :status="project.status" type="project" />
        </view>

        <!-- 项目关键信息 -->
        <view class="flex items-center justify-between py-3 border-t border-gray-100">
          <view class="flex items-center">
            <text class="uni-icons uniui-folder-add-filled text-primary mr-2"></text>
            <text class="text-sm text-gray-500">项目类型</text>
          </view>
          <text class="text-sm text-gray-800">{{ project.type || '-' }}</text>
        </view>
        <view class="flex items-center justify-between py-3 border-t border-gray-100">
          <view class="flex items-center">
            <text class="uni-icons uniui-person-filled text-primary mr-2"></text>
            <text class="text-sm text-gray-500">客户</text>
          </view>
          <text class="text-sm text-gray-800">{{ project.customerName || '-' }}</text>
        </view>
        <view class="flex items-center justify-between py-3 border-t border-gray-100">
          <view class="flex items-center">
            <text class="uni-icons uniui-phone-filled text-primary mr-2"></text>
            <text class="text-sm text-gray-500">电话</text>
          </view>
          <view class="flex items-center" @click="callPhone(project.customerPhone)">
            <text class="text-sm text-primary">{{ project.customerPhone || '-' }}</text>
            <text class="uni-icons uniui-arrowright text-gray-400 ml-1"></text>
          </view>
        </view>
      </view>

      <!-- 地址信息 -->
      <view class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-location-filled text-primary mr-2"></text>
          <text>地址信息</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">完整地址</text>
          <text class="detail-value text-right flex-1">{{ fullAddress || '-' }}</text>
        </view>
      </view>

      <!-- 合同信息 -->
      <view v-if="showContractInfo" class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-wallet-filled text-primary mr-2"></text>
          <text>合同信息</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">合同金额</text>
          <text class="detail-value">{{ project.contractAmount ? `¥${project.contractAmount.toLocaleString()}` : '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">合同开始</text>
          <text class="detail-value">{{ project.contractStartDate || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">合同结束</text>
          <text class="detail-value">{{ project.contractEndDate || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">服务周期</text>
          <text class="detail-value">{{ project.serviceCycle || '-' }}</text>
        </view>
      </view>

      <!-- 项目联系人 -->
      <view v-if="project.contacts && project.contacts.length > 0" class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-person-filled text-primary mr-2"></text>
          <text>项目联系人</text>
        </view>
        <view
          v-for="(contact, index) in project.contacts"
          :key="index"
          class="flex items-center justify-between py-3"
          :class="{ 'border-t border-gray-100': index > 0 }"
        >
          <view class="flex items-center">
            <view class="w-10 h-10 rounded-full bg-primary-light flex items-center justify-center mr-3">
              <text class="uni-icons uniui-person text-primary"></text>
            </view>
            <view>
              <text class="text-sm text-gray-800">{{ contact.name }}</text>
              <text v-if="contact.role" class="text-xs text-gray-400 block">{{ contact.role }}</text>
            </view>
          </view>
          <view class="flex items-center" @click="callPhone(contact.phone)">
            <text class="text-sm text-primary">{{ contact.phone }}</text>
            <view class="w-8 h-8 rounded-full bg-primary-light flex items-center justify-center ml-2">
              <text class="uni-icons uniui-phone-filled text-primary text-sm"></text>
            </view>
          </view>
        </view>
      </view>

      <!-- 服务点信息 -->
      <view class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-location-filled text-primary mr-2"></text>
          <text>服务点与服务项</text>
        </view>
        <view v-if="project.servicePoints && project.servicePoints.length > 0">
          <view
            v-for="(point, index) in project.servicePoints"
            :key="index"
            class="py-3"
            :class="{ 'border-t border-gray-100': index > 0 }"
          >
            <view class="flex items-center mb-2">
              <text class="uni-icons uniui-location-filled text-primary mr-2"></text>
              <text class="text-sm font-medium text-gray-800">{{ point.name || `服务点 ${index + 1}` }}</text>
            </view>
            <view class="pl-6">
              <text v-if="point.address" class="text-xs text-gray-500 block mb-1">{{ point.address }}</text>
              <view class="flex items-center flex-wrap gap-2">
                <text v-if="point.serviceType" class="px-2 py-1 bg-primary-light text-primary rounded text-xs">{{ point.serviceType }}</text>
                <text v-if="point.contactName" class="text-xs text-gray-500">联系人：{{ point.contactName }}</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="py-4 text-center">
          <text class="text-sm text-gray-400">暂无服务点信息</text>
        </view>
      </view>

      <!-- 项目位置 -->
      <view class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-map-filled text-primary mr-2"></text>
          <text>项目位置</text>
        </view>
        <MapView
          :latitude="projectLatitude"
          :longitude="projectLongitude"
          :title="project.name"
          :address="fullAddress"
          :height="180"
        />
      </view>

      <!-- 备注 -->
      <view v-if="project.remark" class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-compose text-primary mr-2"></text>
          <text>备注</text>
        </view>
        <text class="text-sm text-gray-600">{{ project.remark }}</text>
      </view>

      <!-- 关联任务 -->
      <view class="card p-4">
        <view class="flex items-center justify-between mb-4">
          <view class="detail-section-title mb-0">
            <text class="uni-icons uniui-flag-filled text-primary mr-2"></text>
            <text>关联任务</text>
          </view>
          <text class="text-sm text-primary" @click="goToTaskList">查看全部</text>
        </view>
        <view v-if="projectTasks.length > 0">
          <view
            v-for="task in projectTasks"
            :key="task.id"
            class="flex items-center justify-between py-3 active:bg-gray-50"
            @click="goToTask(task.id)"
          >
            <view class="flex items-center">
              <view class="w-10 h-10 rounded-full bg-primary-light flex items-center justify-center mr-3">
                <text class="uni-icons uniui-flag text-primary"></text>
              </view>
              <view>
                <text class="text-sm text-gray-800">{{ task.projectName }}</text>
                <text class="text-xs text-gray-400 block">{{ formatDate(task.scheduleDate || task.serviceDate || task.createTime, 'YYYY-MM-DD') }}</text>
              </view>
            </view>
            <StatusTag :status="task.status" />
          </view>
        </view>
        <view v-else class="py-4 text-center">
          <text class="text-sm text-gray-400">暂无关联任务</text>
        </view>
      </view>

      <!-- 底部操作按钮 -->
      <view class="px-4 pt-2 pb-6">
        <button class="w-full py-4 btn-primary rounded-2xl text-base font-semibold flex items-center justify-center" @click="goToPublishTask">
          <text class="uni-icons uniui-plusempty mr-2"></text>
          发布新任务
        </button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useProjectStore } from '../../stores/project'
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 MapView from '../../components/common/MapView.vue'
import { formatDate } from '../../utils'

const projectStore = useProjectStore()
const taskStore = useTaskStore()

const project = computed(() => projectStore.currentProject)
const projectTasks = ref<any[]>([])

const fullAddress = computed(() => {
  if (!project.value) return ''
  const parts = [project.value.province, project.value.city, project.value.district, project.value.address]
  return parts.filter(Boolean).join('')
})

const showContractInfo = computed(() => {
  if (!project.value) return false
  return !!(
    project.value.contractAmount ||
    project.value.contractStartDate ||
    project.value.contractEndDate ||
    project.value.serviceCycle
  )
})

const projectLatitude = computed(() => project.value?.location?.lat || 39.9)
const projectLongitude = computed(() => project.value?.location?.lng || 116.4)

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

function goToTask(taskId: string) {
  taskStore.setCurrentTask(taskId)
  uni.navigateTo({ url: '/subPackages/pages-common/taskDetail' })
}

function goToTaskList() {
  uni.switchTab({ url: '/pages/task/task' })
}

function goToPublishTask() {
  uni.navigateTo({ 
    url: `/subPackages/pages-common/publishTask?projectId=${project.value?.id}` 
  })
}

onMounted(async () => {
  if (!project.value) {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1] as any
    const projectId = currentPage.options?.id
    if (projectId) {
      projectStore.setCurrentProject(projectId)
    }
  }

  if (project.value) {
    await taskStore.fetchTasks()
    projectTasks.value = taskStore.tasks.filter((t) => t.projectId === project.value?.id)
  }
})
</script>
