<template>
  <div class="completed-supervision-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>监管任务结项</h1>
      <div class="header-actions">
        <a-button type="primary" @click="handleBatchImport">
          <upload-outlined />
          批量导入
        </a-button>
      </div>
    </div>

    <!-- 搜索筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16" align="middle">
        <a-col :span="4">
          <a-select
            v-model:value="searchForm.contractNumber"
            placeholder="合同编号"
            allow-clear
            style="width: 100%"
          >
            <a-select-option value="LOAN2024001">LOAN2024001</a-select-option>
            <a-select-option value="LOAN2024002">LOAN2024002</a-select-option>
            <a-select-option value="LOAN2024003">LOAN2024003</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.keyword"
            placeholder="请输入关键字"
            allow-clear
          />
        </a-col>
        <a-col :span="4">
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <search-outlined />
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="filteredTasks"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        :locale="{ emptyText: '暂无数据' }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'settlementStatus'">
            <a-tag :color="getSettlementStatusColor(record.settlementStatus)">
              {{ getSettlementStatusName(record.settlementStatus) }}
            </a-tag>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="viewTask(record)">查看</a-button>
              <a-button type="link" size="small" @click="editTask(record)">编辑</a-button>
              <a-button type="link" size="small" @click="exportTask(record)">导出</a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 编辑监管任务已结项对话框 -->
    <a-modal
      v-model:open="editModalVisible"
      title="编辑监管任务已结项"
      width="800px"
      @ok="handleEditTask"
      @cancel="handleCancelEdit"
      :confirmLoading="editLoading"
    >
      <a-form
        ref="editTaskFormRef"
        :model="editTaskForm"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请单号" name="applicationNumber">
              <a-input v-model:value="editTaskForm.applicationNumber" placeholder="请输入申请单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="放款合同编号" name="contractNumber">
              <a-input v-model:value="editTaskForm.contractNumber" placeholder="请输入放款合同编号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="产品名称" name="productName">
              <a-input v-model:value="editTaskForm.productName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="客户姓名" name="customerName">
              <a-input v-model:value="editTaskForm.customerName" placeholder="请输入客户姓名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="证件类型" name="idType">
              <a-select v-model:value="editTaskForm.idType" placeholder="请选择证件类型">
                <a-select-option value="ID_CARD">身份证</a-select-option>
                <a-select-option value="PASSPORT">护照</a-select-option>
                <a-select-option value="OTHER">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="证件号码" name="idNumber">
              <a-input v-model:value="editTaskForm.idNumber" 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="editTaskForm.assetType" placeholder="请输入养殖生资种类" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="监管生资数量" name="assetQuantity">
              <a-input-number 
                v-model:value="editTaskForm.assetQuantity" 
                :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="totalRepaymentPeriods">
              <a-input-number 
                v-model:value="editTaskForm.totalRepaymentPeriods" 
                :min="0" 
                placeholder="请输入总还款期数"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="结清状态" name="settlementStatus">
              <a-select v-model:value="editTaskForm.settlementStatus" placeholder="请选择结清状态">
                <a-select-option value="settled">已结清</a-select-option>
                <a-select-option value="unsettled">未结清</a-select-option>
                <a-select-option value="partial">部分结清</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="settlementDate">
              <a-date-picker 
                v-model:value="editTaskForm.settlementDate" 
                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="importTime">
              <a-date-picker 
                v-model:value="editTaskForm.importTime" 
                placeholder="请选择导入时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                show-time
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="结清金额" name="settlementAmount">
              <a-input-number 
                v-model:value="editTaskForm.settlementAmount" 
                :min="0" 
                :precision="2"
                placeholder="请输入结清金额"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="剩余金额" name="remainingAmount">
              <a-input-number 
                v-model:value="editTaskForm.remainingAmount" 
                :min="0" 
                :precision="2"
                placeholder="请输入剩余金额"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="结清备注" name="settlementNotes">
          <a-textarea 
            v-model:value="editTaskForm.settlementNotes" 
            placeholder="请输入结清备注"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

