<template>
  <div class="insurance-type-management">
    <a-page-header
      title="险种管理"
      sub-title="管理系统支持的保险产品险种"
    >
      <template #extra>
        <a-space>
          <a-button @click="handleExport">
            <DownloadOutlined />
            导出Excel
          </a-button>
          <a-button type="primary" @click="showModal">
            <PlusOutlined />
            新增险种
          </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.name"
            placeholder="请输入险种名称"
            @pressEnter="handleSearch"
            @input="handleSearchInput"
            allowClear
          />
        </a-form-item>

        <a-form-item>
          <a-button type="primary" @click="handleSearch">
            <SearchOutlined />
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="resetSearch">
            <RedoOutlined />
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 险种表格 -->
    <a-card style="margin-top: 16px">
      <a-table
        :columns="columns"
        :data-source="typeList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 1500 }"
        :rowKey="getRowKey"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'on_sale_status'">
            <a-switch 
              :key="'on_sale_status-' + (record._key ?? record.id ?? '')"
              :checked="!!record.on_sale_status" 
              @change="(checked) => handleToggleOnSaleStatus(record, checked)"
              checked-children="在售"
              un-checked-children="停售"
            />
          </template>
          <template v-else-if="column.key === 'applicable_livestock'">
            <span :key="'applicable_livestock-' + (record._key ?? record.id ?? '')">{{ formatApplicableLivestock(record.applicable_livestock) }}</span>
          </template>
          <template v-else-if="column.key === 'coverage_amount'">
            <span :key="'coverage_amount-' + (record._key ?? record.id ?? '')">{{ formatCoverageAmount(record.coverage_amount_min, record.coverage_amount_max) }}</span>
          </template>
          <template v-else-if="column.key === 'insurance_term'">
            <span :key="'insurance_term-' + (record._key ?? record.id ?? '')">{{ record.insurance_term ? `${record.insurance_term}个月` : '-' }}</span>
          </template>
          <template v-else-if="column.key === 'created_at'">
            <span :key="'created_at-' + (record._key ?? record.id ?? '')">{{ record.created_at ? formatDate(record.created_at) : '-' }}</span>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space :key="'action-' + (record._key ?? record.id ?? '')">
              <a-button size="small" @click="handleEdit(record)">编辑</a-button>
              <a-button size="small" @click="handleView(record)">详情</a-button>
              <a-popconfirm
                title="确定要删除这个险种吗？"
                @confirm="handleDelete(record.id)"
              >
                <a-button size="small" danger>删除</a-button>
              </a-popconfirm>
            </a-space>
          </template>
          <template v-else>
            <span :key="'default-' + (column.key || column.dataIndex || '') + '-' + (record._key ?? record.id ?? '')">{{ getDefaultCellText(column, record) }}</span>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑模态框 -->
    <a-modal
      :open="modalVisible"
      @update:open="modalVisible = $event"
      :title="isEdit ? '编辑险种' : '新增险种'"
      :ok-text="isEdit ? '更新' : '创建'"
      cancel-text="取消"
      :confirmLoading="submitLoading"
      @ok="handleSubmit"
      @cancel="handleCancel"
      width="1000px"
      :destroyOnClose="true"
    >
      <a-form
        ref="formRef"
        :model="formState"
        :rules="rules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="险种名称" name="name">
              <a-input 
                v-model:value="formState.name" 
                placeholder="请输入险种名称"
                @input="handleNameInput"
                @focus="handleNameFocus"
                @blur="handleNameBlur"
                @change="handleNameChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="适用生资" name="applicable_livestock">
              <a-select
                v-model:value="formState.applicable_livestock"
                placeholder="请选择适用生资"
                style="width: 100%"
                mode="multiple"
                :max-tag-count="3"
                @change="handleLivestockChange"
                @focus="handleLivestockFocus"
                @blur="handleLivestockBlur"
              >
                <a-select-option value="牛">牛</a-select-option>
                <a-select-option value="羊">羊</a-select-option>
                <a-select-option value="猪">猪</a-select-option>
                <a-select-option value="鸡">鸡</a-select-option>
                <a-select-option value="鸭">鸭</a-select-option>
                <a-select-option value="鹅">鹅</a-select-option>
                <a-select-option value="马">马</a-select-option>
                <a-select-option value="驴">驴</a-select-option>
                <a-select-option value="兔">兔</a-select-option>
                <a-select-option value="鱼">鱼</a-select-option>
                <a-select-option value="虾">虾</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="保险期限/月" name="insurance_term">
              <a-select
                v-model:value="formState.insurance_term"
                placeholder="请选择保险期限"
                style="width: 100%"
                @change="handleInsuranceTermChange"
                @focus="handleInsuranceTermFocus"
                @blur="handleInsuranceTermBlur"
              >
                <a-select-option :value="1">1个月</a-select-option>
                <a-select-option :value="3">3个月</a-select-option>
                <a-select-option :value="6">6个月</a-select-option>
                <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-col>
          <a-col :span="8">
            <a-form-item label="服务区域" name="description">
              <a-input 
                v-model:value="formState.description" 
                placeholder="请输入服务区域"
                @input="handleDescriptionInput"
                @focus="handleDescriptionFocus"
                @blur="handleDescriptionBlur"
                @change="handleDescriptionChange"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="保单形式" name="policy_form">
              <a-select
                v-model:value="formState.policy_form"
                placeholder="请选择保单形式"
                style="width: 100%"
                @change="handlePolicyFormChange"
                @focus="handlePolicyFormFocus"
                @blur="handlePolicyFormBlur"
              >
                <a-select-option value="电子保单">电子保单</a-select-option>
                <a-select-option value="纸质保单">纸质保单</a-select-option>
                <a-select-option value="电子保单+纸质保单">电子保单+纸质保单</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="保险额度" name="coverage_amount">
              <a-input-group compact>
                <a-input-number
                  v-model:value="formState.coverage_amount_min"
                  placeholder="最低额度"
                  :min="0"
                  :precision="2"
                  style="width: 45%"
                  @change="handleCoverageMinChange"
                  @focus="handleCoverageMinFocus"
                  @blur="handleCoverageMinBlur"
                />
                <a-input
                  style="width: 10%; text-align: center; pointer-events: none"
                  placeholder="~"
                  disabled
                />
                <a-input-number
                  v-model:value="formState.coverage_amount_max"
                  placeholder="最高额度"
                  :min="0"
                  :precision="2"
                  style="width: 45%"
                  @change="handleCoverageMaxChange"
                  @focus="handleCoverageMaxFocus"
                  @blur="handleCoverageMaxBlur"
                />
              </a-input-group>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="添加时间" name="created_at">
              <a-date-picker
                v-model:value="formState.created_at"
                placeholder="请选择添加时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                show-time
                @change="handleCreatedAtChange"
                @focus="handleCreatedAtFocus"
                @blur="handleCreatedAtBlur"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="在售状态" name="on_sale_status">
              <a-switch
                v-model:checked="formState.on_sale_status"
                checked-children="在售"
                un-checked-children="停售"
                @change="handleOnSaleStatusChange"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="保费费率" name="premium_rate">
              <a-input-number
                v-model:value="formState.premium_rate"
                placeholder="请输入费率（0-1之间）"
                :min="0"
                :max="1"
                :precision="4"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-modal>

    <!-- 详情查看模态框 -->
    <a-modal
      :open="detailVisible"
      @update:open="detailVisible = $event"
      title="险种详情"
      :footer="null"
      width="800px"
      :destroyOnClose="true"
    >
      <a-descriptions :column="2" bordered>
        <a-descriptions-item label="险种名称">
          {{ currentDetail.name || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="适用生资">
          {{ formatApplicableLivestock(currentDetail.applicable_livestock) }}
        </a-descriptions-item>
        <a-descriptions-item label="保险期限">
          {{ currentDetail.insurance_term ? `${currentDetail.insurance_term}个月` : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="服务区域">
          {{ currentDetail.description || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="保单形式">
          {{ currentDetail.policy_form || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="保险额度">
          {{ formatCoverageAmount(currentDetail.coverage_amount_min, currentDetail.coverage_amount_max) }}
        </a-descriptions-item>
        <a-descriptions-item label="添加时间">
          {{ currentDetail.created_at ? formatDate(currentDetail.created_at) : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="在售状态">
          <a-tag :color="currentDetail.on_sale_status ? 'green' : 'red'">
            {{ currentDetail.on_sale_status ? '在售' : '停售' }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="最后更新时间" :span="2">
          {{ currentDetail.updated_at ? formatDate(currentDetail.updated_at) : '-' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

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

const loading = ref(false)
const modalVisible = ref(false)
const detailVisible = ref(false)
const isEdit = ref(false)
const submitLoading = ref(false)
const typeList = ref([])
const formRef = ref()
const currentDetail = ref({})
const searchTimeout = ref(null)

const searchForm = reactive({
  name: ''
})

const formState = reactive({
  id: null,
  name: '',
  applicable_livestock: [],
  insurance_term: null,
  description: '',
  policy_form: '',
  coverage_amount_min: null,
  coverage_amount_max: null,
  created_at: null,
  on_sale_status: true
})

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

const columns = [
  {
    title: '险种名称',
    dataIndex: 'name',
    key: 'name',
    width: 150,
    fixed: 'left'
  },
  {
    title: '适用生资',
    dataIndex: 'applicable_livestock',
    key: 'applicable_livestock',
    width: 120
  },
  {
    title: '保险期限/月',
    dataIndex: 'insurance_term',
    key: 'insurance_term',
    width: 120,
    sorter: true
  },
  {
    title: '服务区域',
    dataIndex: 'description',
    key: 'description',
    width: 200
  },
  {
    title: '保单形式',
    dataIndex: 'policy_form',
    key: 'policy_form',
    width: 150,
    filters: [
      { text: '电子保单', value: '电子保单' },
      { text: '纸质保单', value: '纸质保单' },
      { text: '电子保单+纸质保单', value: '电子保单+纸质保单' }
    ]
  },
  {
    title: '保险额度',
    dataIndex: 'coverage_amount',
    key: 'coverage_amount',
    width: 150
  },
  {
    title: '添加时间',
    dataIndex: 'created_at',
    key: 'created_at',
    width: 180,
    sorter: true
  },
  {
    title: '在售状态',
    dataIndex: 'on_sale_status',
    key: 'on_sale_status',
    width: 100
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

const rules = {
  name: [
    { required: true, message: '请输入险种名称' },
    { type: 'string', min: 1, max: 100, message: '险种名称长度需在1-100个字符' }
  ],
  applicable_livestock: [
    { required: true, message: '请输入适用生资' },
    {
      validator: (_, value) => {
        if (Array.isArray(value) && value.length > 0) {
          const mergedLength = value.join(',').length
          if (mergedLength > 100) {
            return Promise.reject('适用生资选项合并后长度超过100字符（数据库varchar(100)）')
          }
          return Promise.resolve()
        }
        return Promise.reject('至少选择一个适用生资')
      }
    }
  ],
  insurance_term: [
    { required: true, message: '请输入保险期限' },
    {
      validator: (_, value) => {
        if (value == null || value === '') return Promise.reject('保险期限不能为空')
        const num = Number(value)
        if (!Number.isInteger(num) || num <= 0) return Promise.reject('保险期限必须为大于0的整数（月）')
        return Promise.resolve()
      }
    }
  ],
  description: [{ required: true, message: '请输入服务区域' }],
  policy_form: [{ required: true, message: '请选择保单形式' }],
  coverage_amount_min: [
    { required: true, message: '请输入最低保险额度' },
    {
      validator: (_, value) => {
        if (value == null || value === '') return Promise.reject('最低保险额度不能为空')
        const num = Number(value)
        if (Number.isNaN(num) || num < 0) return Promise.reject('最低保险额度必须为非负数')
        // 近似校验 decimal(15,2) 的位数限制（不做过度严格校验）
        const [intPart, decPart = ''] = String(Math.abs(num)).split('.')
        if (intPart.length > 15 || decPart.length > 2) return Promise.reject('最低保险额度最多15位整数且保留2位小数')
        return Promise.resolve()
      }
    }
  ],
  coverage_amount_max: [
    { required: true, message: '请输入最高保险额度' },
    {
      validator: (_, value) => {
        if (value == null || value === '') return Promise.reject('最高保险额度不能为空')
        const num = Number(value)
        if (Number.isNaN(num) || num < 0) return Promise.reject('最高保险额度必须为非负数')
        if (formState.coverage_amount_min != null && num < Number(formState.coverage_amount_min)) return Promise.reject('最高额度必须不小于最低额度')
        const [intPart, decPart = ''] = String(Math.abs(num)).split('.')
        if (intPart.length > 15 || decPart.length > 2) return Promise.reject('最高保险额度最多15位整数且保留2位小数')
        return Promise.resolve()
      }
    }
  ],
  premium_rate: [
    { required: true, message: '请输入保费费率' },
    {
      validator: (_, value) => {
        if (value == null || value === '') return Promise.reject('保费费率不能为空')
        const num = Number(value)
        if (Number.isNaN(num)) return Promise.reject('保费费率必须为数字')
        if (num < 0 || num > 1) return Promise.reject('保费费率必须在0~1之间')
        const scaled = Math.round(num * 10000) / 10000
        // 容忍浮点误差：使用近似比较
        if (Math.abs(scaled - num) > 1e-8) return Promise.reject('保费费率最多保留4位小数（decimal(5,4)）')
        return Promise.resolve()
      }
    }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 格式化保险额度
const formatCoverageAmount = (min, max) => {
  if (!min && !max) return '-'
  if (min && max) {
    return `${min}~${max}元`
  }
  if (min) return `${min}元以上`
  if (max) return `${max}元以下`
  return '-'
}

// 格式化适用生资
const formatApplicableLivestock = (livestock) => {
  if (!livestock) return '-'
  if (Array.isArray(livestock)) {
    return livestock.join('、')
  }
  if (typeof livestock === 'string') {
    // 如果是字符串，尝试解析为数组
    try {
      const parsed = JSON.parse(livestock)
      if (Array.isArray(parsed)) {
        return parsed.join('、')
      }
    } catch (e) {
      // 如果解析失败，按逗号分割
      return livestock.split(',').join('、')
    }
  }
  return livestock.toString()
}

// 通用单元格文本获取，避免渲染空 vnode
const getDefaultCellText = (column, record) => {
  if (!column || !record) return '-'
  const key = column.dataIndex || column.key
  let val = key && record ? record[key] : undefined
  if (val === null || val === undefined) return '-'
  if (Array.isArray(val)) return val.join('、')
  if (typeof val === 'object') return JSON.stringify(val)
  return String(val)
}

// 统一行 key 获取，确保稳定且唯一，避免 diff 异常
const getRowKey = (record) => {
  if (!record) return `row-${Math.random().toString(36).slice(2)}`
  return record._key ?? record.id ?? `${record.name || ''}-${record.created_at || ''}-${record.coverage_amount_min ?? ''}-${record.coverage_amount_max ?? ''}`
}

const loadInsuranceTypes = async () => {
  // 检查组件是否仍然挂载
  if (!isComponentMounted.value) {
    console.warn('组件已卸载，取消加载操作')
    return
  }
  
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    const response = await insuranceTypeAPI.getList(params)
    console.log('险种管理API响应:', response)
    
    // 再次检查组件是否仍然挂载
    if (!isComponentMounted.value) {
      console.warn('组件已卸载，取消数据更新')
      return
    }
    
    if (response.data && response.data.status === 'success') {
      // API返回的数据直接是数组格式
      let dataList = response.data.data || []
      // 过滤掉异常项，避免渲染阶段出现 null/undefined 导致的 patch 错误
      dataList = dataList.filter(item => item && typeof item === 'object')
      // 中文名称精确查询：当关键词包含中文时，前端执行精确匹配过滤
      if (searchForm.name && /[\u4e00-\u9fa5]/.test(searchForm.name)) {
        const keyword = searchForm.name.trim()
        dataList = dataList.filter(item => (item.name || '').trim() === keyword)
      }
      // 注入稳定且唯一的 _key，避免重复 key 导致的 diff 异常
      typeList.value = dataList.map((item, idx) => ({
        ...item,
        _key: item.id ?? `${item.name || ''}-${item.created_at || ''}-${item.coverage_amount_min ?? ''}-${item.coverage_amount_max ?? ''}-${idx}`
      }))
      pagination.total = response.data.pagination?.total || dataList.length
      console.log('险种管理数据设置成功:', typeList.value.length, '个')
    } else {
      console.log('险种管理响应格式错误:', response)
      if (isComponentMounted.value) {
        message.error(response.data?.message || '加载险种列表失败')
      }
    }
  } catch (error) {
    if (isComponentMounted.value) {
      message.error('加载险种列表失败')
    }
    console.error('Error loading insurance types:', error)
  } finally {
    if (isComponentMounted.value) {
      loading.value = false
    }
  }
}

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

// 搜索输入监听事件，实现实时精确查询（中文优先精确匹配）
const handleSearchInput = () => {
  // 防抖处理，避免频繁请求
  clearTimeout(searchTimeout.value)
  searchTimeout.value = setTimeout(() => {
    handleSearch()
  }, 500)
}

const resetSearch = () => {
  Object.assign(searchForm, {
    name: ''
  })
  handleSearch()
}

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

const showModal = () => {
  isEdit.value = false
  Object.assign(formState, {
    id: null,
    name: '',
    applicable_livestock: [],
    insurance_term: null,
    description: '',
    policy_form: '',
    coverage_amount_min: undefined,
    coverage_amount_max: undefined,
    created_at: null,
    on_sale_status: true,
    premium_rate: undefined
  })
  modalVisible.value = true
}

const handleEdit = (record) => {
  isEdit.value = true
  
  // 处理 applicable_livestock 数据类型
  let applicableLivestock = []
  if (record.applicable_livestock) {
    if (Array.isArray(record.applicable_livestock)) {
      applicableLivestock = record.applicable_livestock
    } else if (typeof record.applicable_livestock === 'string') {
      try {
        applicableLivestock = JSON.parse(record.applicable_livestock)
      } catch (e) {
        applicableLivestock = record.applicable_livestock.split(',').map(item => item.trim())
      }
    }
  }
  
  Object.assign(formState, {
    id: record.id,
    name: record.name,
    applicable_livestock: applicableLivestock,
    // 确保数值类型正确
    insurance_term: record.insurance_term != null ? Number(record.insurance_term) : null,
    description: record.description,
    policy_form: record.policy_form,
    coverage_amount_min: record.coverage_amount_min != null ? Number(record.coverage_amount_min) : undefined,
    coverage_amount_max: record.coverage_amount_max != null ? Number(record.coverage_amount_max) : undefined,
    created_at: record.created_at ? dayjs(record.created_at) : null,
    on_sale_status: !!record.on_sale_status,
    premium_rate: record.premium_rate != null ? Number(record.premium_rate) : undefined
  })
  modalVisible.value = true
}

const handleView = (record) => {
  // 设置详情数据
  currentDetail.value = { ...record }
  detailVisible.value = true
}

const handleSubmit = async () => {
  try {
    // 检查组件是否仍然挂载
    if (!isComponentMounted.value) {
      console.warn('组件已卸载，取消提交操作')
      return
    }
    
    submitLoading.value = true
    
    // 检查表单引用是否存在
    if (!formRef.value) {
      console.warn('表单引用不存在，组件可能已卸载')
      return
    }
    
    await formRef.value.validate()
    await nextTick()

    const submitData = {
      id: formState.id,
      name: formState.name ? formState.name.trim() : '',
      applicable_livestock: Array.isArray(formState.applicable_livestock)
        ? formState.applicable_livestock.join(',')
        : formState.applicable_livestock,
      insurance_term: formState.insurance_term != null ? Number(formState.insurance_term) : null,
      description: formState.description,
      policy_form: formState.policy_form,
      coverage_amount_min: formState.coverage_amount_min != null ? Number(formState.coverage_amount_min) : null,
      coverage_amount_max: formState.coverage_amount_max != null ? Number(formState.coverage_amount_max) : null,
      created_at: formState.created_at
        ? (typeof formState.created_at === 'string'
          ? formState.created_at
          : formState.created_at.format('YYYY-MM-DD HH:mm:ss'))
        : null,
      on_sale_status: !!formState.on_sale_status,
      premium_rate: formState.premium_rate != null ? Number(formState.premium_rate) : null
    }

    // 📤 前端请求数据日志
    console.log('=== 前端发送请求数据 ===')
    console.log('请求类型:', isEdit.value ? 'UPDATE' : 'CREATE')
    console.log('原始表单数据 (formState):', JSON.stringify({
      ...formState,
      created_at: formState.created_at && typeof formState.created_at !== 'string' ? formState.created_at.format('YYYY-MM-DD HH:mm:ss') : formState.created_at
    }, null, 2))
    console.log('处理后提交数据 (submitData):', JSON.stringify(submitData, null, 2))
    console.log('请求时间:', new Date().toLocaleString())
    console.log('请求URL:', isEdit.value ? `/api/insurance-types/${formState.id}` : '/api/insurance-types')
    console.log('========================')

    if (isEdit.value) {
      console.log('🔄 发起更新请求...')
      const response = await insuranceTypeAPI.update(formState.id, submitData)

      // 📥 前端接收响应数据 (UPDATE)
      console.log('=== 前端接收响应数据 (UPDATE) ===')
      console.log('响应状态:', response.status)
      console.log('响应数据:', JSON.stringify(response, null, 2))
      console.log('响应时间:', new Date().toLocaleString())
      console.log('================================')

      if (response.data && response.data.status === 'success') {
        message.success(response.data.message || '险种更新成功')
      } else {
        message.error(response.data?.message || '险种更新失败')
      }
    } else {
      console.log('➕ 发起创建请求...')
      const response = await insuranceTypeAPI.create(submitData)

      // 📥 前端接收响应数据 (CREATE)
      console.log('=== 前端接收响应数据 (CREATE) ===')
      console.log('响应状态:', response.status)
      console.log('响应数据:', JSON.stringify(response, null, 2))
      console.log('响应时间:', new Date().toLocaleString())
      console.log('================================')

      if (response.data && response.data.status === 'success') {
        message.success(response.data.message || '险种创建成功')
      } else {
        message.error(response.data?.message || '险种创建失败')
      }
    }

    // 刷新列表并关闭弹窗
    // await loadInsuranceTypes()
    // modalVisible.value = false
    // 检查组件是否仍然挂载再执行UI更新
    if (modalVisible.value !== undefined) {
      modalVisible.value = false
    }
    await nextTick()
    await loadInsuranceTypes()
  } catch (error) {
    // 🚨 前端错误日志
    console.log('=== 前端请求错误日志 ===')
    console.log('错误类型:', error.name)
    console.log('错误信息:', error.message)
    console.log('错误详情:', error)
    if (error.response) {
      console.log('错误响应状态:', error.response.status)
      console.log('错误响应数据:', error.response.data)
    }
    console.log('错误时间:', new Date().toLocaleString())
    console.log('=====================')
    
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      console.log('表单验证失败', error)
    }
  } finally {
    // 安全地重置loading状态，检查组件是否仍然挂载
    if (submitLoading.value !== undefined) {
      submitLoading.value = false
    }
  }
}

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

const handleToggleOnSaleStatus = async (record, checked) => {
  try {
    // 检查组件是否仍然挂载
    if (!isComponentMounted.value) {
      console.warn('组件已卸载，取消状态更新操作')
      return
    }
    
    const response = await insuranceTypeAPI.updateStatus(record.id, {
      on_sale_status: checked
    })
    
    // 再次检查组件是否仍然挂载
    if (!isComponentMounted.value) {
      console.warn('组件已卸载，取消UI更新')
      return
    }
    
    if (response.data && response.data.status === 'success') {
      message.success('在售状态更新成功')
      loadInsuranceTypes()
    } else {
      message.error(response.data?.message || '在售状态更新失败')
    }
  } catch (error) {
    if (isComponentMounted.value) {
      message.error('在售状态更新失败')
    }
    console.error('Error updating on sale status:', error)
  }
}

const handleDelete = async (id) => {
  try {
    // 检查组件是否仍然挂载
    if (!isComponentMounted.value) {
      console.warn('组件已卸载，取消删除操作')
      return
    }
    
    const response = await insuranceTypeAPI.delete(id)
    
    // 再次检查组件是否仍然挂载
    if (!isComponentMounted.value) {
      console.warn('组件已卸载，取消UI更新')
      return
    }
    
    if (response.data && response.data.status === 'success') {
      message.success('险种删除成功')
      loadInsuranceTypes()
    } else {
      message.error(response.data?.message || '险种删除失败')
    }
  } catch (error) {
    if (isComponentMounted.value) {
      message.error('险种删除失败')
    }
    console.error('Error deleting insurance type:', error)
  }
}

// 险种名称输入框事件监听器
const handleNameInput = (e) => {
  console.log('险种名称输入中:', e.target.value)
  const value = e.target.value
  
  // 实时验证险种名称长度（数据库 varchar(100)）
  if (value.length > 100) {
    message.warning('险种名称不能超过100个字符')
    // 截断超长内容
    e.target.value = value.substring(0, 100)
    formState.name = e.target.value
  }
  
  // 检查特殊字符
  const invalidChars = /[<>'"&]/g
  if (invalidChars.test(value)) {
    message.warning('险种名称不能包含特殊字符 < > \' " &')
  }
  
  // 实时更新字符计数提示
  if (value.length > 80) {
    message.info(`还可输入 ${100 - value.length} 个字符`)
  }
}

const handleNameFocus = () => {
  console.log('险种名称输入框获得焦点')
  // 显示输入提示
  message.info('请输入简洁明确的险种名称，建议10-30个字符')
}

const handleNameBlur = () => {
  console.log('险种名称输入框失去焦点')
  // 失去焦点时验证是否为空
  if (!formState.name.trim()) {
    message.warning('请输入险种名称')
    return
  }
  
  // 检查是否与现有险种重名
  const existingNames = typeList.value.map(item => item.name.toLowerCase())
  if (existingNames.includes(formState.name.toLowerCase()) && !isEdit.value) {
    message.error('该险种名称已存在，请使用其他名称')
  }
}

const handleNameChange = (e) => {
  console.log('险种名称变更:', e.target.value)
  // 自动去除首尾空格并格式化
  const formatted = e.target.value.trim().replace(/\s+/g, ' ')
  formState.name = formatted
  
  // 自动首字母大写（如果是英文）
  if (/^[a-zA-Z]/.test(formatted)) {
    formState.name = formatted.charAt(0).toUpperCase() + formatted.slice(1)
  }
}

// 适用生资选择框事件监听器
const handleLivestockChange = (value) => {
  console.log('适用生资变更:', value)
  
  if (value.length > 5) {
    message.warning('建议选择不超过5种生资类型，过多选择可能影响风险评估')
  } else if (value.length === 0) {
    message.warning('请至少选择一种适用生资')
  }
  
  // 根据选择的生资类型给出建议
  if (value.includes('牛') && value.includes('羊')) {
    message.info('牛羊混合保险建议设置差异化保费')
  }
  
  // 自动调整保险额度建议
  if (value.includes('牛') && !value.includes('羊')) {
    message.info('牛类保险建议保额范围：5000-50000元')
  } else if (value.includes('羊') && !value.includes('牛')) {
    message.info('羊类保险建议保额范围：1000-10000元')
  }
}

const handleLivestockFocus = () => {
  console.log('适用生资选择框获得焦点')
  message.info('请选择该险种适用的生资类型，可多选')
}

const handleLivestockBlur = () => {
  console.log('适用生资选择框失去焦点')
  if (!formState.applicable_livestock || formState.applicable_livestock.length === 0) {
    message.error('请选择至少一种适用生资')
  } else {
    message.success(`已选择 ${formState.applicable_livestock.length} 种生资类型`)
  }
}

// 保险期限选择框事件监听器
const handleInsuranceTermChange = (value) => {
  console.log('保险期限变更:', value)
  
  // 根据保险期限给出专业建议
  if (value >= 24) {
    message.info('长期保险(≥24个月)建议设置更优惠的费率，提高竞争力')
  } else if (value >= 12) {
    message.info('中期保险(12-23个月)适合大多数养殖周期')
  } else if (value >= 6) {
    message.info('短期保险(6-11个月)适合季节性养殖')
  } else if (value > 0) {
    message.warning('保险期限过短(≤6个月)可能影响保障效果')
  }
  
  // 自动调整保费建议
  if (value >= 12) {
    message.info('建议设置年度保费优惠政策')
  }
}

const handleInsuranceTermFocus = () => {
  console.log('保险期限选择框获得焦点')
  message.info('请选择保险期限，建议根据生资养殖周期设定')
}

const handleInsuranceTermBlur = () => {
  console.log('保险期限选择框失去焦点')
  if (!formState.insurance_term || formState.insurance_term <= 0) {
    message.error('请选择有效的保险期限')
  }
}

// 服务区域输入框事件监听器
const handleDescriptionInput = (e) => {
  console.log('服务区域输入中:', e.target.value)
  const value = e.target.value
  
  // 实时验证长度
  if (value.length > 200) {
    message.warning('服务区域描述不能超过200个字符')
    e.target.value = value.substring(0, 200)
    formState.description = e.target.value
  }
  
  // 智能识别区域关键词
  const regions = ['全国', '省', '市', '县', '区', '乡', '镇', '村']
  const hasRegion = regions.some(region => value.includes(region))
  if (value.length > 5 && !hasRegion) {
    message.info('建议明确服务区域范围，如：全国、某省、某市等')
  }
}

const handleDescriptionFocus = () => {
  console.log('服务区域输入框获得焦点')
  message.info('请输入服务区域，如：全国、宁夏回族自治区、银川市等')
}

const handleDescriptionBlur = () => {
  console.log('服务区域输入框失去焦点')
  if (!formState.description.trim()) {
    message.error('请输入服务区域')
    return
  }
  
  // 验证区域格式
  const commonRegions = ['全国', '华北', '华南', '华东', '华西', '东北', '西北', '西南']
  const isCommonRegion = commonRegions.some(region => formState.description.includes(region))
  if (isCommonRegion) {
    message.success('服务区域设置完成')
  }
}

const handleDescriptionChange = (e) => {
  console.log('服务区域变更:', e.target.value)
  // 自动格式化和去除多余空格
  const formatted = e.target.value.trim().replace(/\s+/g, ' ')
  formState.description = formatted
  
  // 自动补全常见区域后缀
  if (formatted.endsWith('省') || formatted.endsWith('市') || formatted.endsWith('区')) {
    message.info('区域格式正确')
  }
}

// 保单形式选择框事件监听器
const handlePolicyFormChange = (value) => {
  console.log('保单形式变更:', value)
  
  // 根据保单形式给出详细提示和建议
  if (value === '纸质保单') {
    message.warning('纸质保单需要额外的邮寄成本和时间，建议评估必要性')
  } else if (value === '电子保单') {
    message.success('电子保单环保便捷，支持即时生成和发送')
  } else if (value === '混合保单') {
    message.info('混合保单可满足不同客户需求，但管理成本较高')
  }
  
  // 根据保单形式调整处理时效提示
  if (value === '电子保单') {
    message.info('电子保单可实现即时出单，提升客户体验')
  } else {
    message.info('请预留足够的保单制作和配送时间')
  }
}

const handlePolicyFormFocus = () => {
  console.log('保单形式选择框获得焦点')
  message.info('请选择保单形式，建议优先选择电子保单')
}

const handlePolicyFormBlur = () => {
  console.log('保单形式选择框失去焦点')
  if (!formState.policy_form) {
    message.error('请选择保单形式')
  }
}

// 保险额度最低值事件监听器
const lastCoverageMinListened = ref(null)
const lastCoverageMaxListened = ref(null)

const handleCoverageMinChange = (value) => {
  console.log('最低保险额度变更:', value)
  lastCoverageMinListened.value = value
  
  // 验证最低额度不能大于最高额度
  if (value && formState.coverage_amount_max && value > formState.coverage_amount_max) {
    message.warning('最低额度不能大于最高额度，已自动调整')
    formState.coverage_amount_min = formState.coverage_amount_max
    return
  }
  
  // 验证最低额度合理性
  if (value < 100) {
    message.warning('最低保险额度建议不少于100元')
  } else if (value > 100000) {
    message.warning('最低保险额度过高，请确认是否合理')
  }
  
  // 智能建议最高额度
  if (value && !formState.coverage_amount_max) {
    const suggestedMax = Math.round(value * 10)
    message.info(`建议最高额度设置为：${suggestedMax.toLocaleString()}元`)
  }
}

const handleCoverageMinFocus = () => {
  console.log('最低保险额度输入框获得焦点')
  message.info('请输入最低保险额度，建议根据生资最低价值设定')
}

const handleCoverageMinBlur = () => {
  console.log('最低保险额度输入框失去焦点')
  const rawMin = formState.coverage_amount_min
  const processedMin = rawMin != null ? Number(Math.round(Number(rawMin) * 100) / 100) : null
  if (processedMin != null && processedMin !== lastCoverageMinListened.value) {
    console.warn('监听的数据和处理后的数据不一致: 最低额度', { listened: lastCoverageMinListened.value, processed: processedMin })
    // 以处理后的数值为准，统一表单数据
    formState.coverage_amount_min = processedMin
    message.warning('最低保险额度已按统一规则处理为两位小数')
  }
  if (!formState.coverage_amount_min || formState.coverage_amount_min <= 0) {
    message.error('请输入有效的最低保险额度')
  }
}

// 保险额度最高值事件监听器
const handleCoverageMaxChange = (value) => {
  console.log('最高保险额度变更:', value)
  lastCoverageMaxListened.value = value
  
  // 验证最高额度不能小于最低额度
  if (value && formState.coverage_amount_min && value < formState.coverage_amount_min) {
    message.warning('最高额度不能小于最低额度，已自动调整')
    formState.coverage_amount_max = formState.coverage_amount_min
    return
  }
  
  // 验证最高额度合理性
  if (value > 1000000) {
    message.warning('最高保险额度超过100万，请确认风险承受能力')
  }
  
  // 计算保额区间合理性
  if (value && formState.coverage_amount_min) {
    const ratio = value / formState.coverage_amount_min
    if (ratio > 100) {
      message.warning('保额区间过大，建议缩小范围以便精准定价')
    } else if (ratio < 2) {
      message.info('保额区间较小，有利于精准定价')
    }
  }
}

const handleCoverageMaxFocus = () => {
  console.log('最高保险额度输入框获得焦点')
  message.info('请输入最高保险额度，建议根据生资最高价值设定')
}

const handleCoverageMaxBlur = () => {
  console.log('最高保险额度输入框失去焦点')
  const rawMax = formState.coverage_amount_max
  const processedMax = rawMax != null ? Number(Math.round(Number(rawMax) * 100) / 100) : null
  if (processedMax != null && processedMax !== lastCoverageMaxListened.value) {
    console.warn('监听的数据和处理后的数据不一致: 最高额度', { listened: lastCoverageMaxListened.value, processed: processedMax })
    // 以处理后的数值为准，统一表单数据
    formState.coverage_amount_max = processedMax
    message.warning('最高保险额度已按统一规则处理为两位小数')
  }
  if (!formState.coverage_amount_max || formState.coverage_amount_max <= 0) {
    message.error('请输入有效的最高保险额度')
  } else if (formState.coverage_amount_min && formState.coverage_amount_max) {
    const avgAmount = (formState.coverage_amount_min + formState.coverage_amount_max) / 2
    message.success(`保额区间设置完成，平均保额：${avgAmount.toLocaleString()}元`)
  }
}

// 添加时间日期选择器事件监听器
const handleCreatedAtChange = (date, dateString) => {
  console.log('添加时间变更:', date, dateString)
  
  if (date) {
    const selectedDate = new Date(date)
    const now = new Date()
    
    // 验证时间合理性
    if (selectedDate > now) {
      message.warning('添加时间不能晚于当前时间')
      return
    }
    
    // 检查时间是否过于久远
    const oneYearAgo = new Date()
    oneYearAgo.setFullYear(now.getFullYear() - 1)
    
    if (selectedDate < oneYearAgo) {
      message.info('注意：选择的时间距今已超过一年')
    }
    
    // 更新表单数据
    formState.created_at = dateString
    message.success('添加时间设置成功')
  }
}

const handleCreatedAtFocus = () => {
  console.log('添加时间选择器获得焦点')
  message.info('请选择险种添加时间，默认为当前时间')
}

const handleCreatedAtBlur = () => {
  console.log('添加时间选择器失去焦点')
  if (!formState.created_at) {
    message.warning('建议设置添加时间，便于记录管理')
  }
}

// 在售状态开关事件监听器
const handleOnSaleStatusChange = (checked) => {
  console.log('在售状态变更:', checked)
  
  // 更新表单数据
  formState.on_sale_status = checked
  
  // 根据状态给出相应提示
  if (checked) {
    message.success('险种已设置为在售状态，客户可以购买')
    
    // 检查必要信息是否完整
    const requiredFields = ['name', 'applicable_livestock', 'insurance_term', 'description']
    const missingFields = requiredFields.filter(field => !formState[field] || 
      (Array.isArray(formState[field]) && formState[field].length === 0))
    
    if (missingFields.length > 0) {
      message.warning('启用在售状态前，请确保所有必要信息已填写完整')
    }
  } else {
    message.info('险种已设置为停售状态，客户暂时无法购买')
  }
  
  // 状态变更日志
  const statusText = checked ? '启用' : '停用'
  console.log(`险种销售状态${statusText}，时间：${new Date().toLocaleString()}`)
}

// 导出Excel
const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm
    }
    
    const response = await insuranceTypeAPI.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
  }
}

// 组件卸载状态跟踪
const isComponentMounted = ref(true)

onMounted(() => {
  loadInsuranceTypes()
})

onBeforeUnmount(() => {
  isComponentMounted.value = false
  console.log('InsuranceTypeManagement组件即将卸载')
})

// 错误边界处理
onErrorCaptured((error, instance, info) => {
  console.error('InsuranceTypeManagement组件捕获错误:', error)
  console.error('错误信息:', info)
  console.error('组件实例:', instance)
  
  // 防止错误向上传播
  return false
})
</script>

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