<template>
  <div class="claim-management">
    <a-page-header
      title="理赔管理"
      sub-title="管理系统所有理赔申请"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleExport">
            <download-outlined />
            导出Excel
          </a-button>
          <a-button type="primary" @click="showModal">
            <plus-outlined />
            新增理赔
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 搜索区域 -->
    <a-card style="margin-top: 16px">
      <a-form layout="inline" :model="searchForm">
        <a-form-item label="理赔单号">
          <a-input
            v-model:value="searchForm.claim_no"
            placeholder="请输入理赔单号"
            @pressEnter="handleSearch"
            @change="onSearchFieldChange('claim_no', $event)"
            @input="onSearchFieldInput('claim_no', $event)"
            allowClear
          />
        </a-form-item>
        <a-form-item label="保单号">
          <a-input
            v-model:value="searchForm.policy_no"
            placeholder="请输入保单号"
            @pressEnter="handleSearch"
            @change="onSearchFieldChange('policy_no', $event)"
            @input="onSearchFieldInput('policy_no', $event)"
            allowClear
          />
        </a-form-item>
        <a-form-item label="报案人">
          <a-input
            v-model:value="searchForm.reporter_name"
            placeholder="请输入报案人姓名"
            @pressEnter="handleSearch"
            @change="onSearchFieldChange('reporter_name', $event)"
            @input="onSearchFieldInput('reporter_name', $event)"
            allowClear
          />
        </a-form-item>
        <a-form-item label="联系电话">
          <a-input
            v-model:value="searchForm.contact_phone"
            placeholder="请输入联系电话"
            @pressEnter="handleSearch"
            @change="onSearchFieldChange('contact_phone', $event)"
            @input="onSearchFieldInput('contact_phone', $event)"
            allowClear
          />
        </a-form-item>
        <a-form-item label="事故类型">
          <a-select
            v-model:value="searchForm.claim_type"
            placeholder="请选择事故类型"
            style="width: 120px"
            @change="onSearchFieldChange('claim_type', $event)"
            allowClear
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="disease">疾病</a-select-option>
            <a-select-option value="accident">意外事故</a-select-option>
            <a-select-option value="natural_disaster">自然灾害</a-select-option>
            <a-select-option value="theft">盗窃</a-select-option>
            <a-select-option value="other">其他</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.claim_status"
            placeholder="请选择状态"
            style="width: 120px"
            @change="onSearchFieldChange('claim_status', $event)"
            allowClear
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="pending">待处理</a-select-option>
            <a-select-option value="investigating">调查中</a-select-option>
            <a-select-option value="approved">已通过</a-select-option>
            <a-select-option value="rejected">已拒绝</a-select-option>
            <a-select-option value="paid">已赔付</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <search-outlined />
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">
            <redo-outlined />
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 理赔表格 -->
    <a-card style="margin-top: 16px">
      <a-table
        :columns="columns"
        :data-source="claimList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'claim_status'">
            <a-tag :color="getStatusColor(record.claim_status)">
              {{ getStatusText(record.claim_status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'claim_type'">
            <a-tag :color="getClaimTypeColor(record.claim_type)">
              {{ getClaimTypeText(record.claim_type) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'claim_amount'">
            <span>¥{{ record.claim_amount?.toLocaleString() }}</span>
          </template>
          <template v-else-if="column.key === 'contact_phone'">
            <span>{{ record.contact_phone || '-' }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleView(record)">查看</a-button>
              <a-button
                size="small"
                type="primary"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>
              <a-popconfirm
                title="确定要删除这条理赔记录吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleDelete(record.id)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
              <a-dropdown>
                <a-button size="small">更多</a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item 
                      @click="handleProcess(record)" 
                      :disabled="record.claim_status !== 'pending'"
                    >
                      处理
                    </a-menu-item>
                    <a-menu-item 
                      @click="handleApprove(record)" 
                      :disabled="record.claim_status !== 'pending'"
                    >
                      通过
                    </a-menu-item>
                    <a-menu-item 
                      @click="handleReject(record)" 
                      :disabled="record.claim_status !== 'pending'"
                    >
                      拒绝
                    </a-menu-item>
                  </a-menu>
                </template>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 查看详情模态框 -->
    <a-modal
      v-model:visible="detailVisible"
      title="理赔详情"
      width="800px"
      :footer="null"
    >
      <a-descriptions
        v-if="currentClaim"
        title="基本信息"
        bordered
        :column="2"
      >
        <a-descriptions-item label="理赔单号">{{ currentClaim.claim_no }}</a-descriptions-item>
        <a-descriptions-item label="报案人">{{ currentClaim.reporter_name }}</a-descriptions-item>
        <a-descriptions-item label="联系电话">{{ currentClaim.contact_phone }}</a-descriptions-item>
        <a-descriptions-item label="保单号">{{ currentClaim.policy_no }}</a-descriptions-item>
        <a-descriptions-item label="事故类型">{{ currentClaim.claim_type }}</a-descriptions-item>
        <a-descriptions-item label="受影响数量">{{ currentClaim.affected_count }}</a-descriptions-item>
        <a-descriptions-item label="申请金额">¥{{ currentClaim.claim_amount?.toLocaleString() }}</a-descriptions-item>
        <a-descriptions-item label="出险地址">{{ currentClaim.incident_location }}</a-descriptions-item>
        <a-descriptions-item label="报案时间">{{ currentClaim.report_date }}</a-descriptions-item>
        <a-descriptions-item label="事故时间">{{ currentClaim.incident_date }}</a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(currentClaim.claim_status)">
            {{ getStatusText(currentClaim.claim_status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="调查员">{{ currentClaim.investigator_name || '-' }}</a-descriptions-item>
        <a-descriptions-item label="调查时间">{{ currentClaim.investigation_date || '-' }}</a-descriptions-item>
        <a-descriptions-item label="审核员">{{ currentClaim.reviewer_name || '-' }}</a-descriptions-item>
        <a-descriptions-item label="审核时间">{{ currentClaim.review_date || '-' }}</a-descriptions-item>
        <a-descriptions-item label="赔付金额" v-if="currentClaim.payment_amount">
          ¥{{ currentClaim.payment_amount?.toLocaleString() }}
        </a-descriptions-item>
        <a-descriptions-item label="赔付时间">{{ currentClaim.payment_date || '-' }}</a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-descriptions
        title="事故详情"
        bordered
        :column="1"
      >
        <a-descriptions-item label="事故描述">
          {{ currentClaim.accident_description }}
        </a-descriptions-item>
        <a-descriptions-item label="处理过程">
          {{ currentClaim.process_description || '暂无处理过程' }}
        </a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-descriptions
        title="相关文档"
        bordered
        :column="1"
      >
        <a-descriptions-item label="附件列表">
          <div v-if="currentClaim.documents && currentClaim.documents.length > 0">
            <a-space direction="vertical" style="width: 100%">
              <div v-for="(doc, index) in currentClaim.documents" :key="index" class="document-item">
                <file-text-outlined />
                <a :href="doc.url" target="_blank">{{ doc.name }}</a>
                <span class="document-size">({{ doc.size }})</span>
              </div>
            </a-space>
          </div>
          <span v-else>暂无附件</span>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 处理理赔模态框 -->
    <a-modal
      v-model:visible="processVisible"
      title="处理理赔申请"
      width="600px"
      @ok="handleProcessOk"
      @cancel="handleProcessCancel"
    >
      <a-form
        ref="processFormRef"
        :model="processForm"
        :rules="processRules"
        layout="vertical"
      >
        <a-form-item label="审核金额" name="approved_amount">
          <a-input-number
            v-model:value="processForm.approved_amount"
            :min="0"
            :max="currentClaim?.claim_amount"
            :step="100"
            style="width: 100%"
            placeholder="请输入审核金额"
          />
        </a-form-item>
        
        <a-form-item label="处理结果" name="status">
          <a-radio-group v-model:value="processForm.status">
            <a-radio value="approved">通过</a-radio>
            <a-radio value="rejected">拒绝</a-radio>
          </a-radio-group>
        </a-form-item>

        <a-form-item
          v-if="processForm.status === 'rejected'"
          label="拒绝原因"
          name="reject_reason"
        >
          <a-textarea
            v-model:value="processForm.reject_reason"
            placeholder="请输入拒绝原因"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="处理说明" name="process_description">
          <a-textarea
            v-model:value="processForm.process_description"
            placeholder="请输入处理说明"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增/编辑模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      width="800px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="理赔单号" name="claim_no">
              <a-input v-model:value="formState.claim_no" placeholder="请输入理赔单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保单号" name="policy_no">
              <a-input v-model:value="formState.policy_no" placeholder="请输入保单号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="报案人" name="reporter_name">
              <a-input v-model:value="formState.reporter_name" placeholder="请输入报案人姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系电话" name="contact_phone">
              <a-input v-model:value="formState.contact_phone" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="事故类型" name="claim_type">
              <a-select v-model:value="formState.claim_type" placeholder="请选择事故类型">
                <a-select-option value="disease">疾病</a-select-option>
                <a-select-option value="accident">意外</a-select-option>
                <a-select-option value="natural_disaster">自然灾害</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="affected_count">
              <a-input-number
                v-model:value="formState.affected_count"
                :min="0"
                :step="1"
                style="width: 100%"
                placeholder="请输入受影响数量"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请金额" name="claim_amount">
              <a-input-number
                v-model:value="formState.claim_amount"
                :min="0"
                :step="100"
                style="width: 100%"
                placeholder="请输入申请金额"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="出险地址" name="incident_location">
              <a-input v-model:value="formState.incident_location" placeholder="请输入出险地址" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="事故日期" name="incident_date">
              <a-date-picker
                v-model:value="formState.incident_date"
                style="width: 100%"
                placeholder="请选择事故日期"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="状态" name="claim_status">
              <a-select v-model:value="formState.claim_status" placeholder="请选择状态">
                <a-select-option value="pending">待处理</a-select-option>
                <a-select-option value="investigating">调查中</a-select-option>
                <a-select-option value="approved">已通过</a-select-option>
                <a-select-option value="rejected">已拒绝</a-select-option>
                <a-select-option value="paid">已赔付</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="事故描述" name="accident_description">
          <a-textarea
            v-model:value="formState.accident_description"
            placeholder="请输入事故详细描述"
            :rows="4"
          />
        </a-form-item>

        <a-form-item label="处理说明" name="process_description">
          <a-textarea
            v-model:value="formState.process_description"
            placeholder="请输入处理说明"
            :rows="3"
          />
        </a-form-item>

        <a-form-item label="拒绝原因" name="reject_reason">
          <a-textarea
            v-model:value="formState.reject_reason"
            placeholder="请输入拒绝原因（如适用）"
            :rows="2"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

const loading = ref(false)
const modalVisible = ref(false)
const detailVisible = ref(false)
const processVisible = ref(false)
const editingId = ref(null)
const currentClaim = ref(null)
const claimList = ref([])
const formRef = ref()
const processFormRef = ref()

const searchForm = reactive({
  claim_no: '',
  policy_no: '',
  reporter_name: '',
  contact_phone: '',
  claim_type: '',
  claim_status: ''
})

const formState = reactive({
  claim_no: '',
  policy_no: '',
  reporter_name: '',
  contact_phone: '',
  claim_type: '',
  affected_count: null,
  claim_amount: null,
  incident_location: '',
  incident_date: null,
  claim_status: 'pending',
  accident_description: '',
  process_description: '',
  reject_reason: '',
  approved_amount: null
})

const processForm = reactive({
  approved_amount: null,
  status: 'approved',
  reject_reason: '',
  process_description: ''
})

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

const columns = [
  {
    title: '理赔单号',
    dataIndex: 'claim_no',
    key: 'claim_no',
    width: 140
  },
  {
    title: '报案人',
    dataIndex: 'reporter_name',
    key: 'reporter_name',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'contact_phone',
    key: 'contact_phone',
    width: 120
  },
  {
    title: '保单号',
    dataIndex: 'policy_no',
    key: 'policy_no',
    width: 140
  },
  {
    title: '事故类型',
    dataIndex: 'claim_type',
    key: 'claim_type',
    width: 100
  },
  {
    title: '申请数量',
    dataIndex: 'affected_count',
    key: 'affected_count',
    width: 80
  },
  {
    title: '申请金额',
    key: 'claim_amount',
    dataIndex: 'claim_amount',
    width: 120
  },
  {
    title: '出险地址',
    dataIndex: 'incident_location',
    key: 'incident_location',
    width: 150
  },
  {
    title: '状态',
    key: 'claim_status',
    dataIndex: 'claim_status',
    width: 100
  },
  {
    title: '报案时间',
    dataIndex: 'report_date',
    key: 'report_date',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right'
  }
]

const rules = {
  claim_no: [{ required: true, message: '请输入理赔单号' }],
  policy_no: [{ required: true, message: '请输入保单号' }],
  reporter_name: [{ required: true, message: '请输入报案人姓名' }],
  contact_phone: [{ required: true, message: '请输入联系电话' }],
  claim_type: [{ required: true, message: '请选择事故类型' }],
  affected_count: [{ required: true, message: '请输入受影响数量' }],
  claim_amount: [{ required: true, message: '请输入申请金额' }],
  incident_location: [{ required: true, message: '请输入出险地址' }],
  incident_date: [{ required: true, message: '请选择事故日期' }],
  claim_status: [{ required: true, message: '请选择状态' }],
  accident_description: [{ required: true, message: '请输入事故描述' }]
}

const processRules = {
  approved_amount: [{ required: true, message: '请输入审核金额' }],
  status: [{ required: true, message: '请选择处理结果' }],
  reject_reason: [
    {
      required: true,
      message: '请输入拒绝原因',
      trigger: 'change',
      validator: (_, value) => {
        if (processForm.status === 'rejected' && !value) {
          return Promise.reject('拒绝时必须填写原因')
        }
        return Promise.resolve()
      }
    }
  ]
}

const modalTitle = computed(() => {
  return editingId.value ? '编辑理赔' : '新增理赔'
})

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

const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    processing: '处理中',
    completed: '已完成'
  }
  return texts[status] || '未知'
}

const getClaimTypeText = (type) => {
  const typeMap = {
    disease: '疾病',
    accident: '意外事故',
    natural_disaster: '自然灾害',
    theft: '盗窃',
    other: '其他'
  }
  return typeMap[type] || type
}

const getClaimTypeColor = (type) => {
  const colorMap = {
    disease: 'red',
    accident: 'orange',
    natural_disaster: 'purple',
    theft: 'volcano',
    other: 'default'
  }
  return colorMap[type] || 'default'
}

const loadClaims = async () => {
  loading.value = true
  console.log('🚀 开始加载理赔数据...')
  
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize
    }
    
    console.log('📋 当前搜索表单状态:', JSON.stringify(searchForm, null, 2))
    
    // 添加搜索条件
    if (searchForm.claim_no) {
      params.claim_no = searchForm.claim_no
      console.log('🔍 添加理赔单号搜索条件:', searchForm.claim_no)
    }
    if (searchForm.policy_no) {
      params.policy_no = searchForm.policy_no
      console.log('🔍 添加保单号搜索条件:', searchForm.policy_no)
    }
    if (searchForm.reporter_name) {
      params.reporter_name = searchForm.reporter_name
      console.log('🔍 添加报案人搜索条件:', searchForm.reporter_name)
    }
    if (searchForm.contact_phone) {
      params.contact_phone = searchForm.contact_phone
      console.log('🔍 添加联系电话搜索条件:', searchForm.contact_phone)
    }
    if (searchForm.claim_type) {
      params.claim_type = searchForm.claim_type
      console.log('🔍 添加事故类型搜索条件:', searchForm.claim_type)
    }
    if (searchForm.claim_status) {
      params.claim_status = searchForm.claim_status
      console.log('🔍 添加状态搜索条件:', searchForm.claim_status)
    }
    
    console.log('📤 [前端->后端] API请求参数:', {
      请求时间: new Date().toLocaleString(),
      请求URL: '/api/livestock-claims',
      请求方法: 'GET',
      请求参数: JSON.stringify(params, null, 2),
      分页信息: {
        当前页: pagination.current,
        每页条数: pagination.pageSize
      }
    })
    
    const response = await livestockClaimApi.getList(params)
    
    console.log('📥 [后端->前端] API响应:', {
      响应时间: new Date().toLocaleString(),
      响应状态: response.status,
      响应头: response.headers,
      响应数据结构: {
        status: response.data?.status,
        message: response.data?.message,
        data类型: Array.isArray(response.data?.data) ? 'Array' : typeof response.data?.data,
        data长度: response.data?.data?.length,
        pagination: response.data?.pagination
      },
      完整响应: JSON.stringify(response.data, null, 2)
    })
    
    if (response.data && response.data.status === 'success') {
      // 后端返回的数据直接是数组格式，不是{list: [], total: 8}格式
      const newClaimList = response.data.data || []
      const newTotal = response.data.pagination?.total || 0
      
      console.log('✅ 数据处理成功:', {
        处理时间: new Date().toLocaleString(),
        数据条数: newClaimList.length,
        总记录数: newTotal,
        数据样例: newClaimList.length > 0 ? JSON.stringify(newClaimList[0], null, 2) : '无数据'
      })
      
      claimList.value = newClaimList
      pagination.total = newTotal
      
      console.log('📊 前端状态更新:', {
        更新时间: new Date().toLocaleString(),
        列表长度: claimList.value.length,
        分页总数: pagination.total,
        当前页: pagination.current,
        每页条数: pagination.pageSize
      })
    } else {
      console.error('❌ 响应格式错误:', {
        错误时间: new Date().toLocaleString(),
        响应状态: response.data?.status,
        错误信息: response.data?.message,
        完整响应: response
      })
      message.error(response.data?.message || '加载理赔列表失败')
      claimList.value = []
    }
  } catch (error) {
    console.error('💥 API请求失败:', {
      错误时间: new Date().toLocaleString(),
      错误类型: error.name,
      错误信息: error.message,
      错误堆栈: error.stack,
      请求配置: error.config,
      响应数据: error.response?.data,
      响应状态: error.response?.status
    })
    message.error('加载理赔列表失败: ' + error.message)
  } finally {
    loading.value = false
    console.log('🏁 理赔数据加载完成')
  }
}

const handleSearch = () => {
    console.log('🔍 执行搜索操作:', {
      触发时间: new Date().toLocaleString(),
      搜索条件: JSON.stringify(searchForm, null, 2),
      重置分页: '第1页'
    })
    pagination.current = 1
    loadClaims()
  }

const resetSearch = () => {
  console.log('🔄 重置搜索表单')
  searchForm.claim_no = ''
  searchForm.policy_no = ''
  searchForm.reporter_name = ''
  searchForm.contact_phone = ''
  searchForm.claim_type = ''
  searchForm.claim_status = ''
  console.log('🔄 重置后的搜索表单:', JSON.stringify(searchForm, null, 2))
  loadClaims()
}

// 搜索字段输入监听器
const onSearchFieldInput = (fieldName, event) => {
  const value = event.target ? event.target.value : event
  console.log(`📝 [输入监听] ${fieldName}:`, {
    输入值: value,
    事件类型: 'input',
    时间戳: new Date().toLocaleString(),
    当前表单状态: JSON.stringify(searchForm, null, 2)
  })
}

// 搜索字段变化监听器
const onSearchFieldChange = (fieldName, event) => {
  const value = event.target ? event.target.value : event
  console.log(`🔍 [变化监听] ${fieldName}:`, {
    变化值: value,
    事件类型: 'change',
    时间戳: new Date().toLocaleString(),
    变化前表单: JSON.stringify(searchForm, null, 2)
  })
  
  // 延迟一点时间确保 v-model 已更新
  setTimeout(() => {
    console.log(`🔍 [变化后] ${fieldName}:`, {
      表单中的值: searchForm[fieldName],
      变化后表单: JSON.stringify(searchForm, null, 2)
    })
  }, 10)
}

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

const showModal = () => {
  editingId.value = null
  Object.assign(formState, {
    claim_no: '',
    policy_no: '',
    reporter_name: '',
    contact_phone: '',
    claim_type: '',
    affected_count: null,
    claim_amount: null,
    incident_location: '',
    incident_date: null,
    claim_status: 'pending',
    accident_description: '',
    process_description: '',
    reject_reason: '',
    approved_amount: null
  })
  modalVisible.value = true
}

const handleAdd = () => {
  showModal()
}

const handleView = (record) => {
  currentClaim.value = record
  detailVisible.value = true
}

const handleProcess = (record) => {
  currentClaim.value = record
  Object.assign(processForm, {
    approved_amount: record.claim_amount,
    status: 'approved',
    reject_reason: '',
    process_description: ''
  })
  processVisible.value = true
}

const handleEdit = (record) => {
  editingId.value = record.id
  
  // 复制记录数据到表单
  Object.assign(formState, {
    claim_no: record.claim_no,
    policy_no: record.policy_no,
    reporter_name: record.reporter_name,
    contact_phone: record.contact_phone,
    claim_type: record.claim_type,
    affected_count: record.affected_count,
    claim_amount: record.claim_amount,
    incident_location: record.incident_location,
    incident_date: record.incident_date ? dayjs(record.incident_date) : null,
    claim_status: record.claim_status,
    accident_description: record.accident_description,
    process_description: record.process_description,
    reject_reason: record.reject_reason,
    approved_amount: record.approved_amount
  })
  
  modalVisible.value = true
}

const handleApprove = async (record) => {
  try {
    // await livestockClaimApi.approve(record.id, { approved_amount: record.claim_amount })
    message.success('理赔申请已通过')
    loadClaims()
  } catch (error) {
    message.error('操作失败')
  }
}

const handleReject = async (record) => {
  message.info('请使用处理功能填写拒绝原因')
}

const handleProcessOk = async () => {
  try {
    await processFormRef.value.validate()
    
    // await livestockClaimApi.process(currentClaim.value.id, processForm)
    message.success('处理完成')
    processVisible.value = false
    loadClaims()
  } catch (error) {
    console.log('表单验证失败', error)
  }
}

const handleProcessCancel = () => {
  processVisible.value = false
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    
    const formData = { ...formState }
    
    // 处理日期格式
    if (formData.incident_date) {
      formData.incident_date = formData.incident_date.format('YYYY-MM-DD')
    }
    
    if (editingId.value) {
      // 编辑
      await livestockClaimApi.update(editingId.value, formData)
      message.success('更新成功')
    } else {
      // 新增
      // 生成理赔单号
      if (!formData.claim_no) {
        formData.claim_no = 'LC' + Date.now()
      }
      await livestockClaimApi.create(formData)
      message.success('新增成功')
    }
    
    modalVisible.value = false
    loadClaims()
  } catch (error) {
    console.error('保存失败:', error)
    message.error('保存失败: ' + (error.response?.data?.message || error.message))
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
}

const handleDelete = async (id) => {
  try {
    await livestockClaimApi.delete(id)
    message.success('删除成功')
    loadClaims()
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败: ' + (error.response?.data?.message || error.message))
  }
}

const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      search: searchForm.search || undefined,
      status: searchForm.status || undefined
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await livestockClaimApi.export(params)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `理赔列表_${new Date().getTime()}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

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

<style scoped>
.claim-management {
  padding: 0;
}

.document-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.document-size {
  color: #999;
  font-size: 12px;
}
</style>