<template>
  <div class="loan-contracts-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="contractNumber">合同编号</a-select-option>
            <a-select-option value="applicationNumber">申请单号</a-select-option>
            <a-select-option value="borrowerName">贷款人姓名</a-select-option>
            <a-select-option value="farmerName">申请养殖户</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="contracts-table-section">
      <a-table
        :columns="columns"
        :data-source="contracts"
        :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 === 'amount'">
            {{ formatAmount(record.amount) }}
          </template>
          <template v-else-if="column.key === 'paidAmount'">
            {{ formatAmount(record.paidAmount) }}
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleEdit(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="selectedContract" class="contract-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="合同编号">
            {{ selectedContract.contractNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="申请单号">
            {{ selectedContract.applicationNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="贷款产品">
            {{ selectedContract.productName }}
          </a-descriptions-item>
          <a-descriptions-item label="申请养殖户">
            {{ selectedContract.farmerName }}
          </a-descriptions-item>
          <a-descriptions-item label="贷款人姓名">
            {{ selectedContract.borrowerName }}
          </a-descriptions-item>
          <a-descriptions-item label="贷款人身份证号">
            {{ selectedContract.borrowerIdNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="生资种类">
            {{ selectedContract.assetType }}
          </a-descriptions-item>
          <a-descriptions-item label="申请数量">
            {{ selectedContract.applicationQuantity }}
          </a-descriptions-item>
          <a-descriptions-item label="合同金额">
            {{ formatAmount(selectedContract.amount) }}
          </a-descriptions-item>
          <a-descriptions-item label="已还款金额">
            {{ formatAmount(selectedContract.paidAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="剩余金额">
            {{ formatAmount(selectedContract.remainingAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="合同状态">
            <a-tag :color="getStatusColor(selectedContract.status)">
              {{ getStatusText(selectedContract.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="合同类型">
            {{ getTypeText(selectedContract.type) }}
          </a-descriptions-item>
          <a-descriptions-item label="合同期限">
            {{ selectedContract.term }} 个月
          </a-descriptions-item>
          <a-descriptions-item label="利率">
            {{ selectedContract.interestRate }}%
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ selectedContract.phone }}
          </a-descriptions-item>
          <a-descriptions-item label="贷款用途">
            {{ selectedContract.purpose }}
          </a-descriptions-item>
          <a-descriptions-item label="合同签订时间">
            {{ selectedContract.contractTime }}
          </a-descriptions-item>
          <a-descriptions-item label="放款时间">
            {{ selectedContract.disbursementTime || '未放款' }}
          </a-descriptions-item>
          <a-descriptions-item label="到期时间">
            {{ selectedContract.maturityTime || '未设置' }}
          </a-descriptions-item>
          <a-descriptions-item label="完成时间">
            {{ selectedContract.completedTime || '未完成' }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">
            {{ selectedContract.remark || '无' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>

    <!-- 编辑合同模态框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑合同"
      width="800px"
      :confirm-loading="editLoading"
      @ok="handleEditSubmit"
      @cancel="handleEditCancel"
    >
      <a-form
        ref="editFormRef"
        :model="editForm"
        :rules="editFormRules"
        layout="vertical"
        v-if="editModalVisible"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款产品" name="productName">
              <a-input v-model:value="editForm.productName" placeholder="请输入贷款产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请养殖户" name="farmerName">
              <a-input v-model:value="editForm.farmerName" placeholder="请输入申请养殖户姓名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="贷款人姓名" name="borrowerName">
              <a-input v-model:value="editForm.borrowerName" placeholder="请输入贷款人姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款人身份证号" name="borrowerIdNumber">
              <a-input v-model:value="editForm.borrowerIdNumber" placeholder="请输入身份证号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生资种类" name="assetType">
              <a-input v-model:value="editForm.assetType" placeholder="请输入生资种类" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请数量" name="applicationQuantity">
              <a-input v-model:value="editForm.applicationQuantity" placeholder="请输入申请数量" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="合同金额" name="amount">
              <a-input-number
                v-model:value="editForm.amount"
                placeholder="请输入合同金额"
                :min="0"
                :precision="2"
                style="width: 100%"
                addon-after="元"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="已还款金额" name="paidAmount">
              <a-input-number
                v-model:value="editForm.paidAmount"
                placeholder="请输入已还款金额"
                :min="0"
                :precision="2"
                style="width: 100%"
                addon-after="元"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="合同状态" name="status">
              <a-select v-model:value="editForm.status" placeholder="请选择合同状态">
                <a-select-option value="pending">待放款</a-select-option>
                <a-select-option value="active">已放款</a-select-option>
                <a-select-option value="completed">已完成</a-select-option>
                <a-select-option value="defaulted">违约</a-select-option>
                <a-select-option value="cancelled">已取消</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="合同类型" name="type">
              <a-select v-model:value="editForm.type" placeholder="请选择合同类型">
                <a-select-option value="livestock_collateral">畜禽活体抵押</a-select-option>
                <a-select-option value="farmer_loan">惠农贷</a-select-option>
                <a-select-option value="business_loan">商业贷款</a-select-option>
                <a-select-option value="personal_loan">个人贷款</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="term">
              <a-input-number
                v-model:value="editForm.term"
                placeholder="请输入合同期限"
                :min="1"
                style="width: 100%"
                addon-after="个月"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="利率" name="interestRate">
              <a-input-number
                v-model:value="editForm.interestRate"
                placeholder="请输入利率"
                :min="0"
                :max="100"
                :precision="2"
                style="width: 100%"
                addon-after="%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="联系电话" name="phone">
              <a-input v-model:value="editForm.phone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款用途" name="purpose">
              <a-input v-model:value="editForm.purpose" placeholder="请输入贷款用途" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="editForm.remark"
            placeholder="请输入备注"
            :rows="3"
          />
        </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: 'contractNumber',
  value: ''
})
const detailModalVisible = ref(false)
const editModalVisible = ref(false)
const editLoading = ref(false)
const selectedContract = ref(null)
const contracts = ref([])

// 编辑表单
const editForm = ref({
  id: null,
  productName: '',
  farmerName: '',
  borrowerName: '',
  borrowerIdNumber: '',
  assetType: '',
  applicationQuantity: '',
  amount: null,
  paidAmount: null,
  status: 'pending',
  type: 'livestock_collateral',
  term: null,
  interestRate: null,
  phone: '',
  purpose: '',
  remark: ''
})

const editFormRef = ref()

// 表单验证规则
const editFormRules = {
  productName: [
    { required: true, message: '请输入贷款产品名称', trigger: 'blur' }
  ],
  farmerName: [
    { required: true, message: '请输入申请养殖户姓名', trigger: 'blur' }
  ],
  borrowerName: [
    { required: true, message: '请输入贷款人姓名', trigger: 'blur' }
  ],
  borrowerIdNumber: [
    { required: true, message: '请输入贷款人身份证号', trigger: 'blur' }
  ],
  assetType: [
    { required: true, message: '请输入生资种类', trigger: 'blur' }
  ],
  applicationQuantity: [
    { required: true, message: '请输入申请数量', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: '请输入合同金额', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '合同金额必须大于0', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择合同状态', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择合同类型', trigger: 'change' }
  ],
  term: [
    { required: true, message: '请输入合同期限', trigger: 'blur' },
    { type: 'number', min: 1, message: '合同期限必须大于0', trigger: 'blur' }
  ],
  interestRate: [
    { required: true, message: '请输入利率', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '利率必须在0-100之间', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' }
  ]
}

// 分页配置
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: 'amount',
    key: 'amount',
    width: 120,
    sorter: true
  },
  {
    title: '当前状态',
    dataIndex: 'status',
    key: 'status',
    width: 120,
    filters: [
      { text: '待放款', value: 'pending' },
      { text: '已放款', value: 'active' },
      { text: '已完成', value: 'completed' },
      { text: '违约', value: 'defaulted' },
      { text: '已取消', value: 'cancelled' }
    ]
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    fixed: 'right'
  }
]

// 获取合同列表
const fetchContracts = async () => {
  try {
    loading.value = true
    const response = await api.loanContracts.getList({
      page: pagination.value.current,
      pageSize: pagination.value.pageSize,
      searchField: searchQuery.value.field,
      searchValue: searchQuery.value.value
    })
    
    if (response.success) {
      contracts.value = response.data.contracts
      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
  fetchContracts()
}

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

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

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

const handleEdit = (record) => {
  Object.assign(editForm.value, {
    id: record.id,
    productName: record.productName,
    farmerName: record.farmerName,
    borrowerName: record.borrowerName,
    borrowerIdNumber: record.borrowerIdNumber,
    assetType: record.assetType,
    applicationQuantity: record.applicationQuantity,
    amount: record.amount,
    paidAmount: record.paidAmount,
    status: record.status,
    type: record.type,
    term: record.term,
    interestRate: record.interestRate,
    phone: record.phone,
    purpose: record.purpose,
    remark: record.remark
  })
  editModalVisible.value = true
}

const handleEditSubmit = async () => {
  try {
    await editFormRef.value.validate()
    editLoading.value = true

    const response = await api.loanContracts.update(editForm.value.id, {
      // 使用数据库字段名
      customer_name: editForm.value.borrowerName,
      customer_phone: editForm.value.phone,
      customer_id_card: editForm.value.borrowerIdNumber,
      loan_amount: editForm.value.amount,
      loan_term: editForm.value.term,
      interest_rate: editForm.value.interestRate,
      status: editForm.value.status,
      type: editForm.value.type,
      purpose: editForm.value.purpose,
      remark: editForm.value.remark
    })

    if (response.success) {
      message.success('合同更新成功')
      editModalVisible.value = false
      fetchContracts() // 刷新列表
    } else {
      message.error(response.message || '更新失败')
    }
  } catch (error) {
    console.error('更新失败:', error)
    message.error('更新失败')
  } finally {
    editLoading.value = false
  }
}

const handleEditCancel = () => {
  editModalVisible.value = false
  editFormRef.value?.resetFields()
}

const getStatusColor = (status) => {
  const colors = {
    pending: 'blue',
    active: 'green',
    completed: 'cyan',
    defaulted: 'red',
    cancelled: 'gray'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    pending: '待放款',
    active: '已放款',
    completed: '已完成',
    defaulted: '违约',
    cancelled: '已取消'
  }
  return texts[status] || status
}

const getTypeText = (type) => {
  const texts = {
    livestock_collateral: '畜禽活体抵押',
    farmer_loan: '惠农贷',
    business_loan: '商业贷款',
    personal_loan: '个人贷款'
  }
  return texts[type] || type
}

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

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

<style scoped>
.loan-contracts-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);
}

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

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

/* 表格样式优化 */
: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>