<template>
  <div class="application-management">
    <a-card title="参保申请管理" :bordered="false">
      <!-- 搜索区域 -->
      <div class="search-area">
        <a-form
          :model="searchForm"
          layout="inline"
          @finish="handleSearch"
        >
          <a-form-item label="申请单号">
            <a-input
              v-model:value="searchForm.application_no"
              placeholder="请输入申请单号"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="投保人姓名">
            <a-input
              v-model:value="searchForm.customer_name"
              placeholder="请输入投保人姓名"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="参保险种">
            <a-select
              v-model:value="searchForm.insuranceType"
              placeholder="请选择参保险种"
              allow-clear
              style="width: 150px"
            >
              <a-select-option
                v-for="type in insuranceTypes"
                :key="type.id"
                :value="type.name"
              >
                {{ type.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="参保类型">
            <a-select
              v-model:value="searchForm.insuranceCategory"
              placeholder="请选择参保类型"
              allow-clear
              style="width: 120px"
            >
              <a-select-option value="养殖">养殖</a-select-option>
              <a-select-option value="畜牧养殖">畜牧养殖</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="申请状态">
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择申请状态"
              allow-clear
              style="width: 120px"
            >
              <a-select-option value="pending">待审核</a-select-option>
              <a-select-option value="initial_approved">初审通过</a-select-option>
              <a-select-option value="under_review">复审中</a-select-option>
              <a-select-option value="approved">已通过</a-select-option>
              <a-select-option value="rejected">已拒绝</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space>
              <a-button type="primary" html-type="submit" :loading="loading">
                搜索
              </a-button>
              <a-button @click="resetSearch">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <a-space>
          <a-button type="primary" @click="showCreateModal">
            新增申请
          </a-button>
          <a-button @click="exportData" :loading="exportLoading">
            导出数据
          </a-button>
        </a-space>
      </div>

      <!-- 表格 -->
      <a-table
        :columns="columns"
        :data-source="applications"
        :loading="loading"
        :pagination="pagination"
        :scroll="{ x: 1500 }"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'insurance_category'">
            {{ record.insurance_category }}
          </template>
          <template v-else-if="column.key === 'insurance_amount'">
            ¥{{ Number(record.insurance_amount).toLocaleString() }}
          </template>
          <template v-else-if="column.key === 'insurance_period'">
            {{ record.insurance_period }}个月
          </template>
          <template v-else-if="column.key === 'phone'">
            {{ maskPhone(record.phone) }}
          </template>
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="showApplicationDetail(record)"
              >
                查看
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="editApplication(record)"
                v-if="record.status === 'pending'"
              >
                编辑
              </a-button>
              <a-button
                type="link"
                size="small"
                @click="reviewApplication(record)"
                v-if="['pending', 'initial_approved', 'under_review'].includes(record.status)"
              >
                审核
              </a-button>
              <a-popconfirm
                title="确定要删除这条申请吗？"
                @confirm="deleteApplication(record)"
                v-if="record.status === 'pending'"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 申请详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="申请详情"
      width="800px"
      :footer="null"
    >
      <a-descriptions
        v-if="selectedApplication"
        :column="2"
        bordered
        size="small"
      >
        <a-descriptions-item label="申请单号" :span="2">
          {{ selectedApplication.application_no }}
        </a-descriptions-item>
        <a-descriptions-item label="参保类型">
          {{ selectedApplication.insurance_category }}
        </a-descriptions-item>
        <a-descriptions-item label="参保险种">
          {{ selectedApplication.insurance_type?.name || selectedApplication.insurance_type_id }}
        </a-descriptions-item>
        <a-descriptions-item label="保险金额">
          ¥{{ Number(selectedApplication.application_amount).toLocaleString() }}
        </a-descriptions-item>
        <a-descriptions-item label="保险期限">
          {{ selectedApplication.insurance_period }}个月
        </a-descriptions-item>
        <a-descriptions-item label="投保人姓名">
          {{ selectedApplication.customer_name }}
        </a-descriptions-item>
        <a-descriptions-item label="身份证号">
          {{ maskIdCard(selectedApplication.customer_id_card) }}
        </a-descriptions-item>
        <a-descriptions-item label="联系电话">
          {{ maskPhone(selectedApplication.customer_phone) }}
        </a-descriptions-item>
        <a-descriptions-item label="联系地址" :span="2">
          {{ selectedApplication.customer_address }}
        </a-descriptions-item>
        <a-descriptions-item label="申请时间">
          {{ selectedApplication.application_date }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(selectedApplication.status)">
            {{ getStatusText(selectedApplication.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">
          {{ selectedApplication.remarks || '无' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 审核模态框 -->
    <a-modal
      v-model:open="reviewModalVisible"
      title="申请审核"
      width="600px"
      @ok="handleReview"
      :confirm-loading="reviewLoading"
    >
      <a-form
        :model="reviewFormData"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="审核结果" name="result" :rules="[{ required: true, message: '请选择审核结果' }]">
          <a-radio-group v-model:value="reviewFormData.result">
            <a-radio value="approved">通过</a-radio>
            <a-radio value="rejected">拒绝</a-radio>
            <a-radio value="pending_review">需要复审</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          v-if="reviewFormData.result === 'rejected'"
          label="拒绝原因"
          name="rejectReason"
          :rules="[{ required: true, message: '请选择拒绝原因' }]"
        >
          <a-select v-model:value="reviewFormData.rejectReason" placeholder="请选择拒绝原因">
            <a-select-option value="incomplete_info">信息不完整</a-select-option>
            <a-select-option value="invalid_documents">证件无效</a-select-option>
            <a-select-option value="risk_assessment">风险评估不通过</a-select-option>
            <a-select-option value="other">其他原因</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item
          v-if="reviewFormData.result === 'rejected' && reviewFormData.rejectReason === 'other'"
          label="详细说明"
          name="rejectReasonDetail"
          :rules="[{ required: true, message: '请输入详细说明' }]"
        >
          <a-textarea v-model:value="reviewFormData.rejectReasonDetail" placeholder="请输入拒绝的详细原因" />
        </a-form-item>
        <a-form-item label="审核备注" name="reviewNotes">
          <a-textarea v-model:value="reviewFormData.reviewNotes" placeholder="请输入审核备注" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增/编辑申请模态框 -->
    <a-modal
      v-model:open="createModalVisible"
      :title="isEdit ? '编辑申请' : '新增申请'"
      width="800px"
      @ok="handleCreateOrUpdate"
      :confirm-loading="createLoading"
    >
      <a-form
        :model="createForm"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        ref="createFormRef"
      >
        <a-form-item label="参保类型" name="insurance_category" :rules="[{ required: true, message: '请选择参保类型' }]">
          <a-radio-group v-model:value="createForm.insurance_category">
            <a-radio value="养殖">养殖</a-radio>
            <a-radio value="畜牧养殖">畜牧养殖</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="参保险种" name="insurance_type_id" :rules="[{ required: true, message: '请选择参保险种' }]">
          <a-select v-model:value="createForm.insurance_type_id" placeholder="请选择参保险种">
            <a-select-option
              v-for="type in insuranceTypes"
              :key="type.id"
              :value="type.id"
            >
              {{ type.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="保险金额" name="application_amount" :rules="[{ required: true, message: '请输入保险金额' }]">
          <a-input-number
            v-model:value="createForm.application_amount"
            :min="0"
            :precision="2"
            style="width: 100%"
            placeholder="请输入保险金额"
          />
        </a-form-item>
        <a-form-item label="保险期限" name="insurance_period" :rules="[{ required: true, message: '请选择保险期限' }]">
          <a-select v-model:value="createForm.insurance_period" placeholder="请选择保险期限">
            <a-select-option value="12">12个月</a-select-option>
            <a-select-option value="24">24个月</a-select-option>
            <a-select-option value="36">36个月</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="投保人姓名" name="customer_name" :rules="[{ required: true, message: '请输入投保人姓名' }]">
          <a-input v-model:value="createForm.customer_name" placeholder="请输入投保人姓名" />
        </a-form-item>
        <a-form-item label="身份证号" name="customer_id_card" :rules="[{ required: true, message: '请输入身份证号' }]">
          <a-input v-model:value="createForm.customer_id_card" placeholder="请输入身份证号" />
        </a-form-item>
        <a-form-item label="联系电话" name="customer_phone" :rules="[{ required: true, message: '请输入联系电话' }]">
          <a-input v-model:value="createForm.customer_phone" placeholder="请输入联系电话" />
        </a-form-item>
        <a-form-item label="联系地址" name="customer_address" :rules="[{ required: true, message: '请输入联系地址' }]">
          <a-textarea v-model:value="createForm.customer_address" placeholder="请输入联系地址" />
        </a-form-item>
        <a-form-item label="备注" name="remarks">
          <a-textarea v-model:value="createForm.remarks" placeholder="请输入备注信息" />
        </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 { applicationAPI, insuranceTypeAPI } from '@/utils/api'
import { validateListResponse, validatePagination } from '@/utils/dataValidator'

// 响应式数据
const loading = ref(false)
const exportLoading = ref(false)
const reviewLoading = ref(false)
const createLoading = ref(false)
const applications = ref([])
const insuranceTypes = ref([])

// 模态框显示状态
const detailModalVisible = ref(false)
const reviewModalVisible = ref(false)
const createModalVisible = ref(false)
const isEdit = ref(false)
const selectedApplication = ref(null)

// 搜索表单
const searchForm = reactive({
  application_no: '',
  customer_name: '',
  insuranceType: '',
  insuranceCategory: '',
  status: ''
})

// 审核表单
const reviewFormData = reactive({
  result: '',
  rejectReason: '',
  rejectReasonDetail: '',
  reviewNotes: '',
  comments: ''
})

// 新增申请表单
const createForm = reactive({
  insurance_category: '',
  insurance_type_id: '',
  application_amount: null,
  insurance_period: '',
  customer_name: '',
  customer_id_card: '',
  customer_phone: '',
  customer_address: '',
  remarks: ''
})

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
})

// 表格列配置
const columns = [
  {
    title: '申请单号',
    dataIndex: 'application_no',
    key: 'application_no',
    width: 180,
    fixed: 'left'
  },
  {
    title: '投保人姓名',
    dataIndex: 'customer_name',
    key: 'applicant_name',
    width: 120
  },
  {
    title: '参保类型',
    dataIndex: 'insurance_category',
    key: 'insurance_category',
    width: 100
  },
  {
    title: '参保险种',
    dataIndex: 'insurance_type_id',
    key: 'insurance_type_id',
    width: 150,
    customRender: ({ record }) => {
      return record.insurance_type?.name || record.insurance_type_id
    }
  },
  {
    title: '保险金额',
    dataIndex: 'application_amount',
    key: 'application_amount',
    width: 120
  },
  {
    title: '保险期限',
    dataIndex: 'insurance_period',
    key: 'insurance_period',
    width: 100
  },
  {
    title: '联系电话',
    dataIndex: 'customer_phone',
    key: 'customer_phone',
    width: 130
  },
  {
    title: '申请时间',
    dataIndex: 'application_date',
    key: 'application_date',
    width: 150,
    sorter: true
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    filters: [
      { text: '待审核', value: 'pending' },
      { text: '初审通过', value: 'initial_approved' },
      { text: '复审中', value: 'under_review' },
      { text: '已通过', value: 'approved' },
      { text: '已拒绝', value: 'rejected' }
    ]
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 方法定义
const loadApplications = async () => {
  loading.value = true
  try {
    // 构建搜索参数，映射前端字段名到后端期望的字段名
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      // 字段名映射
      applicationNumber: searchForm.application_no || undefined,
      applicantName: searchForm.customer_name || undefined,
      insuranceType: searchForm.insuranceType || undefined,
      insuranceCategory: searchForm.insuranceCategory || undefined,
      status: searchForm.status || undefined
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    console.log('搜索参数:', params)
    const response = await applicationAPI.getList(params)
    console.log('申请列表API响应:', response)
    
    if (response.data && response.data.status === 'success') {
      // API返回的数据直接是数组格式，不是{list: [], total: 146}格式
      applications.value = response.data.data || []
      pagination.total = response.data.pagination?.total || 0
      console.log('申请列表数据设置成功:', applications.value.length, '条')
    } else {
      console.log('申请列表响应格式错误:', response)
      message.error('加载申请数据失败')
      applications.value = []
    }
  } catch (error) {
    console.error('加载申请数据失败:', error)
    message.error('加载申请数据失败')
    applications.value = []
  } finally {
    loading.value = false
  }
}

const loadInsuranceTypes = async () => {
  try {
    const response = await insuranceTypeAPI.getList()
    console.log('保险类型API响应:', response)
    
    if (response.data && response.data.status === 'success') {
      insuranceTypes.value = response.data.data || []
      console.log('保险类型数据设置成功:', insuranceTypes.value.length, '个')
    } else {
      console.log('保险类型响应格式错误:', response)
      message.error('加载险种数据失败')
      insuranceTypes.value = []
    }
  } catch (error) {
    console.error('加载险种数据失败:', error)
    message.error('加载险种数据失败')
    insuranceTypes.value = []
  }
}

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

const resetSearch = () => {
  Object.assign(searchForm, {
    application_no: '',
    customer_name: '',
    insuranceType: '',
    insuranceCategory: '',
    status: ''
  })
  pagination.current = 1
  loadApplications()
}

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

const showApplicationDetail = (record) => {
  selectedApplication.value = record
  detailModalVisible.value = true
}

const editApplication = (record) => {
  isEdit.value = true
  Object.assign(createForm, record)
  createModalVisible.value = true
}

const reviewApplication = (record) => {
  selectedApplication.value = record
  Object.assign(reviewFormData, {
    result: '',
    rejectReason: '',
    rejectReasonDetail: '',
    reviewNotes: '',
    comments: ''
  })
  reviewModalVisible.value = true
}

const handleReview = async () => {
  reviewLoading.value = true
  try {
    await applicationAPI.review(selectedApplication.value.id, reviewFormData)
    message.success('审核完成')
    reviewModalVisible.value = false
    loadApplications()
  } catch (error) {
    console.error('审核失败:', error)
    message.error('审核失败')
  } finally {
    reviewLoading.value = false
  }
}

const showCreateModal = () => {
  isEdit.value = false
  Object.assign(createForm, {
    insurance_category: '',
    insurance_type_id: '',
    application_amount: null,
    insurance_period: '',
    customer_name: '',
    customer_id_card: '',
    customer_phone: '',
    customer_address: '',
    remarks: ''
  })
  createModalVisible.value = true
}

const handleCreateOrUpdate = async () => {
  createLoading.value = true
  try {
    if (isEdit.value) {
      await applicationAPI.update(createForm.id, createForm)
      message.success('更新成功')
    } else {
      await applicationAPI.create(createForm)
      message.success('创建成功')
    }
    createModalVisible.value = false
    loadApplications()
  } catch (error) {
    console.error(isEdit.value ? '更新失败:' : '创建失败:', error)
    message.error(isEdit.value ? '更新失败' : '创建失败')
  } finally {
    createLoading.value = false
  }
}

const deleteApplication = async (record) => {
  try {
    await applicationAPI.delete(record.id)
    message.success('删除成功')
    loadApplications()
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

const exportData = async () => {
  exportLoading.value = true
  try {
    const response = await applicationAPI.export(searchForm)
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `保险申请数据_${new Date().toISOString().slice(0, 10)}.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 {
    exportLoading.value = false
  }
}

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

const getStatusText = (status) => {
  const texts = {
    pending: '待审核',
    initial_approved: '初审通过',
    under_review: '复审中',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return texts[status] || '未知'
}

const maskIdCard = (idCard) => {
  if (!idCard) return ''
  return idCard.replace(/(\d{6})\d{8}(\d{4})/, '$1********$2')
}

const maskPhone = (phone) => {
  if (!phone) return ''
  return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
}

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

<style scoped>
.application-management {
  padding: 24px;
}

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.action-buttons {
  margin-bottom: 16px;
}

.ant-table {
  background: white;
}

.ant-descriptions-item-label {
  font-weight: 500;
}
</style>