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

    <div class="search-form">
      <a-form :model="searchForm" layout="inline">
        <a-form-item label="保险公司名称" field="insuranceCompanyName">
          <a-input
            v-model="searchForm.insuranceCompanyName"
            placeholder="请输入保险公司名称"
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="联系人" field="contact">
          <a-input
            v-model="searchForm.contact"
            placeholder="请输入联系人"
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-form-item>
        <a-form-item label="合作状态" field="status">
          <a-select
            v-model="searchForm.status"
            placeholder="请选择合作状态"
            style="width: 150px"
            allow-clear
          >
            <a-option value="0">合作中</a-option>
            <a-option value="1">已终止</a-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon>
                <icon-search />
              </template>
              查询
            </a-button>
            <a-button @click="handleReset">
              <template #icon>
                <icon-refresh />
              </template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </div>

    <div class="table-container">
      <a-table
        :columns="columns"
        :data="companyList"
        :pagination="paginationConfig"
        :loading="loading"
        row-key="id"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #status="{ record }">
          <a-tag :color="record.status === '0' ? 'green' : 'red'">
            {{ record.status === '0' ? '合作中' : '已终止' }}
          </a-tag>
        </template>
        <template #actions="{ record }">
          <a-space>
            <a-button 
              type="primary" 
              size="small" 
              @click="editCompany(record)"
            >
              编辑
            </a-button>
            <a-button 
              type="primary" 
              status="warning" 
              size="small" 
              @click="terminateCooperation(record)"
              v-if="record.status === '0'"
            >
              终止合作
            </a-button>
            <a-button 
              type="primary" 
              status="success" 
              size="small" 
              @click="resumeCooperation(record)"
              v-if="record.status === '1'"
            >
              恢复合作
            </a-button>
            <a-button 
              type="primary" 
              status="danger" 
              size="small" 
              @click="deleteCompany(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 添加/编辑保险公司模态框 -->
    <a-modal
      v-model:visible="companyModalVisible"
      :title="isEdit ? '编辑保险公司' : '添加保险公司'"
      width="500px"
      @ok="handleCompanySubmit"
      @cancel="handleCompanyCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="companyFormRef"
        :model="companyForm"
        :rules="companyRules"
        layout="vertical"
      >
        <a-form-item label="保险公司名称" field="insuranceCompanyName">
          <a-input v-model="companyForm.insuranceCompanyName" placeholder="请输入保险公司名称" />
        </a-form-item>
        
        <a-form-item label="联系人" field="contact">
          <a-input v-model="companyForm.contact" placeholder="请输入联系人" />
        </a-form-item>
        
        <a-form-item label="联系电话" field="contactPhone">
          <a-input v-model="companyForm.contactPhone" placeholder="请输入联系电话" />
        </a-form-item>
        
        <a-form-item label="电子邮箱" field="email">
          <a-input v-model="companyForm.email" placeholder="请输入电子邮箱" />
        </a-form-item>
        
        <a-form-item label="公司地址" field="address">
          <a-input v-model="companyForm.address" placeholder="请输入公司地址" />
        </a-form-item>
        
        <a-form-item label="合作开始日期" field="startDate">
          <a-date-picker v-model="companyForm.startDate" style="width: 100%" />
        </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, IconSearch, IconRefresh } from '@arco-design/web-vue/es/icon'
import * as InsuranceCompanyAPI from '@/apis/insurance-company'

// 类型定义
interface Company {
  id?: string
  insuranceCompanyName: string
  contact: string
  contactPhone: string
  status: string
  email?: string
  address?: string
  startDate?: string
}

// 表格列定义
const columns = [
  {
    title: '保险公司名称',
    dataIndex: 'insuranceCompanyName',
    width: 200,
  },
  {
    title: '联系人',
    dataIndex: 'contact',
    width: 120,
  },
  {
    title: '联系电话',
    dataIndex: 'contactPhone',
    width: 150,
  },
  {
    title: '电子邮箱',
    dataIndex: 'email',
    width: 180,
  },
  {
    title: '合作状态',
    dataIndex: 'status',
    slotName: 'status',
    width: 100,
  },
  {
    title: '操作',
    slotName: 'actions',
    width: 200,
  },
]

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const companyList = ref<Company[]>([])
const companyModalVisible = ref(false)
const isEdit = ref(false)
const companyFormRef = ref()

// 搜索表单
const searchForm = reactive({
  insuranceCompanyName: '',
  contact: '',
  status: '',
})

// 分页配置
const paginationConfig = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showPageSize: true,
  pageSizeOptions: ['10', '20', '50', '100']
})

// 表单数据
const companyForm = reactive({
  id: '',
  insuranceCompanyName: '',
  contact: '',
  contactPhone: '',
  status: '0',
  email: '',
  address: '',
  startDate: ''
})

