<template>
  <div class="policy-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.policy_number"
            placeholder="请输入保单号"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="投保人">
          <a-input
            v-model:value="searchForm.policyholder_name"
            placeholder="请输入投保人姓名"
            @pressEnter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="保险类型">
          <a-select
            v-model:value="searchForm.insurance_type_id"
            placeholder="请选择保险类型"
            style="width: 150px"
          >
            <a-select-option value="">全部类型</a-select-option>
            <a-select-option :value="1">综合意外险</a-select-option>
            <a-select-option :value="2">终身寿险</a-select-option>
            <a-select-option :value="3">健康医疗保险</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            style="width: 120px"
          >
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="active">有效</a-select-option>
            <a-select-option value="pending">待审核</a-select-option>
            <a-select-option value="expired">已过期</a-select-option>
            <a-select-option value="cancelled">已取消</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="policyList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'premium_amount'">
            <span>¥{{ record.premium_amount?.toLocaleString() }}</span>
          </template>
          <template v-else-if="column.key === 'coverage_amount'">
            <span>¥{{ record.coverage_amount?.toLocaleString() }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button size="small" @click="handleView(record)">查看</a-button>
              <a-button size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button
                size="small"
                :type="record.status === 'active' ? 'danger' : 'primary'"
                @click="handleToggleStatus(record)"
              >
                {{ record.status === 'active' ? '停用' : '启用' }}
              </a-button>
              <a-dropdown>
                <a-button size="small">更多</a-button>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleRenew(record)">续保</a-menu-item>
                    <a-menu-item @click="handleClaim(record)">理赔</a-menu-item>
                    <a-menu-item danger @click="handleDelete(record.id)">删除</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="currentPolicy"
        title="基本信息"
        bordered
        :column="2"
      >
        <a-descriptions-item label="保单号">{{ currentPolicy.policy_number }}</a-descriptions-item>
        <a-descriptions-item label="保险类型">{{ currentPolicy.insurance_type?.name || currentPolicy.insurance_type_name }}</a-descriptions-item>
        <a-descriptions-item label="投保人">{{ currentPolicy.policyholder_name }}</a-descriptions-item>
        <a-descriptions-item label="被保险人">{{ currentPolicy.insured_name }}</a-descriptions-item>
        <a-descriptions-item label="保费金额">¥{{ currentPolicy.premium_amount?.toLocaleString() }}</a-descriptions-item>
        <a-descriptions-item label="保额">¥{{ currentPolicy.coverage_amount?.toLocaleString() }}</a-descriptions-item>
        <a-descriptions-item label="保险期间">
          {{ currentPolicy.start_date }} 至 {{ currentPolicy.end_date }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(currentPolicy.status)">
            {{ getStatusText(currentPolicy.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间">{{ currentPolicy.created_at }}</a-descriptions-item>
        <a-descriptions-item label="最后更新">{{ currentPolicy.updated_at }}</a-descriptions-item>
      </a-descriptions>

      <a-divider />

      <a-descriptions
        title="联系信息"
        bordered
        :column="2"
      >
        <a-descriptions-item label="联系电话">{{ currentPolicy.phone }}</a-descriptions-item>
        <a-descriptions-item label="电子邮箱">{{ currentPolicy.email }}</a-descriptions-item>
        <a-descriptions-item label="联系地址" :span="2">
          {{ currentPolicy.address }}
        </a-descriptions-item>
      </a-descriptions>
    </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="policy_number">
              <a-input v-model:value="formState.policy_number" placeholder="请输入保单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保险类型" name="insurance_type_id">
              <a-select v-model:value="formState.insurance_type_id" placeholder="请选择保险类型">
                <a-select-option :value="1">综合意外险</a-select-option>
                <a-select-option :value="2">终身寿险</a-select-option>
                <a-select-option :value="3">健康医疗保险</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="customer_id">
              <a-select v-model:value="formState.customer_id" placeholder="请选择客户">
                <a-select-option :value="1">张三 (客户1)</a-select-option>
                <a-select-option :value="2">李四 (客户2)</a-select-option>
                <a-select-option :value="3">王五 (客户3)</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="关联申请" name="application_id">
              <a-select v-model:value="formState.application_id" placeholder="请选择关联申请">
                <a-select-option :value="1">申请001</a-select-option>
                <a-select-option :value="2">申请002</a-select-option>
                <a-select-option :value="3">申请003</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="policyholder_name">
              <a-input v-model:value="formState.policyholder_name" placeholder="请输入投保人姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="被保险人姓名" name="insured_name">
              <a-input v-model:value="formState.insured_name" placeholder="请输入被保险人姓名" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="保费金额" name="premium_amount">
              <a-input-number
                v-model:value="formState.premium_amount"
                :min="0"
                :step="100"
                style="width: 100%"
                placeholder="请输入保费金额"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保额" name="coverage_amount">
              <a-input-number
                v-model:value="formState.coverage_amount"
                :min="0"
                :step="1000"
                style="width: 100%"
                placeholder="请输入保额"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="保险开始日期" name="start_date">
              <a-date-picker
                v-model:value="formState.start_date"
                style="width: 100%"
                placeholder="请选择开始日期"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保险结束日期" name="end_date">
              <a-date-picker
                v-model:value="formState.end_date"
                style="width: 100%"
                placeholder="请选择结束日期"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-form-item label="状态" name="status">
          <a-select v-model:value="formState.status" placeholder="请选择状态">
            <a-select-option value="active">有效</a-select-option>
            <a-select-option value="pending">待审核</a-select-option>
            <a-select-option value="expired">已过期</a-select-option>
            <a-select-option value="cancelled">已取消</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="联系信息">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item name="phone">
                <a-input v-model:value="formState.phone" placeholder="联系电话" />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item name="email">
                <a-input v-model:value="formState.email" placeholder="电子邮箱" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-form-item name="address">
            <a-textarea
              v-model:value="formState.address"
              placeholder="联系地址"
              :rows="2"
            />
          </a-form-item>
        </a-form-item>

        <a-form-item label="备注" name="remarks">
          <a-textarea
            v-model:value="formState.remarks"
            placeholder="请输入备注信息"
            :rows="3"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

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

const loading = ref(false)
const modalVisible = ref(false)
const detailVisible = ref(false)
const editingId = ref(null)
const currentPolicy = ref(null)
const policyList = ref([])
const formRef = ref()

const searchForm = reactive({
  policy_number: '',
  policyholder_name: '',
  insurance_type_id: '',
  status: ''
})

const formState = reactive({
  policy_number: '',
  customer_id: null,
  application_id: null,
  insurance_type_id: null,
  policyholder_name: '',
  insured_name: '',
  premium_amount: null,
  coverage_amount: null,
  start_date: null,
  end_date: null,
  status: 'active',
  phone: '',
  email: '',
  address: '',
  remarks: ''
})

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

const columns = [
  {
    title: '保单号',
    dataIndex: 'policy_number',
    key: 'policy_number'
  },
  {
    title: '保险类型',
    dataIndex: 'insurance_type_name',
    key: 'insurance_type_name',
    customRender: ({ record }) => {
      return record.insurance_type?.name || record.insurance_type_name
    }
  },
  {
    title: '投保人',
    dataIndex: 'policyholder_name',
    key: 'policyholder_name'
  },
  {
    title: '被保险人',
    dataIndex: 'insured_name',
    key: 'insured_name'
  },
  {
    title: '保费金额',
    key: 'premium_amount',
    dataIndex: 'premium_amount'
  },
  {
    title: '保额',
    key: 'coverage_amount',
    dataIndex: 'coverage_amount'
  },
  {
    title: '保险期间',
    key: 'period',
    render: (_, record) => `${record.start_date} 至 ${record.end_date}`
  },
  {
    title: '状态',
    key: 'status',
    dataIndex: 'status'
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 250,
    fixed: 'right'
  }
]

const rules = {
  policy_number: [{ required: true, message: '请输入保单号' }],
  insurance_type_id: [{ required: true, message: '请选择保险类型' }],
  policyholder_name: [{ required: true, message: '请输入投保人姓名' }],
  insured_name: [{ required: true, message: '请输入被保险人姓名' }],
  premium_amount: [{ required: true, message: '请输入保费金额' }],
  coverage_amount: [{ required: true, message: '请输入保额' }],
  start_date: [{ required: true, message: '请选择开始日期' }],
  end_date: [{ required: true, message: '请选择结束日期' }],
  status: [{ required: true, message: '请选择状态' }]
}

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

const getStatusColor = (status) => {
  const colors = {
    active: 'green',
    pending: 'orange',
    expired: 'default',
    cancelled: 'red'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    active: '有效',
    pending: '待审核',
    expired: '已过期',
    cancelled: '已取消'
  }
  return texts[status] || '未知'
}

const loadPolicies = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    console.log('保单管理API请求参数:', params)
    const response = await policyAPI.getList(params)
    console.log('保单管理API响应:', response)
    console.log('响应数据类型:', typeof response)
    console.log('响应data字段:', response.data)
    console.log('响应data.status:', response.data?.status)
    console.log('响应data.data:', response.data?.data)
    console.log('响应data.data长度:', response.data?.data?.length)
    
    if (response.data && response.data.status === 'success') {
      // 后端返回的数据直接是数组格式，不是{list: [], total: 28}格式
      policyList.value = response.data.data || []
      pagination.total = response.data.pagination?.total || 0
      console.log('保单管理数据设置成功:', policyList.value.length, '条')
      console.log('policyList.value:', policyList.value)
    } else {
      console.log('保单管理响应格式错误:', response)
      message.error(response.data?.message || '加载保单列表失败')
      policyList.value = []
    }
  } catch (error) {
    message.error('加载保单列表失败')
  } finally {
    loading.value = false
  }
}

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

const resetSearch = () => {
  searchForm.policy_number = ''
  searchForm.policyholder_name = ''
  searchForm.insurance_type_id = ''
  searchForm.status = ''
  handleSearch()
}

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

const showModal = () => {
  editingId.value = null
  Object.assign(formState, {
    policy_number: '',
    insurance_type_id: null,
    policyholder_name: '',
    insured_name: '',
    premium_amount: null,
    coverage_amount: null,
    start_date: null,
    end_date: null,
    status: 'active',
    phone: '',
    email: '',
    address: '',
    remarks: ''
  })
  modalVisible.value = true
}

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

const handleEdit = (record) => {
  editingId.value = record.id
  Object.assign(formState, {
    policy_number: record.policy_number,
    insurance_type_id: record.insurance_type_id,
    policyholder_name: record.policyholder_name,
    insured_name: record.insured_name,
    premium_amount: record.premium_amount,
    coverage_amount: record.coverage_amount,
    start_date: record.start_date ? dayjs(record.start_date) : null,
    end_date: record.end_date ? dayjs(record.end_date) : null,
    status: record.status,
    phone: record.phone,
    email: record.email,
    address: record.address,
    remarks: record.remarks
  })
  modalVisible.value = true
}

const handleModalOk = async () => {
  try {
    await formRef.value.validate()
    
    // 准备提交数据，格式化日期
    const submitData = { ...formState }
    if (submitData.start_date) {
      submitData.start_date = submitData.start_date.format('YYYY-MM-DD')
    }
    if (submitData.end_date) {
      submitData.end_date = submitData.end_date.format('YYYY-MM-DD')
    }
    
    if (editingId.value) {
      await policyAPI.update(editingId.value, submitData)
      message.success('保单更新成功')
    } else {
      await policyAPI.create(submitData)
      message.success('保单创建成功')
    }
    
    modalVisible.value = false
    loadPolicies()
  } catch (error) {
    if (error.errorFields) {
      console.log('表单验证失败', error)
    } else {
      message.error(editingId.value ? '保单更新失败' : '保单创建失败')
      console.error('API调用失败:', error)
    }
  }
}

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

const handleToggleStatus = async (record) => {
  try {
    const newStatus = record.status === 'active' ? 'cancelled' : 'active'
    await policyAPI.update(record.id, { status: newStatus })
    message.success('状态更新成功')
    loadPolicies()
  } catch (error) {
    message.error('状态更新失败')
    console.error('状态更新失败:', error)
  }
}

const handleRenew = async (record) => {
  message.info('续保功能开发中')
}

const handleClaim = async (record) => {
  message.info('理赔功能开发中')
}

const handleDelete = async (id) => {
  Modal.confirm({
    title: '确认删除',
    content: '确定要删除这个保单吗？此操作不可恢复。',
    okText: '确定',
    cancelText: '取消',
    okType: 'danger',
    onOk: async () => {
      try {
        await policyAPI.delete(id)
        message.success('保单删除成功')
        loadPolicies()
      } catch (error) {
        message.error('保单删除失败')
        console.error('删除失败:', error)
      }
    }
  })
}

const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      policy_number: searchForm.policy_number || undefined,
      policyholder_name: searchForm.policyholder_name || undefined,
      insurance_type_id: searchForm.insurance_type_id || undefined,
      status: searchForm.status || undefined
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await policyAPI.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(() => {
  loadPolicies()
})
</script>

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