<template>
  <div class="loan-release-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="releases-table-section">
      <a-table
        :columns="columns"
        :data-source="filteredReleases"
        :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 === 'releaseAmount'">
            {{ formatAmount(record.releaseAmount) }}
          </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="selectedRelease" class="release-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="解押编号">
            {{ selectedRelease.releaseNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="客户姓名">
            {{ selectedRelease.customerName }}
          </a-descriptions-item>
          <a-descriptions-item label="合同编号">
            {{ selectedRelease.contractNumber }}
          </a-descriptions-item>
          <a-descriptions-item label="解押状态">
            <a-tag :color="getStatusColor(selectedRelease.status)">
              {{ getStatusText(selectedRelease.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="抵押物类型">
            <a-tag :color="getCollateralTypeColor(selectedRelease.collateralType)">
              {{ getCollateralTypeText(selectedRelease.collateralType) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="抵押物描述">
            {{ selectedRelease.collateralDescription }}
          </a-descriptions-item>
          <a-descriptions-item label="贷款金额">
            {{ formatAmount(selectedRelease.loanAmount) }}
          </a-descriptions-item>
          <a-descriptions-item label="抵押物价值">
            {{ formatAmount(selectedRelease.collateralValue) }}
          </a-descriptions-item>
          <a-descriptions-item label="申请时间">
            {{ selectedRelease.applicationTime }}
          </a-descriptions-item>
          <a-descriptions-item label="处理时间">
            {{ selectedRelease.processTime || '未处理' }}
          </a-descriptions-item>
          <a-descriptions-item label="完成时间">
            {{ selectedRelease.completeTime || '未完成' }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ selectedRelease.phone }}
          </a-descriptions-item>
          <a-descriptions-item label="身份证号">
            {{ selectedRelease.idCard }}
          </a-descriptions-item>
          <a-descriptions-item label="申请原因" :span="2">
            {{ selectedRelease.reason }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">
            {{ selectedRelease.remark || '无' }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 解押历史 -->
        <div class="release-history" v-if="selectedRelease.history">
          <h4>解押历史</h4>
          <a-timeline>
            <a-timeline-item
              v-for="record in selectedRelease.history"
              :key="record.id"
              :color="getHistoryColor(record.action)"
            >
              <div class="history-item">
                <div class="history-header">
                  <span class="history-action">{{ getHistoryActionText(record.action) }}</span>
                  <span class="history-time">{{ record.time }}</span>
                </div>
                <div class="history-user">操作人：{{ record.operator }}</div>
                <div class="history-comment" v-if="record.comment">
                  备注：{{ record.comment }}
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </div>
      </div>
    </a-modal>

    <!-- 处理解押模态框 -->
    <a-modal
      v-model:open="processModalVisible"
      title="处理解押申请"
      @ok="handleProcessSubmit"
      @cancel="handleProcessCancel"
    >
      <div class="process-content">
        <a-form :model="processForm" layout="vertical">
          <a-form-item label="处理结果" required>
            <a-radio-group v-model:value="processForm.result">
              <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="processForm.comment"
              placeholder="请输入处理意见"
              :rows="4"
            />
          </a-form-item>
          <a-form-item label="备注">
            <a-textarea
              v-model:value="processForm.remark"
              placeholder="请输入备注（可选）"
              :rows="2"
            />
          </a-form-item>
        </a-form>
      </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"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请人姓名" name="applicantName">
              <a-input v-model:value="editForm.applicantName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请人电话" name="applicantPhone">
              <a-input v-model:value="editForm.applicantPhone" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请人身份证号" name="applicantIdNumber">
              <a-input v-model:value="editForm.applicantIdNumber" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="贷款产品" name="productName">
              <a-input v-model:value="editForm.productName" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="生资种类" name="assetType">
              <a-select v-model:value="editForm.assetType">
                <a-select-option value="牛">牛</a-select-option>
                <a-select-option value="羊">羊</a-select-option>
                <a-select-option value="猪">猪</a-select-option>
                <a-select-option value="其他">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请解押数量" name="releaseQuantity">
              <a-input v-model:value="editForm.releaseQuantity" placeholder="如：5头" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请解押额度" name="releaseAmount">
              <a-input-number
                v-model:value="editForm.releaseAmount"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="申请养殖户" name="farmerName">
              <a-input v-model:value="editForm.farmerName" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="抵押物描述" name="collateralDescription">
          <a-textarea
            v-model:value="editForm.collateralDescription"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="申请原因" name="reason">
          <a-textarea
            v-model:value="editForm.reason"
            :rows="3"
          />
        </a-form-item>
        
        <a-form-item label="备注" name="remark">
          <a-textarea
            v-model:value="editForm.remark"
            :rows="2"
          />
        </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 processModalVisible = ref(false)
const editModalVisible = ref(false)
const editLoading = ref(false)
const selectedRelease = ref(null)
const processForm = ref({
  result: 'approve',
  comment: '',
  remark: ''
})
const editForm = ref({
  id: null,
  applicantName: '',
  applicantPhone: '',
  applicantIdNumber: '',
  productName: '',
  assetType: '',
  releaseQuantity: '',
  releaseAmount: 0,
  farmerName: '',
  collateralDescription: '',
  reason: '',
  remark: ''
})
const editFormRef = ref(null)
const editFormRules = ref({
  applicantName: [
    { required: true, message: '请输入申请人姓名', trigger: 'blur' }
  ],
  applicantPhone: [
    { required: true, message: '请输入申请人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  applicantIdNumber: [
    { required: true, message: '请输入申请人身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dX]$/, message: '请输入正确的身份证号', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入贷款产品', trigger: 'blur' }
  ],
  assetType: [
    { required: true, message: '请选择生资种类', trigger: 'change' }
  ],
  releaseQuantity: [
    { required: true, message: '请输入申请解押数量', trigger: 'blur' }
  ],
  releaseAmount: [
    { required: true, message: '请输入申请解押额度', trigger: 'blur' }
  ],
  farmerName: [
    { 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: 'applicantName',
    key: 'applicantName',
    width: 120
  },
  {
    title: '申请人身份证号',
    dataIndex: 'applicantIdNumber',
    key: 'applicantIdNumber',
    width: 180
  },
  {
    title: '申请人电话',
    dataIndex: 'applicantPhone',
    key: 'applicantPhone',
    width: 150
  },
  {
    title: '生资种类',
    dataIndex: 'assetType',
    key: 'assetType',
    width: 100
  },
  {
    title: '申请解押数量',
    dataIndex: 'releaseQuantity',
    key: 'releaseQuantity',
    width: 150,
    sorter: true
  },
  {
    title: '申请解押额度',
    dataIndex: 'releaseAmount',
    key: 'releaseAmount',
    width: 150,
    sorter: true
  },
  {
    title: '当前状态',
    dataIndex: 'status',
    key: 'status',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 解押数据
const releases = ref([])

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

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

  return result
})

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

// 获取解押申请详情
const fetchReleaseDetail = async (id) => {
  try {
    const response = await api.loanReleases.getById(id)
    
    if (response.success) {
      selectedRelease.value = response.data
      return response.data
    } else {
      message.error('获取解押申请详情失败')
      return null
    }
  } catch (error) {
    console.error('获取解押申请详情失败:', error)
    message.error('获取解押申请详情失败')
    return null
  }
}

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

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

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

const handleView = async (record) => {
  const detail = await fetchReleaseDetail(record.id)
  if (detail) {
    detailModalVisible.value = true
  }
}

const handleEdit = (record) => {
  selectedRelease.value = record
  editForm.value = {
    id: record.id,
    applicantName: record.applicantName || '',
    applicantPhone: record.applicantPhone || '',
    applicantIdNumber: record.applicantIdNumber || '',
    productName: record.productName || '',
    assetType: record.assetType || '',
    releaseQuantity: record.releaseQuantity || '',
    releaseAmount: record.releaseAmount || 0,
    farmerName: record.farmerName || '',
    collateralDescription: record.collateralDescription || '',
    reason: record.reason || record.application_reason || '',
    remark: record.remark || ''
  }
  editModalVisible.value = true
}

const handleProcessSubmit = async () => {
  if (!processForm.value.comment) {
    message.error('请输入处理意见')
    return
  }

  try {
    const response = await api.loanReleases.process(selectedRelease.value.id, {
      action: processForm.value.result,
      comment: processForm.value.comment,
      remark: processForm.value.remark
    })

    if (response.success) {
      message.success('处理完成')
      processModalVisible.value = false
      processForm.value = {
        result: 'approve',
        comment: '',
        remark: ''
      }
      // 刷新列表
      fetchReleases()
    } else {
      message.error('处理失败')
    }
  } catch (error) {
    console.error('处理解押申请失败:', error)
    message.error('处理失败')
  }
}

const handleProcessCancel = () => {
  processModalVisible.value = false
  selectedRelease.value = null
}

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

    const response = await api.loanReleases.update(editForm.value.id, {
      customer_name: editForm.value.applicantName,
      customer_phone: editForm.value.applicantPhone,
      customer_id_card: editForm.value.applicantIdNumber,
      farmer_name: editForm.value.farmerName,
      product_name: editForm.value.productName,
      collateral_type: editForm.value.assetType === '牛' ? 'livestock' : editForm.value.assetType,
      release_quantity: editForm.value.releaseQuantity,
      release_amount: editForm.value.releaseAmount,
      collateral_description: editForm.value.collateralDescription,
      application_reason: editForm.value.reason,
      remark: editForm.value.remark
    })

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

const handleEditCancel = () => {
  editModalVisible.value = false
  editForm.value = {
    id: null,
    applicantName: '',
    applicantPhone: '',
    applicantIdNumber: '',
    productName: '',
    assetType: '',
    releaseQuantity: '',
    releaseAmount: 0,
    farmerName: '',
    collateralDescription: '',
    reason: '',
    remark: ''
  }
}

const getStatusColor = (status) => {
  const colors = {
    released: 'default',
    pending: 'orange',
    processing: 'blue',
    completed: 'green',
    rejected: 'red'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    released: '已解押',
    pending: '待处理',
    processing: '处理中',
    completed: '已完成',
    rejected: '已拒绝'
  }
  return texts[status] || status
}

const getCollateralTypeColor = (type) => {
  const colors = {
    house: 'blue',
    car: 'green',
    land: 'orange',
    equipment: 'purple'
  }
  return colors[type] || 'default'
}

const getCollateralTypeText = (type) => {
  const texts = {
    house: '房产',
    car: '车辆',
    land: '土地',
    equipment: '设备'
  }
  return texts[type] || type
}

const getHistoryColor = (action) => {
  const colors = {
    apply: 'blue',
    process: 'orange',
    complete: 'green',
    reject: 'red'
  }
  return colors[action] || 'default'
}

const getHistoryActionText = (action) => {
  const texts = {
    apply: '提交申请',
    process: '开始处理',
    complete: '处理完成',
    reject: '申请拒绝'
  }
  return texts[action] || action
}

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

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

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

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

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

.release-history {
  margin-top: 24px;
}

.release-history h4 {
  margin-bottom: 16px;
  font-size: 16px;
  font-weight: 600;
}

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

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

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

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

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

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

.process-content {
  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>
