<template>
  <div class="container">
    <div class="header">
      <h2>保险类型管理</h2>
      <a-button type="primary" @click="showAddTypeModal">
        <template #icon>
          <icon-plus />
        </template>
        添加保险类型
      </a-button>
    </div>

    <div class="table-container">
      <a-table
        :columns="columns"
        :data="typeList"
        :pagination="false"
        :loading="loading"
        row-key="id"
      >
        <template #actions="{ record }">
          <a-space>
            <a-button 
              type="primary" 
              size="small" 
              @click="editType(record)"
            >
              编辑
            </a-button>
            <a-button 
              type="primary" 
              status="danger" 
              size="small" 
              @click="deleteType(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑保险类型模态框 -->
    <a-modal
      v-model:visible="typeModalVisible"
      :title="isEdit ? '编辑保险类型' : '添加保险类型'"
      width="500px"
      @ok="handleTypeSubmit"
      @cancel="handleTypeCancel"
    >
      <a-form
        ref="typeFormRef"
        :model="typeForm"
        :rules="typeRules"
        layout="vertical"
      >
        <a-form-item label="保险类型名称" field="insuranceTypeName">
          <a-input v-model="typeForm.insuranceTypeName" placeholder="请输入保险类型名称" />
        </a-form-item>
        
        <a-form-item label="描述" field="description">
          <a-textarea 
            v-model="typeForm.description" 
            placeholder="请输入保险类型描述"
            :auto-size="{ minRows: 3, maxRows: 6 }"
          />
        </a-form-item>
        
        <a-form-item label="保障范围" field="coverage">
          <a-textarea 
            v-model="typeForm.coverage" 
            placeholder="请输入保障范围"
            :auto-size="{ minRows: 3, maxRows: 6 }"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { Message, Modal } from '@arco-design/web-vue'
import { IconPlus } from '@arco-design/web-vue/es/icon'
import * as InsuranceTypeAPI from '@/apis/insurance-type'

// 类型定义
interface InsuranceType {
  id?: string
  insuranceTypeName: string
  description: string
  coverage?: string
}

// 表格列定义
const columns = [
  {
    title: '保险类型名称',
    dataIndex: 'insuranceTypeName',
    width: 150,
  },
  {
    title: '描述',
    dataIndex: 'description',
    width: 200,
  },
  {
    title: '保障范围',
    dataIndex: 'coverage',
    width: 300,
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 150,
  },
]

// 响应式数据
const loading = ref(false)
const typeList = ref<InsuranceType[]>([])
const typeModalVisible = ref(false)
const isEdit = ref(false)
const typeFormRef = ref()

// 表单数据
const typeForm = reactive({
  id: '',
  insuranceTypeName: '',
  description: '',
  coverage: ''
})

// 表单验证规则
const typeRules = {
  insuranceTypeName: [
    { required: true, message: '请输入保险类型名称' },
  ],
  description: [
    { required: true, message: '请输入保险类型描述' },
  ],
}

// 获取保险类型列表
const getTypeList = async () => {
  try {
    loading.value = true
    const response = await InsuranceTypeAPI.getInsuranceTypeList()
    
    console.log('保险类型列表响应:', response)
    
    if (response.data) {
      typeList.value = response.data || []
    } else {
      Message.error('获取保险类型列表失败')
    }
  } catch (error) {
    console.error('获取保险类型列表失败:', error)
    Message.error('获取保险类型列表失败')
  } finally {
    loading.value = false
  }
}

// 显示添加保险类型模态框
const showAddTypeModal = () => {
  isEdit.value = false
  resetForm()
  typeModalVisible.value = true
}

// 编辑保险类型
const editType = (record: InsuranceType) => {
  isEdit.value = true
  Object.assign(typeForm, record)
  typeModalVisible.value = true
}

// 删除保险类型
const deleteType = (record: InsuranceType) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除保险类型"${record.insuranceTypeName}"吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk: async () => {
      try {
        if (record.id) {
          await InsuranceTypeAPI.deleteInsuranceType(record.id)
          Message.success('保险类型删除成功')
          await getTypeList()
        }
      } catch (error) {
        console.error('删除保险类型失败:', error)
        Message.error('删除保险类型失败')
      }
    },
  })
}

// 表单提交
const handleTypeSubmit = async () => {
  try {
    await typeFormRef.value?.validate()
    
    if (isEdit.value) {
      // 编辑
      if (typeForm.id) {
        await InsuranceTypeAPI.updateInsuranceType(typeForm.id, typeForm)
        Message.success('保险类型信息更新成功')
      }
    } else {
      // 添加
      await InsuranceTypeAPI.createInsuranceType(typeForm)
      Message.success('保险类型添加成功')
    }
    
    typeModalVisible.value = false
    resetForm()
    await getTypeList()
  } catch (error) {
    console.error('操作失败:', error)
    Message.error('操作失败，请重试')
  }
}

// 取消操作
const handleTypeCancel = () => {
  typeModalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(typeForm, {
    id: '',
    insuranceTypeName: '',
    description: '',
    coverage: ''
  })
  typeFormRef.value?.resetFields()
}

// 初始化数据
const initData = () => {
  getTypeList()
}

// 组件挂载
onMounted(() => {
  initData()
})
</script>

<style scoped>
.container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.table-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style> 