<template>
  <div class="supervisory-task-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">监管任务导入</h2>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <div class="left-actions">
        <a-button type="primary" @click="showCreateModal" :icon="h(PlusOutlined)">
          新增监管任务
        </a-button>
        <a-button @click="handleExport" :icon="h(ExportOutlined)">
          任务导出
        </a-button>
        <a-button @click="showBulkCreateModal" :icon="h(CloudUploadOutlined)">
          批量新增
        </a-button>
      </div>

      <div class="right-actions">
        <a-input-group compact>
          <a-select
            v-model:value="searchType"
            placeholder="搜索类型"
            style="width: 120px"
          >
            <a-select-option value="policyNumber">保单号</a-select-option>
            <a-select-option value="customerName">承保人分类</a-select-option>
          </a-select>
          <a-input
            v-model:value="searchValue"
            placeholder="请输入搜索内容"
            style="width: 200px"
            @press-enter="handleSearch"
          />
        </a-input-group>
        <a-button type="primary" @click="handleSearch" :icon="h(SearchOutlined)">
          搜索
        </a-button>
        <a-button @click="resetSearch">重置</a-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="taskList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
        size="middle"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'applicableSupplies'">
            {{ formatApplicableSupplies(record.applicableSupplies) }}
          </template>
          <template v-else-if="column.key === 'taskStatus'">
            <a-tag :color="getStatusColor(record.taskStatus)">
              {{ record.taskStatus }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <a-tag :color="getPriorityColor(record.priority)">
              {{ record.priority }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button 
              type="link" 
              size="small" 
              @click="showViewModal(record)"
            >
              查看
            </a-button>
            <a-button 
              type="link" 
              size="small" 
              @click="showEditModal(record)"
            >
              编辑
            </a-button>
            <a-popconfirm
              title="确定要删除这个监管任务吗？"
              @confirm="handleDelete(record.id)"
            >
              <a-button 
                type="link" 
                size="small" 
                danger
              >
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 创建/编辑任务弹窗 -->
    <a-modal
      v-model:open="taskModalVisible"
      :title="modalMode === 'create' ? '新增监管任务' : modalMode === 'edit' ? '编辑监管任务' : '查看监管任务'"
      :width="800"
      :footer="modalMode === 'view' ? null : undefined"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
    >
      <a-form
        ref="taskFormRef"
        :model="taskForm"
        :rules="taskFormRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :disabled="modalMode === 'view'"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请单号" name="applicationNumber">
              <a-input v-model:value="taskForm.applicationNumber" placeholder="请输入申请单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保单编号" name="policyNumber">
              <a-input v-model:value="taskForm.policyNumber" placeholder="请输入保单编号" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="产品名称" name="productName">
              <a-input v-model:value="taskForm.productName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保险周期" name="insurancePeriod">
              <a-input v-model:value="taskForm.insurancePeriod" placeholder="请输入保险周期" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="客户姓名" name="customerName">
              <a-input v-model:value="taskForm.customerName" placeholder="请输入客户姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="证件类型" name="idType">
              <a-select v-model:value="taskForm.idType" placeholder="请选择证件类型">
                <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="12">
            <a-form-item label="证件号码" name="idNumber">
              <a-input v-model:value="taskForm.idNumber" placeholder="请输入证件号码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="监管生资数量" name="supervisorySuppliesQuantity">
              <a-input-number 
                v-model:value="taskForm.supervisorySuppliesQuantity" 
                placeholder="请输入监管生资数量"
                :min="0"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="任务状态" name="taskStatus">
              <a-select v-model:value="taskForm.taskStatus" placeholder="请选择任务状态">
                <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-col :span="12">
            <a-form-item label="优先级" name="priority">
              <a-select v-model:value="taskForm.priority" placeholder="请选择优先级">
                <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-form-item label="适用生资" name="applicableSupplies">
          <a-textarea 
            v-model:value="taskForm.applicableSuppliesText" 
            placeholder="请输入适用生资信息"
            :rows="3"
          />
        </a-form-item>

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

    <!-- 批量新增弹窗 -->
    <a-modal
      v-model:open="bulkCreateModalVisible"
      title="批量新增监管任务"
      :width="600"
      @ok="handleBulkCreateOk"
      @cancel="handleBulkCreateCancel"
    >
      <div class="bulk-create-content">
        <a-upload-dragger
          :file-list="fileList"
          :before-upload="beforeUpload"
          @remove="handleRemove"
          accept=".xlsx,.xls,.csv"
        >
          <p class="ant-upload-drag-icon">
            <CloudUploadOutlined />
          </p>
          <p class="ant-upload-text">点击或拖拽文件到此区域上传</p>
          <p class="ant-upload-hint">
            支持 Excel(.xlsx, .xls) 和 CSV 文件格式
          </p>
        </a-upload-dragger>
        
        <div class="template-download" style="margin-top: 16px;">
          <a-button type="link" @click="downloadTemplate">
            下载导入模板
          </a-button>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, h } from 'vue'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  SearchOutlined,
  ExportOutlined,
  CloudUploadOutlined
} from '@ant-design/icons-vue'
import { supervisoryTaskApi } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const taskList = ref([])
const taskModalVisible = ref(false)
const bulkCreateModalVisible = ref(false)
const modalMode = ref('create') // create, edit, view
const taskFormRef = ref()
const searchType = ref('policyNumber')
const searchValue = ref('')
const fileList = ref([])