const loading = ref(false)
const tasks = ref([])

// 编辑相关
const editModalVisible = ref(false)
const editTaskFormRef = ref()
const editTaskForm = ref({})
const editLoading = ref(false)
const currentEditTask = ref(null)

const searchForm = reactive({
  contractNumber: undefined,
  keyword: '',
})

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条`,
})

const columns = [
  { title: '申请单号', dataIndex: 'applicationNumber', key: 'applicationNumber', sorter: true },
  { title: '放款合同编号', dataIndex: 'contractNumber', key: 'contractNumber', sorter: true },
  { title: '产品名称', dataIndex: 'productName', key: 'productName' },
  { title: '客户姓名', dataIndex: 'customerName', key: 'customerName' },
  { title: '证件类型', dataIndex: 'idType', key: 'idType' },
  { title: '证件号码', dataIndex: 'idNumber', key: 'idNumber' },
  { title: '养殖生资种类', dataIndex: 'assetType', key: 'assetType' },
  { title: '监管生资数量', dataIndex: 'assetQuantity', key: 'assetQuantity', sorter: true },
  { title: '总还款期数', dataIndex: 'totalRepaymentPeriods', key: 'totalRepaymentPeriods', sorter: true },
  { title: '结清状态', dataIndex: 'settlementStatus', key: 'settlementStatus', filters: [
    { text: '已结清', value: 'settled' },
    { text: '未结清', value: 'unsettled' },
    { text: '部分结清', value: 'partial' },
  ]},
  { title: '结清日期', dataIndex: 'settlementDate', key: 'settlementDate', sorter: true },
  { title: '结清任务导入时间', dataIndex: 'importTime', key: 'importTime', sorter: true },
  { title: '操作', key: 'action', fixed: 'right', width: 180 },
]

// 模拟数据
const mockTasks = [
  {
    id: 'S001',
    applicationNumber: 'APP2024001',
    contractNumber: 'LOAN2024001',
    productName: '生猪养殖贷',
    customerName: '张三',
    idType: 'ID_CARD',
    idNumber: '4401XXXXXXXXXXXXXX',
    assetType: '生猪',
    assetQuantity: 500,
    totalRepaymentPeriods: 12,
    settlementStatus: 'settled',
    settlementDate: '2024-01-15',
    importTime: '2024-01-15 10:30:00',
  },
  {
    id: 'S002',
    applicationNumber: 'APP2024002',
    contractNumber: 'LOAN2024002',
    productName: '肉牛养殖贷',
    customerName: '李四',
    idType: 'ID_CARD',
    idNumber: '4402XXXXXXXXXXXXXX',
    assetType: '肉牛',
    assetQuantity: 150,
    totalRepaymentPeriods: 24,
    settlementStatus: 'partial',
    settlementDate: '2024-01-20',
    importTime: '2024-01-20 14:20:00',
  },
  {
    id: 'S003',
    applicationNumber: 'APP2024003',
    contractNumber: 'LOAN2024003',
    productName: '蛋鸡养殖贷',
    customerName: '王五',
    idType: 'ID_CARD',
    idNumber: '4403XXXXXXXXXXXXXX',
    assetType: '蛋鸡',
    assetQuantity: 10000,
    totalRepaymentPeriods: 18,
    settlementStatus: 'unsettled',
    settlementDate: null,
    importTime: '2024-01-10 09:15:00',
  },
]

const fetchTasks = async () => {
  loading.value = true
  try {
    console.log('开始获取监管任务已结项列表...', {
      page: pagination.current,
      pageSize: pagination.pageSize,
      search: searchForm.keyword,
      contractNumber: searchForm.contractNumber
    })
    
    const response = await api.completedSupervisions.getList({
      page: pagination.current,
      limit: pagination.pageSize,
      search: searchForm.keyword,
      contractNumber: searchForm.contractNumber
    })
    
    console.log('监管任务已结项列表响应:', response)
    
    if (response.success) {
      tasks.value = response.data.tasks || []
      pagination.total = response.data.pagination.total
    } else {
      message.error(response.message || '获取监管任务已结项列表失败')
    }
  } catch (error) {
    console.error('获取监管任务已结项失败:', error)
    message.error('获取监管任务已结项失败')
  } finally {
    loading.value = false
  }
}

const filteredTasks = computed(() => {
  // 后端已经处理了过滤，直接返回任务列表
  return tasks.value
})

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

const handleReset = () => {
  searchForm.contractNumber = undefined
  searchForm.keyword = ''
  pagination.current = 1
  fetchTasks()
}

const handleBatchImport = () => {
  message.info('批量导入功能开发中...')
}

const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTasks()
}

const getSettlementStatusColor = (status) => {
  const colors = {
    'settled': 'green',
    'unsettled': 'red',
    'partial': 'orange',
  }
  return colors[status] || 'default'
}

const getSettlementStatusName = (status) => {
  const names = {
    'settled': '已结清',
    'unsettled': '未结清',
    'partial': '部分结清',
  }
  return names[status] || status
}

const viewTask = async (record) => {
  try {
    const response = await api.completedSupervisions.getById(record.id)
    if (response.success) {
      message.info(`查看任务: ${record.applicationNumber}`)
      // 这里可以打开详情对话框显示任务信息
      console.log('任务详情:', response.data)
    } else {
      message.error('获取任务详情失败')
    }
  } catch (error) {
    console.error('获取任务详情失败:', error)
    message.error('获取任务详情失败')
  }
}

const editTask = async (record) => {
  try {
    // 保存当前编辑的任务
    currentEditTask.value = record
    
    // 填充编辑表单数据
    editTaskForm.value = {
      applicationNumber: record.applicationNumber || '',
      contractNumber: record.contractNumber || '',
      productName: record.productName || '',
      customerName: record.customerName || '',
      idType: record.idType || 'ID_CARD',
      idNumber: record.idNumber || '',
      assetType: record.assetType || '',
      assetQuantity: record.assetQuantity || 0,
      totalRepaymentPeriods: record.totalRepaymentPeriods || 0,
      settlementStatus: record.settlementStatus || 'unsettled',
      settlementDate: record.settlementDate ? dayjs(record.settlementDate) : null,
      importTime: record.importTime ? dayjs(record.importTime) : null,
      settlementAmount: record.settlementAmount || null,
      remainingAmount: record.remainingAmount || null,
      settlementNotes: record.settlementNotes || ''
    }
    
    // 打开编辑对话框
    editModalVisible.value = true
  } catch (error) {
    console.error('打开编辑对话框失败:', error)
    message.error('打开编辑对话框失败')
  }
}

const exportTask = async (record) => {
  try {
    message.success(`导出任务: ${record.applicationNumber}`)
    // 这里可以实现导出功能
  } catch (error) {
    console.error('导出任务失败:', error)
    message.error('导出任务失败')
  }
}

// 编辑任务处理函数
const handleEditTask = async () => {
  try {
    editLoading.value = true
    
    const response = await api.completedSupervisions.update(currentEditTask.value.id, editTaskForm.value)
    
    if (response.success) {
      message.success('编辑监管任务已结项成功')
      editModalVisible.value = false
      editTaskFormRef.value.resetFields()
      currentEditTask.value = null
      fetchTasks() // 刷新列表
    } else {
      message.error(response.message || '编辑监管任务已结项失败')
    }
  } catch (error) {
    console.error('编辑监管任务已结项失败:', error)
    message.error('编辑监管任务已结项失败')
  } finally {
    editLoading.value = false
  }
}

const handleCancelEdit = () => {
  editModalVisible.value = false
  editTaskFormRef.value.resetFields()
  currentEditTask.value = null
}

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

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

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  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: 24px;
  font-weight: 600;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 12px;
}

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

.table-section {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .header-actions {
    justify-content: center;
  }
  
  .search-section .ant-col {
    margin-bottom: 16px;
  }
  
  .search-section .ant-col:last-child {
    margin-bottom: 0;
  }
}
</style>