<template>
  <div class="project-detail">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <h1>
          <a-button type="text" @click="goBack" class="back-button">
            <arrow-left-outlined />
            返回
          </a-button>
          {{ projectDetail.name || '项目详情' }}
        </h1>
      </div>
      <div class="header-right">
        <a-button type="primary" @click="editProject">
          <edit-outlined />
          编辑项目
        </a-button>
      </div>
    </div>

    <!-- 项目基本信息 -->
    <div class="project-info-section">
      <a-row :gutter="24">
        <a-col :span="8">
          <div class="info-group">
            <div class="info-item">
              <span class="label">养殖场名称:</span>
              <span class="value">{{ projectDetail.farmName || '158****8989 养殖场' }}</span>
            </div>
            <div class="info-item">
              <span class="label">监管周期:</span>
              <span class="value">{{ projectDetail.supervisionPeriod || '1827天' }}</span>
            </div>
            <div class="info-item">
              <span class="label">耳标设备:</span>
              <span class="value">{{ projectDetail.earTagDevices || '0' }}</span>
            </div>
            <div class="info-item">
              <span class="label">饲喂机设备:</span>
              <span class="value">{{ projectDetail.feedingDevices || '0' }}</span>
            </div>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="info-group">
            <div class="info-item">
              <span class="label">监管对象:</span>
              <span class="value">{{ projectDetail.supervisionObject || '牛' }}</span>
            </div>
            <div class="info-item">
              <span class="label">监管金额:</span>
              <span class="value amount">{{ formatAmount(projectDetail.supervisionAmount || 500000) }}</span>
            </div>
            <div class="info-item">
              <span class="label">项圈设备:</span>
              <span class="value">{{ projectDetail.collarDevices || '0' }}</span>
            </div>
            <div class="info-item">
              <span class="label">养殖地址:</span>
              <span class="value">{{ projectDetail.farmAddress || '内蒙古自治区通辽市扎鲁特旗阿日昆都楞镇嘎查村:阿木古楞' }}</span>
            </div>
          </div>
        </a-col>
        <a-col :span="8">
          <div class="info-group">
            <div class="info-item">
              <span class="label">监管数量:</span>
              <span class="value">{{ projectDetail.supervisionQuantity || '36头' }}</span>
            </div>
            <div class="info-item">
              <span class="label">时间范围:</span>
              <span class="value">{{ projectDetail.timeRange || '2023-05-08~2028-05-08' }}</span>
            </div>
            <div class="info-item">
              <span class="label">主机设备:</span>
              <span class="value">{{ projectDetail.mainDevices || '0' }}</span>
            </div>
            <div class="info-item">
              <span class="label">担保机构:</span>
              <span class="value">{{ projectDetail.guaranteeInstitution || '无' }}</span>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 导航标签 -->
    <div class="nav-tabs">
      <div 
        v-for="tab in tabs" 
        :key="tab.key"
        class="nav-tab"
        :class="{ active: activeTab === tab.key }"
        @click="setActiveTab(tab.key)"
      >
        {{ tab.title }}
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <div class="metrics-section">
      <a-row :gutter="24">
        <a-col :span="6">
          <div class="metric-card">
            <div class="metric-icon orange">
              <dollar-circle-outlined />
            </div>
            <div class="metric-content">
              <div class="metric-title">当前生资总估值</div>
              <div class="metric-value red">{{ formatAmount(projectDetail.totalValuation || 0) }}</div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="metric-card">
            <div class="metric-icon yellow">
              <fund-outlined />
            </div>
            <div class="metric-content">
              <div class="metric-title">项目贷款额度</div>
              <div class="metric-value red">{{ formatAmount(projectDetail.loanAmount || 500000) }}</div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="metric-card">
            <div class="metric-icon blue">
              <pie-chart-outlined />
            </div>
            <div class="metric-content">
              <div class="metric-title">抵押生资总数量</div>
              <div class="metric-value blue">{{ projectDetail.mortgagedQuantity || 36 }}</div>
            </div>
          </div>
        </a-col>
        <a-col :span="6">
          <div class="metric-card">
            <div class="metric-icon orange">
              <file-text-outlined />
            </div>
            <div class="metric-content">
              <div class="metric-title">风险评估</div>
              <div class="metric-value">
                <a-tag color="green" class="risk-tag">低风险</a-tag>
                <a-button type="link" size="small" class="dynamic-btn">动态估值</a-button>
              </div>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'estimatedValue'">
            {{ formatAmount(record.estimatedValue) }}
          </template>
          <template v-else-if="column.key === 'exitValue'">
            {{ formatAmount(record.exitValue) }}
          </template>
          <template v-else-if="column.key === 'photo'">
            <a-button type="link" size="small">查看</a-button>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small">编辑</a-button>
              <a-button type="link" size="small">删除</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { api } from '@/utils/api'
