<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="!contract" class="px-4 py-6">
      <EmptyState text="合同不存在" />
    </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-3">
          <view class="min-w-0 mr-3">
            <text class="text-base font-bold text-gray-800 block truncate">{{ contract.contractNo }}</text>
            <text class="card-sub block mt-0.5">合同编号</text>
          </view>
          <view
            class="status-pill px-2.5 py-0.5 rounded-full text-xs flex-shrink-0"
            :style="{ backgroundColor: statusBg(contract.status), color: statusColor(contract.status) }"
          >
            {{ statusText(contract.status) }}
          </view>
        </view>
        <view class="amount-hero rounded-2xl p-4 text-center">
          <text class="amount-hero-label block mb-1">合同金额</text>
          <text class="amount-hero-value">{{ formatMoney(contract.contractAmount) }}</text>
        </view>
      </view>

      <!-- 合同信息 -->
      <view class="card p-4">
        <view class="detail-section-title">
          <text class="uni-icons uniui-file-text-filled text-primary mr-2"></text>
          <text>合同信息</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">付款方式</text>
          <text class="detail-value">{{ getPaymentMethodText(contract.paymentMethod) }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">签订日期</text>
          <text class="detail-value">{{ contract.signDate || '-' }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">服务开始</text>
          <text class="detail-value">{{ serviceStart }}</text>
        </view>
        <view class="detail-row">
          <text class="detail-label">服务结束</text>
          <text class="detail-value">{{ serviceEnd }}</text>
        </view>
        <view v-if="contract.remark" class="detail-row">
          <text class="detail-label">备注</text>
          <text class="detail-value text-right flex-1">{{ contract.remark }}</text>
        </view>
      </view>

      <!-- 关联客户 -->
      <view 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-if="customer">
          <view class="detail-row">
            <text class="detail-label">客户名称</text>
            <text class="detail-value">{{ customer.customerName }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">联系人</text>
            <text class="detail-value">{{ customer.contactName || '-' }}</text>
          </view>
          <view class="detail-row">
            <text class="detail-label">电话</text>
            <view class="detail-value flex items-center" @click="callPhone(customer.phone)">
              <text class="text-primary">{{ customer.phone || '-' }}</text>
            </view>
          </view>
        </view>
        <view v-else class="py-3">
          <text class="text-xs text-gray-400">客户信息加载中或不存在</text>
        </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>
        <text class="text-xs text-gray-400">后端暂未提供付款记录接口</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-danger-ghost rounded-2xl text-base font-semibold flex items-center justify-center"
          @click="onDelete"
        >
          <text class="uni-icons uniui-trash 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 { Contract, Customer } from '../../types'
import { getContractDetail, deleteContract } from '../../api/contract'
import { getCustomerDetail } from '../../api/customer'
import {
  formatMoney,
  getPaymentMethodText,
  getContractStatusText,
  getContractStatusColor,
  getContractStatusBgColor
} from '../../utils'
import TopBar from '../../components/common/TopBar.vue'
import EmptyState from '../../components/common/EmptyState.vue'

const contract = ref<Contract | null>(null)
const customer = ref<Customer | null>(null)
const loading = ref(true)
const contractId = ref<number | string>('')

const statusText = getContractStatusText
const statusColor = getContractStatusColor
const statusBg = getContractStatusBgColor

const serviceParts = computed(() => {
  const sp = contract.value?.servicePeriod || ''
  const parts = sp.split(' 至 ')
  return {
    start: parts[0] || '-',
    end: parts[1] || '-'
  }
})
const serviceStart = computed(() => serviceParts.value.start)
const serviceEnd = computed(() => serviceParts.value.end)

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

function goToEdit() {
  uni.navigateTo({ url: `/subPackages/pages-contract/contractForm?id=${contractId.value}` })
}

function onDelete() {
  uni.showModal({
    title: '确认删除',
    content: '删除后无法恢复，是否继续？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await deleteContract(contractId.value)
          uni.showToast({ title: '已删除', icon: 'success' })
          setTimeout(() => uni.navigateBack(), 800)
        } catch (e) {
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

async function loadDetail(id: number | string) {
  loading.value = true
  try {
    const c = await getContractDetail(id)
    contract.value = c
    if (c.customerId) {
      try {
        customer.value = await getCustomerDetail(c.customerId)
      } catch (e) {
        customer.value = null
      }
    }
  } catch (e) {
    contract.value = null
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  const id = options?.id
  if (id) {
    contractId.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);
}

/* 区块标题：去掉全局 padding/分割线，图标改青山绿 */
.detail-section-title {
  padding: 0;
  border-bottom: none;
  margin-bottom: 12px;
}
.text-primary {
  color: #368f6f;
}

.card-sub {
  font-size: 11px;
  color: #b6c9be;
}
.status-pill {
  font-weight: 500;
}

/* 金额 hero */
.amount-hero {
  background: linear-gradient(135deg, rgba(164, 216, 152, 0.22) 0%, rgba(90, 184, 208, 0.16) 100%);
  border: 1px solid rgba(164, 216, 152, 0.30);
}
.amount-hero-label {
  font-size: 12px;
  color: #6b8a7a;
}
.amount-hero-value {
  font-size: 26px;
  font-weight: 700;
  color: #2f7a5e;
  letter-spacing: 0.5px;
}

/* 操作按钮 */
.btn-ghost {
  background-color: #ffffff;
  border: 1px solid #368f6f;
  color: #368f6f;
}
.btn-ghost:active {
  background-color: rgba(164, 216, 152, 0.12);
}
.btn-danger-ghost {
  background-color: #ffffff;
  border: 1px solid #fca5a5;
  color: #ef4444;
}
.btn-danger-ghost:active {
  background-color: #fef2f2;
}
</style>
