<template>
  <div>
    <h1>金融保险</h1>
    
    <!-- 搜索和操作栏 -->
    <a-card style="margin-bottom: 16px;">
      <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
        <a-input v-model:value="searchKeyword" placeholder="输入养殖户姓名、保单号或身份证号" style="width: 300px;">
          <template #prefix>
            <span class="iconfont icon-sousuo"></span>
          </template>
        </a-input>
        
        <a-select v-model:value="insuranceTypeFilter" placeholder="保险类型" style="width: 150px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="health">健康保险</a-select-option>
          <a-select-option value="accident">意外险</a-select-option>
          <a-select-option value="property">财产保险</a-select-option>
          <a-select-option value="liability">责任险</a-select-option>
          <a-select-option value="agriculture">农业保险</a-select-option>
        </a-select>
        
        <a-select v-model:value="statusFilter" placeholder="保单状态" style="width: 120px;">
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="pending">待生效</a-select-option>
          <a-select-option value="active">已生效</a-select-option>
          <a-select-option value="expired">已过期</a-select-option>
          <a-select-option value="cancelled">已取消</a-select-option>
          <a-select-option value="claimed">已理赔</a-select-option>
        </a-select>
        
        <a-range-picker v-model:value="dateRange" style="width: 300px;" />
        
        <a-button type="primary" @click="handleSearch" style="margin-left: auto;">
          <span class="iconfont icon-sousuo"></span> 搜索
        </a-button>
        
        <a-button type="default" @click="handleReset">重置</a-button>
        
        <a-button type="dashed" @click="handleImport">
          <span class="iconfont icon-daoru"></span> 导入
        </a-button>
        
        <a-button type="dashed" @click="handleExport">
          <span class="iconfont icon-daochu"></span> 导出
        </a-button>
        
        <a-button type="primary" @click="handleAdd">
          <span class="iconfont icon-xinzeng"></span> 新增
        </a-button>
      </div>
    </a-card>
    
    <!-- 数据统计卡片 -->
    <a-row gutter={24} style="margin-bottom: 16px;">
      <a-col :span="6">
        <a-statistic title="总保单数" :value="totalPolicies" suffix="份" />
     </a-col>
      <a-col :span="6">
        <a-statistic title="在保保单" :value="activePolicies" suffix="份" :valueStyle="{ color: '#1890ff' }" />
  </a-col>
      <a-col :span="6">
        <a-statistic title="本月新增" :value="monthlyNew" suffix="份" :valueStyle="{ color: '#52c41a' }" />
     </a-col>
      <a-col :span="6">
        <a-statistic title="理赔金额" :value="claimAmount" suffix="万元" :valueStyle="{ color: '#faad14' }" />
    </a-col>
    </a-row>
    
    <!-- 保险类型分布图表 -->
    <a-card title="保险类型分布" style="margin-bottom: 16px;">
      <div style="display: flex; gap: 24px;">
        <div style="width: 50%; height: 300px;" ref="typePieChartRef"></div>
        <div style="width: 50%; height: 300px;" ref="trendChartRef"></div>
      </div>
    </a-card>
    
    <!-- 保单列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="insuranceList"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
         :scroll="{ x: 'max-content' }"
      >
        <!-- 保险类型列 -->
        <template #bodyCell:insuranceType="{ record }">
          <a-tag :color="getInsuranceTypeColor(record.insuranceType)">{{ getInsuranceTypeText(record.insuranceType) }}</a-tag>
        </template>
        
        <!-- 保单状态列 -->
        <template #bodyCell:status="{ record }">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </template>
        
        <!-- 操作列 -->
        <template #bodyCell:action="{ record }">
          <div style="display: flex; gap: 8px;">
            <a-button size="small" @click="handleView(record)">查看</a-button>
            <a-button size="small" type="primary" @click="handleEdit(record)" v-if="record.status !== 'expired' && record.status !== 'cancelled' && record.status !== 'claimed'">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record.id)" v-if="record.status !== 'expired' && record.status !== 'cancelled' && record.status !== 'claimed'">删除</a-button>
            <a-button size="small" @click="handleClaim(record.id)" v-if="record.status === 'active'">申请理赔</a-button>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑保单模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      title="新增/编辑金融保险保单"
      :footer="null"
      width={700}
    >
      <a-form
        :model="currentPolicy"
        layout="vertical"
        style="max-width: 500px; margin: 0 auto;"
      >
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="保单号" name="policyNumber" :rules="[{ required: true, message: '请输入保单号' }]">
              <a-input v-model:value="currentPolicy.policyNumber" placeholder="请输入保单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保险类型" name="insuranceType" :rules="[{ required: true, message: '请选择保险类型' }]">
              <a-select v-model:value="currentPolicy.insuranceType" placeholder="请选择保险类型">
                <a-select-option value="health">健康保险</a-select-option>
                <a-select-option value="accident">意外险</a-select-option>
                <a-select-option value="property">财产保险</a-select-option>
                <a-select-option value="liability">责任险</a-select-option>
                <a-select-option value="agriculture">农业保险</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="养殖户姓名" name="farmerName" :rules="[{ required: true, message: '请输入养殖户姓名' }]">
              <a-input v-model:value="currentPolicy.farmerName" placeholder="请输入养殖户姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="身份证号" name="idNumber" :rules="[{ required: true, message: '请输入身份证号' }]">
              <a-input v-model:value="currentPolicy.idNumber" placeholder="请输入身份证号" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="联系电话" name="phoneNumber" :rules="[{ required: true, message: '请输入联系电话' }]">
              <a-input v-model:value="currentPolicy.phoneNumber" placeholder="请输入联系电话" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保险公司" name="insuranceCompany" :rules="[{ required: true, message: '请选择保险公司' }]">
              <a-select v-model:value="currentPolicy.insuranceCompany" placeholder="请选择保险公司">
                <a-select-option v-for="company in insuranceCompanies" :key="company.id" :value="company.id">
                  {{ company.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="保险金额" name="coverageAmount" :rules="[{ required: true, message: '请输入保险金额' }]">
              <a-input-number v-model:value="currentPolicy.coverageAmount" min={1} style="width: 100%;" placeholder="保险金额" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保费" name="premium" :rules="[{ required: true, message: '请输入保费' }]">
              <a-input-number v-model:value="currentPolicy.premium" min={1} style="width: 100%;" placeholder="保费" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="生效日期" name="effectiveDate" :rules="[{ required: true, message: '请选择生效日期' }]">
              <a-date-picker v-model:value="currentPolicy.effectiveDate" style="width: 100%;" placeholder="生效日期" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="过期日期" name="expiryDate" :rules="[{ required: true, message: '请选择过期日期' }]">
              <a-date-picker v-model:value="currentPolicy.expiryDate" style="width: 100%;" placeholder="过期日期" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="保单状态" name="status" :rules="[{ required: true, message: '请选择保单状态' }]">
              <a-select v-model:value="currentPolicy.status" placeholder="请选择保单状态">
                <a-select-option value="pending">待生效</a-select-option>
                <a-select-option value="active">已生效</a-select-option>
                <a-select-option value="expired">已过期</a-select-option>
                <a-select-option value="cancelled">已取消</a-select-option>
                <a-select-option value="claimed">已理赔</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="政府补贴" name="governmentSubsidy">
              <a-input-number v-model:value="currentPolicy.governmentSubsidy" min={0} style="width: 100%;" placeholder="政府补贴金额" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="保险内容" name="coverageDetails">
          <a-input.TextArea v-model:value="currentPolicy.coverageDetails" placeholder="请输入保险内容详细说明" :rows="3" />
        </a-form-item>
        
        <a-form-item label="备注信息" name="remark">
          <a-input.TextArea v-model:value="currentPolicy.remark" placeholder="请输入备注信息" :rows="2" />
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isAddEditModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleSave">保存</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 查看保单详情模态框 -->
    <a-modal
      v-model:open="isViewModalOpen"
      title="金融保险保单详情"
      :footer="null"
      width={800}
    >
      <div v-if="viewPolicy" class="policy-detail">
        <div class="detail-row">
          <div class="detail-label">保单号：</div>
          <div class="detail-value">{{ viewPolicy.policyNumber }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">保险类型：</div>
          <div class="detail-value">{{ getInsuranceTypeText(viewPolicy.insuranceType) }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">养殖户姓名：</div>
          <div class="detail-value">{{ viewPolicy.farmerName }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">身份证号：</div>
          <div class="detail-value">{{ viewPolicy.idNumber }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">联系电话：</div>
          <div class="detail-value">{{ viewPolicy.phoneNumber }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">保险公司：</div>
          <div class="detail-value">{{ getInsuranceCompanyName(viewPolicy.insuranceCompany) }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">保险金额：</div>
          <div class="detail-value">{{ viewPolicy.coverageAmount }} 元</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">保费：</div>
          <div class="detail-value">{{ viewPolicy.premium }} 元</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">政府补贴：</div>
          <div class="detail-value">{{ viewPolicy.governmentSubsidy || 0 }} 元</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">生效日期：</div>
          <div class="detail-value">{{ viewPolicy.effectiveDate }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">过期日期：</div>
          <div class="detail-value">{{ viewPolicy.expiryDate }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">保单状态：</div>
          <div class="detail-value">
            <a-tag :color="getStatusColor(viewPolicy.status)">{{ getStatusText(viewPolicy.status) }}</a-tag>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-label">保险内容：</div>
          <div class="detail-value">{{ viewPolicy.coverageDetails || '无' }}</div>
        </div>
        <div class="detail-row" v-if="viewPolicy.claimDetails">
          <div class="detail-label">理赔信息：</div>
          <div class="detail-value">{{ viewPolicy.claimDetails }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">备注信息：</div>
          <div class="detail-value">{{ viewPolicy.remark || '无' }}</div>
        </div>
        
        <!-- 相关文件 -->
        <div class="detail-row" v-if="viewPolicy.files && viewPolicy.files.length > 0">
          <div class="detail-label">保单文件：</div>
          <div class="detail-value">
            <a-upload-list
              :items="getUploadItems(viewPolicy.files)"
              :locale="{ removeFile: '删除', downloadFile: '下载' }"
              :showRemoveIcon="false"
              :showDownloadIcon="true"
            />
          </div>
        </div>
      </div>
      <div style="text-align: center; margin-top: 24px;">
        <a-button @click="isViewModalOpen = false">关闭</a-button>
      </div>
    </a-modal>
    
    <!-- 理赔申请模态框 -->
    <a-modal
      v-model:open="isClaimModalOpen"
      title="保险理赔申请"
      :footer="null"
      width={600}
    >
      <a-form
        :model="claimForm"
        layout="vertical"
        style="max-width: 500px; margin: 0 auto;"
      >
        <a-form-item label="保单号" :disabled="true">
          <a-input v-model:value="claimForm.policyNumber" placeholder="保单号" />
        </a-form-item>
        
        <a-form-item label="理赔金额" name="claimAmount" :rules="[{ required: true, message: '请输入理赔金额' }]">
          <a-input-number v-model:value="claimForm.claimAmount" min={1} style="width: 100%;" placeholder="理赔金额" />
        </a-form-item>
        
        <a-form-item label="理赔原因" name="claimReason" :rules="[{ required: true, message: '请输入理赔原因' }]">
          <a-input.TextArea v-model:value="claimForm.claimReason" placeholder="请输入详细的理赔原因" :rows="4" />
        </a-form-item>
        
        <a-form-item label="上传证明材料">
          <a-upload
            name="file"
            :multiple="true"
            :showUploadList="true"
            :beforeUpload="beforeUpload"
            @change="handleUploadChange"
            accept=".jpg,.jpeg,.png,.pdf,.doc,.docx"
          >
            <a-button>
              <span class="iconfont icon-upload"></span> 选择文件
            </a-button>
          </a-upload>
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isClaimModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleClaimSubmit">提交申请</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 确认对话框 -->
    <a-popconfirm
      v-model:open="isConfirmModalOpen"
      title="确认操作"
      :description="confirmMessage"
      ok-text="确认"
      cancel-text="取消"
      @confirm="handleConfirmAction"
    >
      <template #reference>
        <!-- 这里是空的，通过其他按钮触发 -->
      </template>
    </a-popconfirm>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import * as echarts from 'echarts'

// 搜索条件
const searchKeyword = ref('')
const insuranceTypeFilter = ref('')
const statusFilter = ref('')
const dateRange = ref([])

// 统计数据
const totalPolicies = ref(1256)
const activePolicies = ref(890)
const monthlyNew = ref(156)
const claimAmount = ref(78.5)

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

// 选中的行
const selectedRowKeys = ref([])
const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys
}

// 图表引用
const typePieChartRef = ref(null)
const trendChartRef = ref(null)

// 模态框状态
const isAddEditModalOpen = ref(false)
const isViewModalOpen = ref(false)
const isClaimModalOpen = ref(false)
const isConfirmModalOpen = ref(false)
const confirmMessage = ref('')
const confirmAction = ref('')
const confirmTargetId = ref('')

// 当前编辑的保单
const currentPolicy = reactive({
  id: '',
  policyNumber: '',
  insuranceType: 'agriculture',
  farmerName: '',
  idNumber: '',
  phoneNumber: '',
  insuranceCompany: '',
  coverageAmount: 0,
  premium: 0,
  governmentSubsidy: 0,
  effectiveDate: '',
  expiryDate: '',
  status: 'pending',
  coverageDetails: '',
  claimDetails: '',
  remark: '',
  files: []
})

// 查看的保单
const viewPolicy = ref(null)

// 理赔表单
const claimForm = reactive({
  policyNumber: '',
  claimAmount: 0,
  claimReason: '',
  files: []
})

// 理赔上传文件列表
const uploadFileList = ref([])

// 保险公司列表
const insuranceCompanies = ref([
  { id: '1', name: '中国人民保险' },
  { id: '2', name: '中国平安保险' },
  { id: '3', name: '中国人寿保险' },
  { id: '4', name: '太平洋保险' },
  { id: '5', name: '中华联合保险' },
  { id: '6', name: '阳光保险' },
  { id: '7', name: '大地保险' }
])

// 保险列表数据
const insuranceList = ref([
  {
    id: '1',
    policyNumber: 'INS2023001',
    insuranceType: 'agriculture',
    farmerName: '张三',
    idNumber: '110101199001011234',
    phoneNumber: '13800138001',
    insuranceCompany: '1',
    coverageAmount: 100000,
    premium: 5000,
    governmentSubsidy: 2000,
    effectiveDate: '2023-01-01',
    expiryDate: '2024-01-01',
    status: 'active',
    coverageDetails: '养殖保险：覆盖牛群100头，主要保障疾病、自然灾害等风险',
    remark: '',
    files: ['保单文件1.pdf', '保单文件2.jpg']
  },
  {
    id: '2',
    policyNumber: 'INS2023002',
    insuranceType: 'health',
    farmerName: '李四',
    idNumber: '110101199002022345',
    phoneNumber: '13800138002',
    insuranceCompany: '2',
    coverageAmount: 50000,
    premium: 3000,
    governmentSubsidy: 1000,
    effectiveDate: '2023-02-01',
    expiryDate: '2024-02-01',
    status: 'active',
    coverageDetails: '健康保险：养殖户健康保障，包括意外伤害和重大疾病',
    remark: '',
    files: ['保单文件3.pdf']
  },
  {
    id: '3',
    policyNumber: 'INS2023003',
    insuranceType: 'property',
    farmerName: '王五',
    idNumber: '110101199003033456',
    phoneNumber: '13800138003',
    insuranceCompany: '3',
    coverageAmount: 150000,
    premium: 6000,
    governmentSubsidy: 2500,
    effectiveDate: '2023-03-01',
    expiryDate: '2024-03-01',
    status: 'active',
    coverageDetails: '财产保险：养殖场财产保障，包括建筑物、设备等',
    remark: '',
    files: ['保单文件4.pdf', '保单文件5.jpg']
  },
  {
    id: '4',
    policyNumber: 'INS2023004',
    insuranceType: 'liability',
    farmerName: '赵六',
    idNumber: '110101199004044567',
    phoneNumber: '13800138004',
    insuranceCompany: '4',
    coverageAmount: 200000,
    premium: 8000,
    governmentSubsidy: 3000,
    effectiveDate: '2023-04-01',
    expiryDate: '2024-04-01',
    status: 'active',
    coverageDetails: '责任险：养殖场所需的第三方责任保障',
    remark: '',
    files: ['保单文件6.pdf']
  },
  {
    id: '5',
    policyNumber: 'INS2023005',
    insuranceType: 'accident',
    farmerName: '孙七',
    idNumber: '110101199005055678',
    phoneNumber: '13800138005',
    insuranceCompany: '5',
    coverageAmount: 80000,
    premium: 2000,
    governmentSubsidy: 800,
    effectiveDate: '2023-05-01',
    expiryDate: '2024-05-01',
    status: 'active',
    coverageDetails: '意外险：养殖户工作意外伤害保障',
    remark: '',
    files: ['保单文件7.pdf']
  },
  {
    id: '6',
    policyNumber: 'INS2023006',
    insuranceType: 'agriculture',
    farmerName: '周八',
    idNumber: '110101199006066789',
    phoneNumber: '13800138006',
    insuranceCompany: '1',
    coverageAmount: 120000,
    premium: 6000,
    governmentSubsidy: 2500,
    effectiveDate: '2023-01-01',
    expiryDate: '2023-12-31',
    status: 'expired',
    coverageDetails: '养殖保险：覆盖牛群120头，主要保障疾病、自然灾害等风险',
    remark: '已过期，待续保',
    files: ['保单文件8.pdf']
  },
  {
    id: '7',
    policyNumber: 'INS2023007',
    insuranceType: 'agriculture',
    farmerName: '吴九',
    idNumber: '110101199007077890',
    phoneNumber: '13800138007',
    insuranceCompany: '2',
    coverageAmount: 90000,
    premium: 4500,
    governmentSubsidy: 1800,
    effectiveDate: '2023-06-01',
    expiryDate: '2024-06-01',
    status: 'claimed',
    coverageDetails: '养殖保险：覆盖牛群90头，主要保障疾病、自然灾害等风险',
    claimDetails: '因暴雨导致牛棚受损，理赔金额50000元',
    remark: '已完成理赔',
    files: ['保单文件9.pdf', '理赔材料1.pdf', '理赔材料2.jpg']
  },
  {
    id: '8',
    policyNumber: 'INS2023008',
    insuranceType: 'agriculture',
    farmerName: '郑十',
    idNumber: '110101199008088901',
    phoneNumber: '13800138008',
    insuranceCompany: '3',
    coverageAmount: 110000,
    premium: 5500,
    governmentSubsidy: 2200,
    effectiveDate: '2023-07-01',
    expiryDate: '2024-07-01',
    status: 'pending',
    coverageDetails: '养殖保险：覆盖牛群110头，主要保障疾病、自然灾害等风险',
    remark: '新申请，待审核',
    files: ['保单文件10.pdf']
  },
  {
    id: '9',
    policyNumber: 'INS2023009',
    insuranceType: 'agriculture',
    farmerName: '钱十一',
    idNumber: '110101199009099012',
    phoneNumber: '13800138009',
    insuranceCompany: '4',
    coverageAmount: 80000,
    premium: 4000,
    governmentSubsidy: 1600,
    effectiveDate: '2023-02-01',
    expiryDate: '2024-02-01',
    status: 'cancelled',
    coverageDetails: '养殖保险：覆盖牛群80头，主要保障疾病、自然灾害等风险',
    remark: '养殖户主动取消',
    files: ['保单文件11.pdf', '取消申请.pdf']
  },
  {
    id: '10',
    policyNumber: 'INS2023010',
    insuranceType: 'agriculture',
    farmerName: '孙十二',
    idNumber: '110101199010100123',
    phoneNumber: '13800138010',
    insuranceCompany: '5',
    coverageAmount: 130000,
    premium: 6500,
    governmentSubsidy: 2800,
    effectiveDate: '2023-08-01',
    expiryDate: '2024-08-01',
    status: 'active',
    coverageDetails: '养殖保险：覆盖牛群130头，主要保障疾病、自然灾害等风险',
    remark: '',
    files: ['保单文件12.pdf']
  }
])

// 表格列定义
const columns = [
  {
    title: '保单号',
    dataIndex: 'policyNumber',
    key: 'policyNumber',
    width: 150
  },
  {
    title: '保险类型',
    dataIndex: 'insuranceType',
    key: 'insuranceType',
    width: 100
  },
  {
    title: '养殖户姓名',
    dataIndex: 'farmerName',
    key: 'farmerName',
    width: 100
  },
  {
    title: '身份证号',
    dataIndex: 'idNumber',
    key: 'idNumber',
    width: 180
  },
  {
    title: '保险公司',
    dataIndex: 'insuranceCompany',
    key: 'insuranceCompany',
    width: 120,
    customRender: ({ text }) => getInsuranceCompanyName(text)
  },
  {
    title: '保险金额',
    dataIndex: 'coverageAmount',
    key: 'coverageAmount',
    width: 100,
    customRender: ({ text }) => `${text} 元`
  },
  {
    title: '保费',
    dataIndex: 'premium',
    key: 'premium',
    width: 80,
    customRender: ({ text }) => `${text} 元`
  },
  {
    title: '政府补贴',
    dataIndex: 'governmentSubsidy',
    key: 'governmentSubsidy',
    width: 100,
    customRender: ({ text }) => `${text || 0} 元`
  },
  {
    title: '生效日期',
    dataIndex: 'effectiveDate',
    key: 'effectiveDate',
    width: 120
  },
  {
    title: '过期日期',
    dataIndex: 'expiryDate',
    key: 'expiryDate',
    width: 120
  },
  {
    title: '保单状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    fixed: 'right'
  }
]

// 获取保险类型文本
const getInsuranceTypeText = (insuranceType) => {
  switch (insuranceType) {
    case 'health': return '健康保险'
    case 'accident': return '意外险'
    case 'property': return '财产保险'
    case 'liability': return '责任险'
    case 'agriculture': return '农业保险'
    default: return insuranceType
  }
}

// 获取保险类型颜色
const getInsuranceTypeColor = (insuranceType) => {
  switch (insuranceType) {
    case 'health': return 'blue'
    case 'accident': return 'green'
    case 'property': return 'orange'
    case 'liability': return 'purple'
    case 'agriculture': return 'red'
    default: return 'default'
  }
}

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 'pending': return 'default'
    case 'active': return 'green'
    case 'expired': return 'gray'
    case 'cancelled': return 'volcano'
    case 'claimed': return 'blue'
    default: return 'default'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending': return '待生效'
    case 'active': return '已生效'
    case 'expired': return '已过期'
    case 'cancelled': return '已取消'
    case 'claimed': return '已理赔'
    default: return status
  }
}

// 获取保险公司名称
const getInsuranceCompanyName = (id) => {
  const company = insuranceCompanies.value.find(item => item.id === id)
  return company ? company.name : id
}

// 获取上传文件项
const getUploadItems = (files) => {
  return files.map((file, index) => ({
    uid: `${index}`,
    name: file,
    status: 'done',
    url: `#${file}`,
  }))
}

// 搜索处理
const handleSearch = () => {
  console.log('搜索条件:', {
    keyword: searchKeyword.value,
    insuranceType: insuranceTypeFilter.value,
    status: statusFilter.value,
    dateRange: dateRange.value
  })
  // 这里应该有实际的搜索逻辑
  // 模拟搜索后的总数
  pagination.total = insuranceList.value.length
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  insuranceTypeFilter.value = ''
  statusFilter.value = ''
  dateRange.value = []
  selectedRowKeys.value = []
}

// 导入处理
const handleImport = () => {
  console.log('导入保单记录')
  // 这里应该有实际的导入逻辑
}

// 导出处理
const handleExport = () => {
  console.log('导出保单记录')
  // 这里应该有实际的导出逻辑
}

// 新增保单
const handleAdd = () => {
  // 重置当前保单数据
  Object.assign(currentPolicy, {
    id: '',
    policyNumber: '',
    insuranceType: 'agriculture',
    farmerName: '',
    idNumber: '',
    phoneNumber: '',
    insuranceCompany: '',
    coverageAmount: 0,
    premium: 0,
    governmentSubsidy: 0,
    effectiveDate: '',
    expiryDate: '',
    status: 'pending',
    coverageDetails: '',
    claimDetails: '',
    remark: '',
    files: []
  })
  isAddEditModalOpen.value = true
}

// 编辑保单
const handleEdit = (record) => {
  // 复制记录数据到当前保单
  Object.assign(currentPolicy, JSON.parse(JSON.stringify(record)))
  isAddEditModalOpen.value = true
}

// 查看保单
const handleView = (record) => {
  viewPolicy.value = JSON.parse(JSON.stringify(record))
  isViewModalOpen.value = true
}

// 删除保单 - 弹出确认对话框
const handleDelete = (id) => {
  confirmMessage.value = '确定要删除该保单吗？'
  confirmAction.value = 'delete'
  confirmTargetId.value = id
  isConfirmModalOpen.value = true
}

// 申请理赔
const handleClaim = (id) => {
  const policy = insuranceList.value.find(item => item.id === id)
  if (policy) {
    Object.assign(claimForm, {
      policyNumber: policy.policyNumber,
      claimAmount: 0,
      claimReason: '',
      files: []
    })
    uploadFileList.value = []
    isClaimModalOpen.value = true
  }
}

// 提交理赔申请
const handleClaimSubmit = () => {
  console.log('提交理赔申请:', claimForm)
  // 这里应该有实际的提交理赔申请逻辑
  // 模拟提交成功
  isClaimModalOpen.value = false
  alert('理赔申请提交成功，请等待审核')
}

// 确认操作
const handleConfirmAction = () => {
  if (confirmAction.value === 'delete') {
    console.log('删除保单:', confirmTargetId.value)
    // 这里应该有实际的删除逻辑
    // 模拟删除成功
    alert(`成功删除保单ID: ${confirmTargetId.value}`)
  }
  isConfirmModalOpen.value = false
}

// 保存保单
const handleSave = () => {
  console.log('保存保单:', currentPolicy)
  // 这里应该有实际的保存逻辑
  // 模拟保存成功
  isAddEditModalOpen.value = false
  alert('保存成功')
}

// 文件上传前处理
const beforeUpload = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    alert('文件大小不能超过 2MB!')
    return Upload.LIST_IGNORE
  }
  return false // 阻止自动上传
}

// 文件上传变化处理
const handleUploadChange = ({ fileList }) => {
  uploadFileList.value = fileList
}

// 初始化保险类型分布饼图
const initTypePieChart = () => {
  if (!typePieChartRef.value) return
  
  const chart = echarts.init(typePieChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: '5%',
      left: 'center'
    },
    series: [
      {
        name: '保险类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 20,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 650, name: '农业保险' },
          { value: 250, name: '健康保险' },
          { value: 150, name: '财产保险' },
          { value: 100, name: '责任险' },
          { value: 106, name: '意外险' }
        ]
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化保险趋势图表
const initTrendChart = () => {
  if (!trendChartRef.value) return
  
  const chart = echarts.init(trendChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['保单数量', '理赔金额(万元)']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: [
      {
        type: 'value',
        name: '保单数量',
        position: 'left'
      },
      {
        type: 'value',
        name: '理赔金额(万元)',
        position: 'right'
      }
    ],
    series: [
      {
        name: '保单数量',
        type: 'line',
        stack: 'Total',
        data: [120, 132, 101, 134, 90, 120, 130, 125, 110, 120, 115, 130]
      },
      {
        name: '理赔金额(万元)',
        type: 'line',
        yAxisIndex: 1,
        data: [5, 7.2, 8.1, 9.4, 12, 13.2, 12.1, 11.4, 10, 8, 7.5, 9]
      }
    ]
  }
  
  chart.setOption(option)
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initTypePieChart()
    initTrendChart()
  }, 100)
})

// 初始化数据
pagination.total = insuranceList.value.length
</script>

<style scoped>
  .policy-detail {
    padding: 16px;
  }
  
  .detail-row {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-start;
  }
  
  .detail-label {
    width: 120px;
    font-weight: bold;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    color: #333;
  }
</style>