<template>
  <div class="project-list">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>项目清单</h1>
    </div>

    <!-- 导航标签和搜索 -->
    <div class="nav-section">
      <div class="nav-tabs">
        <div 
          class="nav-tab" 
          :class="{ active: activeTab === 'all' }"
          @click="setActiveTab('all')"
        >
          全部
        </div>
        <div 
          class="nav-tab" 
          :class="{ active: activeTab === 'supervision' }"
          @click="setActiveTab('supervision')"
        >
          监管中
        </div>
        <div 
          class="nav-tab" 
          :class="{ active: activeTab === 'completed' }"
          @click="setActiveTab('completed')"
        >
          已结项
        </div>
      </div>
      
      <div class="search-section">
        <a-input
          v-model:value="searchText"
          placeholder="请输入项目名称"
          class="search-input"
        />
        <a-button type="primary" @click="handleSearch" class="search-btn">Q 搜索</a-button>
        <a-button @click="handleReset" class="reset-btn">重置</a-button>
      </div>
    </div>

    <!-- 项目卡片网格 -->
    <div class="projects-grid">
      <!-- 添加新项目卡片 -->
      <div class="project-card add-card" @click="showAddProjectModal">
        <div class="add-icon">
          <plus-outlined />
        </div>
      </div>

      <!-- 项目卡片 -->
      <div 
        v-for="project in filteredProjects" 
        :key="project.id" 
        class="project-card"
        @click="viewProject(project)"
      >
        <div class="card-header">
          <div class="project-name">{{ project.name }}</div>
          <div class="status-tag" :class="project.status">
            {{ getStatusName(project.status) }}
          </div>
        </div>
        
        <div class="card-content">
          <div class="info-row">
            <span class="label">养殖场名称:</span>
            <span class="value">{{ project.farmName }}</span>
          </div>
          <div class="info-row">
            <span class="label">监管对象:</span>
            <span class="value">{{ project.supervisionObject }}</span>
          </div>
          <div class="info-row">
            <span class="label">监管数量:</span>
            <span class="value">{{ project.supervisionQuantity }}</span>
          </div>
          <div class="info-row">
            <span class="label">监管周期:</span>
            <span class="value">{{ project.supervisionPeriod }}</span>
          </div>
          <div class="info-row">
            <span class="label">监管金额:</span>
            <span class="value">{{ formatAmount(project.supervisionAmount) }}</span>
          </div>
          <div class="info-row">
            <span class="label">起始时间:</span>
            <span class="value">{{ project.startTime }}至{{ project.endTime }}</span>
          </div>
          <div class="info-row">
            <span class="label">耳标:</span>
            <span class="value">{{ project.earTag }}</span>
          </div>
          <div class="info-row">
            <span class="label">项圈:</span>
            <span class="value">{{ project.collar }}</span>
          </div>
          <div class="info-row">
            <span class="label">主机:</span>
            <span class="value">{{ project.host }}</span>
          </div>
          <div class="info-row">
            <span class="label">贷款专员:</span>
            <span class="value">{{ project.loanOfficer || '-' }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 项目详情对话框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="项目详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedProject" class="project-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="项目名称">
            {{ selectedProject.name }}
          </a-descriptions-item>
          <a-descriptions-item label="项目状态">
            <a-tag :color="getStatusColor(selectedProject.status)">
              {{ getStatusName(selectedProject.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="养殖场名称">
            {{ selectedProject.farmName }}
          </a-descriptions-item>
          <a-descriptions-item label="监管对象">
            {{ selectedProject.supervisionObject }}
          </a-descriptions-item>
          <a-descriptions-item label="监管数量">
            {{ selectedProject.supervisionQuantity }}
          </a-descriptions-item>
          <a-descriptions-item label="监管周期">
            {{ selectedProject.supervisionPeriod }}
          </a-descriptions-item>
          <a-descriptions-item label="监管金额">
            {{ formatAmount(selectedProject.supervisionAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="起始时间">
            {{ selectedProject.startTime }} 至 {{ selectedProject.endTime }}
          </a-descriptions-item>
          <a-descriptions-item label="贷款专员">
            {{ selectedProject.loanOfficer || '-' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 新增项目对话框 -->
    <a-modal
      v-model:open="addModalVisible"
      title="新增项目"
      width="800px"
      @ok="handleAddProject"
      @cancel="handleCancelAdd"
      :confirmLoading="addLoading"
    >
      <a-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="项目名称" name="name">
              <a-input v-model:value="addForm.name" placeholder="请输入项目名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="项目状态" name="status">
              <a-select v-model:value="addForm.status" placeholder="请选择项目状态">
                <a-select-option value="supervision">监管中</a-select-option>
                <a-select-option value="completed">已结项</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="养殖场名称" name="farmName">
              <a-input v-model:value="addForm.farmName" placeholder="请输入养殖场名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="监管对象" name="supervisionObject">
              <a-input v-model:value="addForm.supervisionObject" placeholder="请输入监管对象" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="监管数量" name="supervisionQuantity">
              <a-input-number 
                v-model:value="addForm.supervisionQuantity" 
                :min="0" 
                placeholder="请输入监管数量"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="监管周期" name="supervisionPeriod">
              <a-input v-model:value="addForm.supervisionPeriod" placeholder="请输入监管周期" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="监管金额" name="supervisionAmount">
              <a-input-number 
                v-model:value="addForm.supervisionAmount" 
                :min="0" 
                :precision="2"
                placeholder="请输入监管金额"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="起始时间" name="startTime">
              <a-date-picker 
                v-model:value="addForm.startTime" 
                placeholder="请选择起始时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结束时间" name="endTime">
              <a-date-picker 
                v-model:value="addForm.endTime" 
                placeholder="请选择结束时间"
                style="width: 100%"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="耳标数量" name="earTag">
              <a-input-number 
                v-model:value="addForm.earTag" 
                :min="0" 
                placeholder="请输入耳标数量"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="项圈数量" name="collar">
              <a-input-number 
                v-model:value="addForm.collar" 
                :min="0" 
                placeholder="请输入项圈数量"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="主机数量" name="host">
              <a-input-number 
                v-model:value="addForm.host" 
                :min="0" 
                placeholder="请输入主机数量"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款专员" name="loanOfficer">
              <a-input v-model:value="addForm.loanOfficer" placeholder="请输入贷款专员" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="项目描述" name="description">
          <a-textarea 
            v-model:value="addForm.description" 
            placeholder="请输入项目描述"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { api } from '@/utils/api'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const searchText = ref('')
const activeTab = ref('all')
const detailModalVisible = ref(false)
const selectedProject = ref(null)

// 新增项目相关
const addModalVisible = ref(false)
const addLoading = ref(false)
const addFormRef = ref(null)
const addForm = ref({
  name: '',
  status: 'supervision',
  farmName: '',
  supervisionObject: '',
  supervisionQuantity: 0,
  supervisionPeriod: '',
  supervisionAmount: 0,
  startTime: '',
  endTime: '',
  earTag: 0,
  collar: 0,
  host: 0,
  loanOfficer: '',
  description: ''
})

// 项目数据
const projects = ref([])

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

// 新增项目表单验证规则
const addFormRules = ref({
  name: [
    { required: true, message: '请输入项目名称', trigger: 'blur' },
    { max: 100, message: '项目名称不能超过100个字符', trigger: 'blur' }
  ],
  farmName: [
    { required: true, message: '请输入养殖场名称', trigger: 'blur' },
    { max: 200, message: '养殖场名称不能超过200个字符', trigger: 'blur' }
  ],
  supervisionObject: [
    { required: true, message: '请输入监管对象', trigger: 'blur' },
    { max: 50, message: '监管对象不能超过50个字符', trigger: 'blur' }
  ],
  supervisionPeriod: [
    { required: true, message: '请输入监管周期', trigger: 'blur' },
    { max: 50, message: '监管周期不能超过50个字符', trigger: 'blur' }
  ],
  startTime: [
    { required: true, message: '请选择起始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  supervisionQuantity: [
    { type: 'number', min: 0, message: '监管数量不能为负数', trigger: 'blur' }
  ],
  supervisionAmount: [
    { type: 'number', min: 0, message: '监管金额不能为负数', trigger: 'blur' }
  ],
  earTag: [
    { type: 'number', min: 0, message: '耳标数量不能为负数', trigger: 'blur' }
  ],
  collar: [
    { type: 'number', min: 0, message: '项圈数量不能为负数', trigger: 'blur' }
  ],
  host: [
    { type: 'number', min: 0, message: '主机数量不能为负数', trigger: 'blur' }
  ],
  loanOfficer: [
    { max: 100, message: '贷款专员不能超过100个字符', trigger: 'blur' }
  ]
})

// 计算属性
const filteredProjects = computed(() => {
  return projects.value
})

// 方法
const setActiveTab = (tab) => {
  activeTab.value = tab
  fetchProjects()
}

const handleSearch = () => {
  pagination.value.current = 1
  fetchProjects()
}

const handleReset = () => {
  searchText.value = ''
  activeTab.value = 'all'
  pagination.value.current = 1
  fetchProjects()
}

const getStatusName = (status) => {
  const names = {
    'supervision': '监管中',
    'completed': '已结项'
  }
  return names[status] || status
}

const getStatusColor = (status) => {
  const colors = {
    'supervision': 'blue',
    'completed': 'gray'
  }
  return colors[status] || 'default'
}

const formatAmount = (amount) => {
  if (amount === null || amount === undefined || amount === '') {
    return '0.00元'
  }
  const numAmount = parseFloat(amount)
  if (isNaN(numAmount)) {
    return '0.00元'
  }
  return `${numAmount.toFixed(2)}元`
}

const showAddProjectModal = () => {
  addModalVisible.value = true
  // 重置表单
  addForm.value = {
    name: '',
    status: 'supervision',
    farmName: '',
    supervisionObject: '',
    supervisionQuantity: 0,
    supervisionPeriod: '',
    supervisionAmount: 0,
    startTime: '',
    endTime: '',
    earTag: 0,
    collar: 0,
    host: 0,
    loanOfficer: '',
    description: ''
  }
}

const viewProject = (project) => {
  // 跳转到项目详情页面
  router.push({
    name: 'ProjectDetail',
    params: { id: project.id }
  })
}

// 新增项目处理函数
const handleAddProject = async () => {
  try {
    // 验证表单
    await addFormRef.value.validate()
    
    // 验证日期逻辑
    if (addForm.value.startTime && addForm.value.endTime) {
      const startDate = new Date(addForm.value.startTime)
      const endDate = new Date(addForm.value.endTime)
      if (startDate >= endDate) {
        message.error('结束时间必须晚于开始时间')
        return
      }
    }

    addLoading.value = true
    
    // 调用API创建项目
    const response = await api.projects.create(addForm.value)
    
    if (response.success) {
      message.success('项目创建成功')
      addModalVisible.value = false
      // 刷新项目列表
      await fetchProjects()
    } else {
      message.error(response.message || '创建项目失败')
    }
  } catch (error) {
    console.error('创建项目失败:', error)
    if (error.response && error.response.data) {
      message.error(error.response.data.message || '创建项目失败')
    } else {
      message.error('创建项目失败: ' + error.message)
    }
  } finally {
    addLoading.value = false
  }
}

// 取消新增项目
const handleCancelAdd = () => {
  addModalVisible.value = false
  addFormRef.value?.resetFields()
}

// API调用函数
const fetchProjects = async (params = {}) => {
  try {
    loading.value = true
    console.log('开始获取项目列表...', {
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      search: searchText.value,
      status: activeTab.value === 'all' ? '' : activeTab.value
    })
    
    const response = await api.projects.getList({
      page: pagination.value.current,
      limit: pagination.value.pageSize,
      search: searchText.value,
      status: activeTab.value === 'all' ? '' : activeTab.value,
      ...params
    })
    
    console.log('项目列表响应:', response)
    
    if (response.success) {
      projects.value = response.data.projects || []
      pagination.value.total = response.data.pagination?.total || 0
      console.log('项目数据已更新:', projects.value.length, '个项目')
    } else {
      console.error('API返回错误:', response.message)
      message.error(response.message || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    message.error('获取项目列表失败: ' + error.message)
  } finally {
    loading.value = false
  }
}

const handleTableChange = (paginationInfo) => {
  pagination.value = paginationInfo
  fetchProjects()
}

onMounted(() => {
  fetchProjects()
})
</script>

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

.page-header {
  margin-bottom: 24px;
  padding: 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header h1 {
  margin: 0;
  font-size: 28px;
  font-weight: 600;
  color: #333;
}

.nav-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 24px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.nav-tabs {
  display: flex;
  gap: 0;
}

.nav-tab {
  padding: 8px 24px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  color: #666;
  font-size: 16px;
  transition: all 0.3s;
}

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

.nav-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  font-weight: 500;
}

.search-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-input {
  width: 300px;
}

.search-btn {
  background: #1890ff;
  border-color: #1890ff;
}

.reset-btn {
  color: #666;
  border-color: #d9d9d9;
}

.projects-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  padding: 0;
}

.project-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
}

.project-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.add-card {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
  border: 2px dashed #d9d9d9;
  background: #fafafa;
}

.add-card:hover {
  border-color: #1890ff;
  background: #f0f8ff;
}

.add-icon {
  font-size: 48px;
  color: #d9d9d9;
}

.add-card:hover .add-icon {
  color: #1890ff;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.project-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.status-tag {
  padding: 4px 12px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: white;
}

.status-tag.supervision {
  background: #1890ff;
}

.status-tag.completed {
  background: #8c8c8c;
}

.card-content {
  padding: 20px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 14px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.label {
  color: #666;
  font-weight: 500;
  min-width: 80px;
}

.value {
  color: #333;
  font-weight: 400;
  text-align: right;
  flex: 1;
  margin-left: 12px;
}

.project-detail {
  padding: 16px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .projects-grid {
    grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  }
}

@media (max-width: 768px) {
  .nav-section {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .nav-tabs {
    justify-content: center;
  }
  
  .search-section {
    justify-content: center;
  }
  
  .search-input {
    width: 200px;
  }
  
  .projects-grid {
    grid-template-columns: 1fr;
  }
}
</style>