// 表单验证规则
const companyRules = {
  insuranceCompanyName: [
    { required: true, message: '请输入保险公司名称' },
  ],
  contact: [
    { required: true, message: '请输入联系人' },
  ],
  contactPhone: [
    { required: true, message: '请输入联系电话' },
    { 
      pattern: /^1[3-9]\d{9}$/, 
      message: '请输入正确的手机号码' 
    },
  ],
  email: [
    { 
      pattern: /^[^\s@]+@[^\s@]+\.[^\s@]+$/, 
      message: '请输入正确的邮箱地址' 
    },
  ],
}

// 获取保险公司列表
const getCompanyList = async () => {
  try {
    loading.value = true
    const params = {
      ...searchForm,
      current: paginationConfig.current,
      size: paginationConfig.pageSize,
    }
    
    const response = await InsuranceCompanyAPI.getInsuranceCompanyList(params)
    
    console.log('保险公司列表响应:', response)
    
    if (response.data) {
      companyList.value = response.data || []
      paginationConfig.total = response.data.total || 0
    } else {
      Message.error('获取保险公司列表失败')
    }
  } catch (error) {
    console.error('获取保险公司列表失败:', error)
    Message.error('获取保险公司列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  paginationConfig.current = 1
  getCompanyList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    insuranceCompanyName: '',
    contact: '',
    status: '',
  })
  paginationConfig.current = 1
  getCompanyList()
}

// 分页变化
const handlePageChange = (page: number) => {
  paginationConfig.current = page
  getCompanyList()
}

// 页码大小变化
const handlePageSizeChange = (pageSize: number) => {
  paginationConfig.pageSize = pageSize
  paginationConfig.current = 1
  getCompanyList()
}

// 显示添加保险公司模态框
const showAddCompanyModal = () => {
  isEdit.value = false
  resetForm()
  companyModalVisible.value = true
}

// 编辑保险公司
const editCompany = (record: Company) => {
  isEdit.value = true
  Object.assign(companyForm, record)
  companyModalVisible.value = true
}

// 终止合作
const terminateCooperation = (record: Company) => {
  Modal.confirm({
    title: '确认终止合作',
    content: `确定要终止与 ${record.insuranceCompanyName} 的合作吗？`,
    onOk: async () => {
      try {
        const response = await InsuranceCompanyAPI.terminateCooperation(record.id!)
        if (response.code === 200) {
          Message.success('合作已终止')
          getCompanyList()
        } else {
          Message.error(response.msg || '终止合作失败')
        }
      } catch (error) {
        console.error('终止合作失败:', error)
        Message.error('终止合作失败')
      }
    }
  })
}

// 恢复合作
const resumeCooperation = (record: Company) => {
  Modal.confirm({
    title: '确认恢复合作',
    content: `确定要恢复与 ${record.insuranceCompanyName} 的合作吗？`,
    onOk: async () => {
      try {
        const response = await InsuranceCompanyAPI.resumeCooperation(record.id!)
        if (response.code === 200) {
          Message.success('合作已恢复')
          getCompanyList()
        } else {
          Message.error(response.msg || '恢复合作失败')
        }
      } catch (error) {
        console.error('恢复合作失败:', error)
        Message.error('恢复合作失败')
      }
    }
  })
}

// 删除保险公司
const deleteCompany = (record: Company) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除 ${record.insuranceCompanyName} 吗？此操作不可恢复。`,
    onOk: async () => {
      try {
        const response = await InsuranceCompanyAPI.deleteInsuranceCompany(record.id!)
        if (response.code === 200) {
          Message.success('删除成功')
          getCompanyList()
        } else {
          Message.error(response.msg || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        Message.error('删除失败')
      }
    }
  })
}

// 表单提交
const handleCompanySubmit = async () => {
  try {
    await companyFormRef.value?.validate()
    submitLoading.value = true
    
    const formData = { ...companyForm }
    
    if (isEdit.value) {
      // 编辑保险公司
      const response = await InsuranceCompanyAPI.updateInsuranceCompany(formData.id!, formData)
      if (response.code === 200) {
        Message.success('保险公司信息更新成功')
        companyModalVisible.value = false
        resetForm()
        getCompanyList()
      } else {
        Message.error(response.msg || '更新失败')
      }
    } else {
      // 新增保险公司
      const response = await InsuranceCompanyAPI.createInsuranceCompany(formData)
      if (response.code === 200) {
        Message.success('保险公司添加成功')
        companyModalVisible.value = false
        resetForm()
        getCompanyList()
      } else {
        Message.error(response.msg || '添加失败')
      }
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    submitLoading.value = false
  }
}

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

// 重置表单
const resetForm = () => {
  Object.assign(companyForm, {
    id: '',
    insuranceCompanyName: '',
    contact: '',
    contactPhone: '',
    status: '0',
    email: '',
    address: '',
    startDate: ''
  })
  companyFormRef.value?.resetFields()
}

// 组件挂载
onMounted(() => {
  getCompanyList()
})
</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;
}

.search-form {
  background: white;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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