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

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

    <view v-else-if="!project" class="px-4 py-6">
      <EmptyState icon="uniui-folder-add-filled" text="项目不存在" />
    </view>

    <view v-else class="px-4 py-4 gap-y-4">
      <!-- 头部 -->
      <view class="card p-4">
        <view class="mb-2">
          <text class="text-lg font-bold text-gray-800">{{ project.projectName }}</text>
          <text v-if="project.projectCode" class="text-xs text-gray-400 block mt-1">{{ project.projectCode }}</text>
        </view>
        <view class="flex flex-wrap gap-2 mt-3">
          <text class="chip chip-type px-2.5 py-0.5 rounded-full text-xs">{{ getCooperationTypeText(project.cooperationType) }}</text>
          <text
            v-for="ft in facilityList"
            :key="ft"
            class="chip chip-facility px-2.5 py-0.5 rounded-full text-xs"
          >{{ getFacilityTypeText(ft) }}</text>
        </view>
      </view>

      <!-- 基本信息 -->
      <view class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-info-filled text-primary mr-2"></text>
          <text>基本信息</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">项目名称</text>
          <text class="detail-value font-medium">{{ project.projectName || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">合作类型</text>
          <text class="detail-value">
            <text class="chip chip-type px-2 py-0.5 rounded text-xs">{{ getCooperationTypeText(project.cooperationType) }}</text>
          </text>
        </view>
        <view class="detail-row">
          <text class="detail-label">设施类型</text>
          <text class="detail-value">{{ facilityText }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">项目地址</text>
          <text class="detail-value text-right flex-1">{{ fullAddress || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">累计服务</text>
          <text class="detail-value">
            <text class="text-primary font-bold text-lg">{{ completedTaskCount }}</text>
            <text class="text-xs text-gray-500 ml-1">次</text>
          </text>
        </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="hasLocation" class="mt-1">
          <MapView
            :latitude="projectLatitude"
            :longitude="projectLongitude"
            :title="project.projectName"
            :address="fullAddress"
            :height="180"
          />
        </view>
        <view v-else class="py-6 text-center">
          <text class="text-sm text-gray-400">未设置地图定位</text>
        </view>
      </view>

      <!-- 项目情况介绍 -->
      <view v-if="project.projectDescription" class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-info-filled text-primary mr-2"></text>
          <text>项目情况介绍</text>
        </view>
        <text class="text-sm text-gray-600 leading-relaxed">{{ project.projectDescription }}</text>
      </view>

      <!-- 位置联系人 -->
      <view v-if="locationContacts.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 locationContacts" :key="index" class="contact-item">
          <view class="contact-avatar">
            <text class="uni-icons uniui-person text-primary"></text>
          </view>
          <view class="flex-1 min-w-0 mr-3">
            <text class="text-sm font-medium text-gray-800 block">{{ contact.name || `联系人 ${index + 1}` }}</text>
            <text class="text-xs text-gray-400">{{ maskPhone(contact.phone) }}</text>
          </view>
          <view class="call-btn" @click="callPhone(contact.phone)">
            <text class="uni-icons uniui-phone text-white text-sm"></text>
          </view>
        </view>
      </view>

      <!-- 费用信息 -->
      <view 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 text-xl font-bold text-orange-500">{{ formatMoney(project.contractAmount) }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">付款方式</text>
          <text class="detail-value">{{ getPaymentMethodText(project.paymentMethod || '') }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">合同状态</text>
          <text class="detail-value">
            <text
              class="px-2 py-0.5 rounded text-xs font-medium"
              :style="{ backgroundColor: contractStatusBg, color: contractStatusColor }"
            >{{ contractStatusText }}</text>
          </text>
        </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="servicePointList.length > 0">
          <view
            v-for="(point, index) in servicePointList"
            :key="index"
            class="service-point-item"
            :class="{ 'border-t border-gray-100': index > 0 }"
          >
            <view class="flex items-center justify-between mb-2">
              <view class="flex items-center min-w-0">
                <text class="text-sm font-medium text-gray-800 truncate">服务点{{ index + 1 }}：{{ point.name || '未命名' }}</text>
              </view>
              <text
                class="px-2 py-0.5 rounded text-xs font-medium flex-shrink-0 ml-2"
                :style="{ backgroundColor: index === 0 ? 'rgba(164, 216, 152, 0.22)' : '#f3f4f6', color: index === 0 ? '#368f6f' : '#6b7280' }"
              >{{ index === 0 ? '主服务点' : '正常' }}</text>
            </view>
            <view class="space-y-1">
              <view class="flex items-center">
                <text class="uni-icons uniui-location-filled text-gray-400 text-xs mr-1.5"></text>
                <text class="text-xs text-gray-500">位置：{{ point.address || '-' }}</text>
              </view>
              <view class="flex items-center">
                <text class="uni-icons uniui-settings-filled text-gray-400 text-xs mr-1.5"></text>
                <text class="text-xs text-gray-500">服务项：</text>
                <text class="px-2 py-0.5 bg-primary-light text-primary rounded text-xs">{{ point.serviceItem || point.serviceType || '-' }}</text>
              </view>
              <view class="flex items-center">
                <text class="uni-icons uniui-clock text-gray-400 text-xs mr-1.5"></text>
                <text class="text-xs text-gray-400">最近服务：{{ getLastServiceTime(point) }}</text>
              </view>
            </view>
          </view>
        </view>
        <view v-else class="py-4 text-center">
          <text class="text-sm text-gray-400">暂无服务点信息</text>
        </view>
      </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="px-4 pt-2 pb-6 flex gap-3">
        <button
          class="flex-1 py-4 btn-ghost rounded-2xl text-base font-semibold flex items-center justify-center"
          @click="goToEdit"
        >
          <text class="uni-icons uniui-compose mr-2"></text>
          编辑项目
        </button>
        <button
          class="flex-1 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 } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { Project, ServicePoint, Task } from '../../types'
import { getProjectDetail } from '../../api/project'
import { getTasksByProjectId } from '../../api/task'
import {
  formatMoney,
  parseJsonArray,
  parseLocationContacts,
  getCooperationTypeText,
  getFacilityTypeText,
  getPaymentMethodText,
  getContractStatusText,
  getContractStatusColor,
  getContractStatusBgColor
} from '../../utils'
import TopBar from '../../components/common/TopBar.vue'
import EmptyState from '../../components/common/EmptyState.vue'
import MapView from '../../components/common/MapView.vue'

const project = ref<Project | null>(null)
const tasks = ref<Task[]>([])
const loading = ref(true)
const projectId = ref<number | string>('')

const facilityList = computed(() => parseJsonArray<string>(project.value?.facilityTypes))
const facilityText = computed(() => {
  const list = facilityList.value
  if (list.length === 0) return '-'
  return list.map(t => getFacilityTypeText(t)).join('、')
})
const servicePointList = computed(() => parseJsonArray<ServicePoint>(project.value?.servicePoints))
const locationContacts = computed(() => parseLocationContacts(project.value?.locationContacts))

const completedTaskCount = computed(() => tasks.value.filter(t => t.status === 'completed').length)

const contractStatusText = computed(() => getContractStatusText(project.value?.contractStatus || ''))
const contractStatusColor = computed(() => getContractStatusColor(project.value?.contractStatus || ''))
const contractStatusBg = computed(() => getContractStatusBgColor(project.value?.contractStatus || ''))

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

const hasLocation = computed(() => !!(project.value?.latitude && project.value?.longitude))
const projectLatitude = computed(() => Number(project.value?.latitude) || 39.9)
const projectLongitude = computed(() => Number(project.value?.longitude) || 116.4)

function maskPhone(phone?: string) {
  if (!phone) return ''
  if (phone.length === 11) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
  }
  return phone
}

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

function getPointTasks(point: ServicePoint) {
  return tasks.value.filter(t =>
    t.status === 'completed' &&
    (t.address?.includes(point.name || '') || t.faultLocation?.includes(point.name || ''))
  )
}

function getLastServiceTime(point: ServicePoint) {
  const pointTasks = getPointTasks(point)
  if (pointTasks.length === 0) return '暂无服务记录'
  const sorted = pointTasks.slice().sort((a, b) => {
    const ta = new Date(a.completionTime || a.updateTime || 0).getTime()
    const tb = new Date(b.completionTime || b.updateTime || 0).getTime()
    return tb - ta
  })
  const time = sorted[0]?.completionTime || sorted[0]?.updateTime
  return time || '暂无'
}

function goToEdit() {
  uni.navigateTo({ url: `/subPackages/pages-common/addProject?mode=edit&id=${projectId.value}` })
}

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

async function loadDetail(id: number | string) {
  loading.value = true
  try {
    const [p, taskList] = await Promise.all([
      getProjectDetail(id),
      getTasksByProjectId(id).catch(() => [])
    ])
    project.value = p
    tasks.value = Array.isArray(taskList) ? taskList : []
  } catch (e) {
    project.value = null
    tasks.value = []
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  const id = options?.id
  if (id) {
    projectId.value = id
    loadDetail(id)
  } else {
    loading.value = false
  }
})
</script>

<style scoped>
.detail-page {
  background-color: #f6fbf9;
}

.card {
  border-radius: 20px;
  margin-bottom: 0;
  border: 1px solid rgba(164, 216, 152, 0.28);
  box-shadow: 0 14px 34px -18px rgba(54, 143, 111, 0.35);
}

.detail-section-title {
  padding: 0;
  border-bottom: none;
  margin-bottom: 12px;
}
.text-primary {
  color: #368f6f;
}

/* 头部标签 */
.chip {
  font-weight: 500;
}
.chip-type {
  background-color: rgba(164, 216, 152, 0.22);
  color: #368f6f;
}
.chip-facility {
  background-color: #f3f4f6;
  color: #6b7280;
}

/* 服务点类型标签 */
.bg-primary-light {
  background-color: rgba(164, 216, 152, 0.22);
}

/* 联系人 */
.contact-item {
  display: flex;
  align-items: center;
  padding: 10px 0;
}
.contact-item + .contact-item {
  border-top: 1px solid rgba(164, 216, 152, 0.20);
}
.contact-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: rgba(164, 216, 152, 0.22);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  flex-shrink: 0;
}
.call-btn {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  box-shadow: 0 6px 14px -6px rgba(54, 143, 111, 0.55);
}
.call-btn:active {
  opacity: 0.92;
  transform: scale(0.94);
}

/* 服务点 */
.service-point-item {
  padding: 14px 0;
}
.service-point-item:first-child {
  padding-top: 0;
}

/* 操作按钮 */
.btn-ghost {
  background-color: #ffffff;
  border: 1px solid #368f6f;
  color: #368f6f;
}
.btn-ghost:active {
  background-color: rgba(164, 216, 152, 0.12);
}
.btn-primary {
  background: linear-gradient(135deg, #368f6f 0%, #5ab8d0 100%);
  box-shadow: 0 10px 22px -10px rgba(54, 143, 111, 0.55);
}
</style>
