<template>
  <div class="loan-applications-page">
    <div class="page-header">
      <h1>贷款申请进度</h1>
    </div>

    <div class="search-filter-section">
      <a-row :gutter="16" align="middle">
        <a-col :span="4">
          <a-select
            v-model:value="searchQuery.field"
            placeholder="申请单号"
            style="width: 100%"
          >
            <a-select-option value="applicationNumber">申请单号</a-select-option>
            <a-select-option value="customerName">客户姓名</a-select-option>
            <a-select-option value="productName">贷款产品</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="8">
          <a-input
            v-model:value="searchQuery.value"
            placeholder="请输入内容"
            allow-clear
          />
        </a-col>
        <a-col :span="4">
          <a-button type="primary" @click="handleSearch">
            <search-outlined /> 搜索
          </a-button>
        </a-col>
        <a-col :span="4">
          <a-button @click="handleReset">重置</a-button>
        </a-col>
      </a-row>
    </div>

    <div class="applications-table-section">
      <a-table
        :columns="columns"
        :data-source="filteredApplications"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        @change="handleTableChange"
        :expand-row-by-click="false"
        :expand-icon-column-index="0"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'policyInfo'">
            <a-button type="link" size="small" @click="viewPolicy(record)">
              查看保单
            </a-button>
          </template>
          <template v-else-if="column.key === 'amount'">
            {{ formatAmount(record.amount) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleReject(record)">
                打回
              </a-button>
              <a-button type="link" size="small" @click="handleApprove(record)">
                通过
              </a-button>
              <a-button type="link" size="small" @click="handleView(record)">
                详情
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 申请详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="申请详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedApplication" class="application-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="申请编号">
            {{ selectedApplication.applicationNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="申请人">
            {{ selectedApplication.applicantName }}
          </a-descriptions-item>
          <a-descriptions-item label="申请类型">
            <a-tag :color="getTypeColor(selectedApplication.type)">
              {{ getTypeText(selectedApplication.type) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="申请状态">
            <a-tag :color="getStatusColor(selectedApplication.status)">
              {{ getStatusText(selectedApplication.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="申请金额">
            {{ formatAmount(selectedApplication.amount) }}
          </a-descriptions-item>
          <a-descriptions-item label="申请期限">
            {{ selectedApplication.term }} 个月
          </a-descriptions-item>
          <a-descriptions-item label="申请时间">
            {{ selectedApplication.applicationTime }}
          </a-descriptions-item>
          <a-descriptions-item label="预计利率">
            {{ selectedApplication.interestRate }}%
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ selectedApplication.phone }}
          </a-descriptions-item>
          <a-descriptions-item label="身份证号">
            {{ selectedApplication.idCard }}
          </a-descriptions-item>
          <a-descriptions-item label="申请用途" :span="2">
            {{ selectedApplication.purpose }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">
            {{ selectedApplication.remark || '无' }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 审核记录 -->
        <div class="audit-records" v-if="selectedApplication.auditRecords">
          <h4>审核记录</h4>
          <a-timeline>
            <a-timeline-item
              v-for="record in selectedApplication.auditRecords"
              :key="record.id"
              :color="getAuditColor(record.action)"
            >
              <div class="audit-item">
                <div class="audit-header">
                  <span class="audit-action">{{ getAuditActionText(record.action) }}</span>
                  <span class="audit-time">{{ record.time }}</span>
                </div>
                <div class="audit-user">审核人：{{ record.auditor }}</div>
                <div class="audit-comment" v-if="record.comment">
                  备注：{{ record.comment }}
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </a-modal>

    <!-- 审核模态框 -->
    <a-modal
      v-model:open="auditModalVisible"
      title="贷款审核"
      @ok="handleAuditSubmit"
      @cancel="handleAuditCancel"
    >
      <a-form :model="auditForm" layout="vertical">
        <a-form-item label="审核结果" required>
          <a-radio-group v-model:value="auditForm.action">
            <a-radio value="approve">通过</a-radio>
            <a-radio value="reject">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="审核意见" required>
          <a-textarea
            v-model:value="auditForm.comment"
            placeholder="请输入审核意见"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

// 响应式数据
const loading = ref(false)
const searchQuery = ref({
  field: 'applicationNumber',
  value: ''
})
const detailModalVisible = ref(false)
const auditModalVisible = ref(false)
const selectedApplication = ref(null)
const auditForm = ref({
  action: 'approve',
  comment: ''
})

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

// 表格列配置
const columns = [
  {
    title: '',
    key: 'expand',
    width: 50,
    customRender: () => '>'
  },
  {
    title: '申请单号',
    dataIndex: 'applicationNumber',
    key: 'applicationNumber',
    width: 180
  },
  {
    title: '贷款产品',
    dataIndex: 'productName',
    key: 'productName',
    width: 200
  },
  {
    title: '申请养殖户',
    dataIndex: 'farmerName',
    key: 'farmerName',
    width: 120
  },
  {
    title: '贷款人姓名',
    dataIndex: 'borrowerName',
    key: 'borrowerName',
    width: 120
  },
  {
    title: '贷款人身份证号',
    dataIndex: 'borrowerIdNumber',
    key: 'borrowerIdNumber',
    width: 180
  },
  {
    title: '生资种类',
    dataIndex: 'assetType',
    key: 'assetType',
    width: 100
  },
  {
    title: '申请数量',
    dataIndex: 'applicationQuantity',
    key: 'applicationQuantity',
    width: 120,
    sorter: true
  },
  {
    title: '保单信息',
    dataIndex: 'policyInfo',
    key: 'policyInfo',
    width: 100
  },
  {
    title: '申请额度',
    dataIndex: 'amount',
    key: 'amount',
    width: 120,
    sorter: true
  },
  {
    title: '当前状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
    filters: [
      { text: '待初审', value: 'pending_review' },
      { text: '核验待放款', value: 'verification_pending' },
      { text: '待绑定', value: 'pending_binding' },
      { text: '已通过', value: 'approved' },
      { text: '已拒绝', value: 'rejected' }
    ]
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 申请数据
const applications = ref([])

// 计算属性
const filteredApplications = computed(() => {
  let result = applications.value

  if (searchQuery.value.value) {
    const searchValue = searchQuery.value.value.toLowerCase()
    const field = searchQuery.value.field
    
    result = result.filter(app => {
      if (field === 'applicationNumber') {
        return app.applicationNumber.toLowerCase().includes(searchValue)
      } else if (field === 'customerName') {
        return app.borrowerName.toLowerCase().includes(searchValue) || 
               app.farmerName.toLowerCase().includes(searchValue)
      } else if (field === 'productName') {
        return app.productName.toLowerCase().includes(searchValue)
      }
      return true
    })
  }

  return result
})

// 获取申请列表
const fetchApplications = async () => {
  try {
    loading.value = true
    const response = await api.loanApplications.getList({
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      searchField: searchQuery.value.field,
      searchValue: searchQuery.value.value
    })
    
    if (response.success) {
      applications.value = response.data.applications
      pagination.value.total = response.data.pagination.total
    } else {
      message.error(response.message || '获取申请列表失败')
    }
  } catch (error) {
    console.error('获取申请列表失败:', error)
    message.error('获取申请列表失败')
  } finally {
    loading.value = false
  }
}

// 方法
const handleSearch = () => {
  pagination.value.current = 1
  fetchApplications()
}

const handleReset = () => {
  searchQuery.value = {
    field: 'applicationNumber',
    value: ''
  }
}

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

const handleView = (record) => {
  selectedApplication.value = record
  detailModalVisible.value = true
}

const handleApprove = (record) => {
  selectedApplication.value = record
  auditForm.value.action = 'approve'
  auditForm.value.comment = ''
  auditModalVisible.value = true
}

const handleReject = (record) => {
  selectedApplication.value = record
  auditForm.value.action = 'reject'
  auditForm.value.comment = ''
  auditModalVisible.value = true
}

const viewPolicy = (record) => {
  message.info(`查看保单: ${record.applicationNumber}`)
  // 实际项目中这里会打开保单详情页面
}

const handleAuditSubmit = async () => {
  if (!auditForm.value.comment) {
    message.error('请输入审核意见')
    return
  }

  try {
    const response = await api.loanApplications.audit(selectedApplication.value.id, {
      action: auditForm.value.action,
      comment: auditForm.value.comment
    })

    if (response.success) {
      message.success('审核完成')
      auditModalVisible.value = false
      fetchApplications() // 刷新列表
    } else {
      message.error(response.message || '审核失败')
    }
  } catch (error) {
    console.error('审核失败:', error)
    message.error('审核失败')
  }
}

const handleAuditCancel = () => {
  auditModalVisible.value = false
  selectedApplication.value = null
}

const getStatusColor = (status) => {
  const colors = {
    pending_review: 'blue',
    verification_pending: 'blue',
    pending_binding: 'blue',
    approved: 'green',
    rejected: 'red'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    pending_review: '待初审',
    verification_pending: '核验待放款',
    pending_binding: '待绑定',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

const getTypeColor = (type) => {
  const colors = {
    personal: 'blue',
    business: 'green',
    mortgage: 'purple'
  }
  return colors[type] || 'default'
}

const getTypeText = (type) => {
  const texts = {
    personal: '个人贷款',
    business: '企业贷款',
    mortgage: '抵押贷款'
  }
  return texts[type] || type
}

const getProgressPercent = (status) => {
  const percents = {
    pending: 25,
    processing: 50,
    approved: 100,
    rejected: 100
  }
  return percents[status] || 0
}

const getProgressStatus = (status) => {
  if (status === 'approved') return 'success'
  if (status === 'rejected') return 'exception'
  return 'active'
}

const getAuditColor = (action) => {
  const colors = {
    submit: 'blue',
    approve: 'green',
    reject: 'red'
  }
  return colors[action] || 'default'
}

const getAuditActionText = (action) => {
  const texts = {
    submit: '提交申请',
    approve: '审核通过',
    reject: '审核拒绝'
  }
  return texts[action] || action
}

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

// 生命周期
onMounted(() => {
  fetchApplications()
})
</script>

<style scoped>
.loan-applications-page {
  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 {
  font-size: 28px;
  color: #333;
  margin: 0;
}

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

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

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

.audit-records {
  margin-top: 24px;
}

.audit-records h4 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

.audit-item {
  padding: 8px 0;
}

.audit-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
}

.audit-action {
  font-weight: 600;
}

.audit-time {
  color: #999;
  font-size: 12px;
}

.audit-user {
  color: #666;
  font-size: 12px;
  margin-bottom: 4px;
}

.audit-comment {
  color: #333;
  font-size: 12px;
  background: #f5f5f5;
  padding: 8px;
  border-radius: 4px;
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

:deep(.ant-table-tbody > tr > td) {
  padding: 12px 8px;
}

:deep(.ant-table-tbody > tr:hover > td) {
  background-color: #f5f5f5;
}

/* 状态标签样式 */
:deep(.ant-tag) {
  border-radius: 4px;
  font-size: 12px;
  padding: 2px 8px;
}

/* 操作按钮样式 */
:deep(.ant-btn-link) {
  padding: 4px 8px;
  height: auto;
  line-height: 1.2;
}

/* 分页样式 */
:deep(.ant-pagination) {
  margin-top: 16px;
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .search-filter-section .ant-col {
    margin-bottom: 16px;
  }
  
  .search-filter-section .ant-col:last-child {
    margin-bottom: 0;
  }
}
</style>