// 表单数据
const taskForm = reactive({
  id: null,
  applicationNumber: '',
  policyNumber: '',
  productName: '',
  insurancePeriod: '',
  customerName: '',
  idType: '身份证',
  idNumber: '',
  supervisorySuppliesQuantity: 0,
  taskStatus: '待处理',
  priority: '中',
  applicableSuppliesText: '',
  notes: ''
})

// 表单验证规则
const taskFormRules = {
  applicationNumber: [
    { required: true, message: '请输入申请单号', trigger: 'blur' }
  ],
  policyNumber: [
    { required: true, message: '请输入保单编号', trigger: 'blur' }
  ],
  productName: [
    { required: true, message: '请输入产品名称', trigger: 'blur' }
  ],
  customerName: [
    { required: true, message: '请输入客户姓名', trigger: 'blur' }
  ],
  idNumber: [
    { required: true, message: '请输入证件号码', trigger: 'blur' }
  ]
}

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条数据`
})

// 表格列配置
const columns = [
  {
    title: '申请单号',
    dataIndex: 'applicationNumber',
    key: 'applicationNumber',
    width: 150
  },
  {
    title: '保单编号',
    dataIndex: 'policyNumber',
    key: 'policyNumber',
    width: 150
  },
  {
    title: '产品名称',
    dataIndex: 'productName',
    key: 'productName',
    width: 120
  },
  {
    title: '保险周期',
    dataIndex: 'insurancePeriod',
    key: 'insurancePeriod',
    width: 100
  },
  {
    title: '客户姓名',
    dataIndex: 'customerName',
    key: 'customerName',
    width: 100
  },
  {
    title: '证件类型',
    dataIndex: 'idType',
    key: 'idType',
    width: 100
  },
  {
    title: '证件号码',
    dataIndex: 'idNumber',
    key: 'idNumber',
    width: 150
  },
  {
    title: '适用生资',
    dataIndex: 'applicableSupplies',
    key: 'applicableSupplies',
    width: 120
  },
  {
    title: '监管生资数量',
    dataIndex: 'supervisorySuppliesQuantity',
    key: 'supervisorySuppliesQuantity',
    width: 120
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 状态颜色映射
const getStatusColor = (status) => {
  const colorMap = {
    '待处理': 'orange',
    '处理中': 'blue',
    '已完成': 'green',
    '已取消': 'red'
  }
  return colorMap[status] || 'default'
}

// 优先级颜色映射
const getPriorityColor = (priority) => {
  const colorMap = {
    '低': 'green',
    '中': 'blue',
    '高': 'orange',
    '紧急': 'red'
  }
  return colorMap[priority] || 'default'
}

// 获取任务列表
const fetchTaskList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      limit: pagination.pageSize
    }

    // 添加搜索条件
    if (searchValue.value) {
      params[searchType.value] = searchValue.value
    }

    const response = await supervisoryTaskApi.getList(params)
    console.log('监管任务API响应:', response)
    if (response.data && response.data.status === 'success') {
      taskList.value = response.data.data.list
      pagination.total = response.data.data.total
      console.log('监管任务数据设置成功:', taskList.value.length, '条')
    } else {
      console.log('监管任务响应格式错误:', response)
      message.error(response.data?.message || '获取任务列表失败')
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    message.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 表格变化处理
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTaskList()
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchTaskList()
}

// 重置搜索
const resetSearch = () => {
  searchValue.value = ''
  pagination.current = 1
  fetchTaskList()
}

// 显示创建弹窗
const showCreateModal = () => {
  modalMode.value = 'create'
  resetTaskForm()
  taskModalVisible.value = true
}

// 显示编辑弹窗
const showEditModal = (record) => {
  modalMode.value = 'edit'
  fillTaskForm(record)
  taskModalVisible.value = true
}

// 显示查看弹窗
const showViewModal = (record) => {
  modalMode.value = 'view'
  fillTaskForm(record)
  taskModalVisible.value = true
}

// 填充表单数据
const fillTaskForm = (record) => {
  Object.keys(taskForm).forEach(key => {
    if (key === 'applicableSuppliesText') {
      try {
        const supplies = JSON.parse(record.applicableSupplies || '[]')
        taskForm[key] = Array.isArray(supplies) ? supplies.join('\n') : record.applicableSupplies || ''
      } catch {
        taskForm[key] = record.applicableSupplies || ''
      }
    } else {
      taskForm[key] = record[key]
    }
  })
}

// 重置表单
const resetTaskForm = () => {
  Object.keys(taskForm).forEach(key => {
    if (key === 'idType') {
      taskForm[key] = '身份证'
    } else if (key === 'taskStatus') {
      taskForm[key] = '待处理'
    } else if (key === 'priority') {
      taskForm[key] = '中'
    } else if (key === 'supervisorySuppliesQuantity') {
      taskForm[key] = 0
    } else {
      taskForm[key] = key === 'id' ? null : ''
    }
  })
}

// 弹窗确定处理
const handleModalOk = async () => {
  try {
    await taskFormRef.value.validate()
    
    const submitData = { ...taskForm }
    
    // 处理适用生资数据
    if (submitData.applicableSuppliesText) {
      submitData.applicableSupplies = submitData.applicableSuppliesText.split('\n').filter(item => item.trim())
    }
    delete submitData.applicableSuppliesText

    if (modalMode.value === 'create') {
      delete submitData.id
      const response = await supervisoryTaskApi.create(submitData)
      if (response.code === 201) {
        message.success('创建监管任务成功')
        taskModalVisible.value = false
        fetchTaskList()
      }
    } else if (modalMode.value === 'edit') {
      const response = await supervisoryTaskApi.update(submitData.id, submitData)
      if (response.code === 200) {
        message.success('更新监管任务成功')
        taskModalVisible.value = false
        fetchTaskList()
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    if (error.response?.data?.message) {
      message.error(error.response.data.message)
    } else {
      message.error('操作失败')
    }
  }
}

// 弹窗取消处理
const handleModalCancel = () => {
  taskModalVisible.value = false
  resetTaskForm()
}

// 删除任务
const handleDelete = async (id) => {
  try {
    const response = await supervisoryTaskApi.delete(id)
    if (response.code === 200) {
      message.success('删除监管任务成功')
      fetchTaskList()
    }
  } catch (error) {
    console.error('删除失败:', error)
    message.error('删除失败')
  }
}

// 导出任务
const handleExport = async () => {
  try {
    const response = await supervisoryTaskApi.export()
    if (response.code === 200) {
      // 这里可以实现文件下载逻辑
      message.success('导出成功')
    }
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败')
  }
}

// 显示批量创建弹窗
const showBulkCreateModal = () => {
  bulkCreateModalVisible.value = true
  fileList.value = []
}

// 文件上传前处理
const beforeUpload = (file) => {
  fileList.value = [file]
  return false // 阻止自动上传
}

// 移除文件
const handleRemove = () => {
  fileList.value = []
}

// 批量创建确定
const handleBulkCreateOk = async () => {
  if (fileList.value.length === 0) {
    message.warning('请选择要上传的文件')
    return
  }

  try {
    // 这里应该实现文件解析和批量创建逻辑
    message.success('批量创建成功')
    bulkCreateModalVisible.value = false
    fetchTaskList()
  } catch (error) {
    console.error('批量创建失败:', error)
    message.error('批量创建失败')
  }
}

// 批量创建取消
const handleBulkCreateCancel = () => {
  bulkCreateModalVisible.value = false
  fileList.value = []
}

// 下载模板
const downloadTemplate = () => {
  // 实现模板下载逻辑
  message.info('模板下载功能开发中')
}

// 格式化适用生资
const formatApplicableSupplies = (supplies) => {
  try {
    const parsed = JSON.parse(supplies || '[]')
    return Array.isArray(parsed) ? parsed.join(', ') : supplies || ''
  } catch {
    return supplies || ''
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchTaskList()
})
</script>

<style scoped>
.supervisory-task-management {
  padding: 24px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
}

.page-title {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #262626;
}

.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.left-actions {
  display: flex;
  gap: 8px;
}

.right-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

.table-container {
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  overflow: hidden;
}

.bulk-create-content {
  padding: 16px 0;
}

.template-download {
  text-align: center;
  padding-top: 16px;
  border-top: 1px solid #f0f0f0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 16px;
  }
  
  .left-actions,
  .right-actions {
    width: 100%;
    justify-content: center;
  }
  
  .right-actions {
    flex-wrap: wrap;
  }
}
</style>