import { 
  EditOutlined, 
  ArrowLeftOutlined,
  DollarCircleOutlined, 
  FundOutlined, 
  PieChartOutlined, 
  FileTextOutlined 
} from '@ant-design/icons-vue'

const route = useRoute()
const router = useRouter()

// 响应式数据
const loading = ref(false)
const activeTab = ref('valuation')
const projectDetail = ref({})
const tableData = ref([])

// 标签页配置
const tabs = ref([
  { key: 'supervision', title: '生资监管' },
  { key: 'valuation', title: '生资估值' },
  { key: 'earTag', title: '耳标设备' },
  { key: 'collar', title: '项圈设备' },
  { key: 'main', title: '主机设备' },
  { key: 'video', title: '视频设备' },
  { key: 'pen', title: '栏舍信息' },
  { key: 'log', title: '处理日志' }
])

// 表格列配置
const columns = ref([
  {
    title: '监管设备编号',
    dataIndex: 'deviceId',
    key: 'deviceId',
    width: 150
  },
  {
    title: '牧畜档案编号',
    dataIndex: 'livestockId',
    key: 'livestockId',
    width: 150
  },
  {
    title: '生资品种',
    dataIndex: 'breed',
    key: 'breed',
    width: 120
  },
  {
    title: '养殖地',
    dataIndex: 'location',
    key: 'location',
    width: 150
  },
  {
    title: '当前月龄',
    dataIndex: 'age',
    key: 'age',
    width: 100
  },
  {
    title: '当前预估价值',
    dataIndex: 'estimatedValue',
    key: 'estimatedValue',
    width: 150
  },
  {
    title: '预计出栏时间',
    dataIndex: 'exitTime',
    key: 'exitTime',
    width: 150
  },
  {
    title: '预计出栏体重',
    dataIndex: 'exitWeight',
    key: 'exitWeight',
    width: 150
  },
  {
    title: '预计出栏价值',
    dataIndex: 'exitValue',
    key: 'exitValue',
    width: 150
  },
  {
    title: '评估登记照',
    dataIndex: 'photo',
    key: 'photo',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    fixed: 'right'
  }
])

// 分页配置
const pagination = ref({
  current: 1,
  pageSize: 15,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共${total}条`
})

// 方法
const setActiveTab = (tabKey) => {
  activeTab.value = tabKey
  // 根据标签页加载不同数据
  loadTabData(tabKey)
}

const loadTabData = async (tabKey) => {
  loading.value = true
  try {
    // 这里根据不同的标签页加载不同的数据
    // 目前先使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 500))
    tableData.value = []
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const loadProjectDetail = async () => {
  try {
    const projectId = route.params.id
    if (!projectId) {
      message.error('项目ID不存在')
      router.back()
      return
    }

    loading.value = true
    
    // 调用API获取项目详情
    const response = await api.projects.getById(projectId)
    
    if (response.success) {
      const project = response.data
      projectDetail.value = {
        id: project.id,
        name: project.name || '项目详情',
        farmName: project.farmName || '158****8989 养殖场',
        supervisionPeriod: project.supervisionPeriod || '1827天',
        earTagDevices: project.earTagDevices || '0',
        feedingDevices: project.feedingDevices || '0',
        supervisionObject: project.supervisionObject || '牛',
        supervisionAmount: project.supervisionAmount || 500000,
        collarDevices: project.collarDevices || '0',
        farmAddress: project.farmAddress || '内蒙古自治区通辽市扎鲁特旗阿日昆都楞镇嘎查村:阿木古楞',
        supervisionQuantity: project.supervisionQuantity || '36头',
        timeRange: project.timeRange || '2023-05-08~2028-05-08',
        mainDevices: project.mainDevices || '0',
        guaranteeInstitution: project.guaranteeInstitution || '无',
        totalValuation: project.totalValuation || 0,
        loanAmount: project.loanAmount || 500000,
        mortgagedQuantity: project.mortgagedQuantity || 36,
        status: project.status,
        description: project.description,
        loanOfficer: project.loanOfficer,
        createdAt: project.createdAt,
        updatedAt: project.updatedAt
      }
    } else {
      throw new Error(response.message || '获取项目详情失败')
    }
  } catch (error) {
    console.error('加载项目详情失败:', error)
    message.error('加载项目详情失败')
    
    // 如果API调用失败，使用模拟数据作为降级处理
    const projectId = route.params.id
    projectDetail.value = {
      id: projectId,
      name: '敖日布仁琴',
      farmName: '158****8989 养殖场',
      supervisionPeriod: '1827天',
      earTagDevices: '0',
      feedingDevices: '0',
      supervisionObject: '牛',
      supervisionAmount: 500000,
      collarDevices: '0',
      farmAddress: '内蒙古自治区通辽市扎鲁特旗阿日昆都楞镇嘎查村:阿木古楞',
      supervisionQuantity: '36头',
      timeRange: '2023-05-08~2028-05-08',
      mainDevices: '0',
      guaranteeInstitution: '无',
      totalValuation: 0,
      loanAmount: 500000,
      mortgagedQuantity: 36
    }
  } finally {
    loading.value = false
  }
}

const goBack = () => {
  router.back()
}

const editProject = () => {
  message.info('编辑项目功能开发中')
}

const formatAmount = (amount) => {
  return `${amount.toFixed(2)}元`
}

const handleTableChange = (pag) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  loadTabData(activeTab.value)
}

// 生命周期
onMounted(() => {
  loadProjectDetail()
  loadTabData(activeTab.value)
})
</script>

<style scoped>
.project-detail {
  padding: 24px;
  background-color: #f0f2f5;
  min-height: calc(100vh - 134px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
  display: flex;
  align-items: center;
}

.back-button {
  margin-right: 12px;
  color: #1890ff;
  font-size: 16px;
  padding: 0;
  height: auto;
  line-height: 1;
}

.back-button:hover {
  color: #40a9ff;
  background: transparent;
}

.back-button .anticon {
  margin-right: 4px;
}

.project-info-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.info-group {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #666;
  min-width: 100px;
  flex-shrink: 0;
}

.info-item .value {
  color: #262626;
  flex: 1;
}

.info-item .value.amount {
  color: #ff4d4f;
  font-weight: 600;
}

.nav-tabs {
  display: flex;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 24px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow-x: auto;
}

.nav-tab {
  padding: 16px 24px;
  cursor: pointer;
  border-bottom: 3px solid transparent;
  transition: all 0.3s;
  white-space: nowrap;
  color: #666;
}

.nav-tab:hover {
  color: #1890ff;
}

.nav-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  background-color: #f6ffed;
}

.metrics-section {
  margin-bottom: 24px;
}

.metric-card {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  display: flex;
  align-items: center;
  gap: 16px;
  height: 100%;
}

.metric-icon {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #fff;
}

.metric-icon.orange {
  background-color: #fa8c16;
}

.metric-icon.yellow {
  background-color: #fadb14;
}

.metric-icon.blue {
  background-color: #1890ff;
}

.metric-content {
  flex: 1;
}

.metric-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 8px;
}

.metric-value {
  font-size: 20px;
  font-weight: 600;
}

.metric-value.red {
  color: #ff4d4f;
}

.metric-value.blue {
  color: #1890ff;
}

.risk-tag {
  margin-right: 8px;
}

.dynamic-btn {
  padding: 0;
  height: auto;
}

.table-section {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .project-detail {
    padding: 16px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: flex-start;
  }
  
  .nav-tabs {
    flex-wrap: wrap;
  }
  
  .nav-tab {
    padding: 12px 16px;
  }
  
  .metric-card {
    flex-direction: column;
    text-align: center;
  }
}
</style>
