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

    <!-- 操作按钮区 -->
    <div class="action-buttons">
      <a-space>
        <a-button @click="handleExport">
          <DownloadOutlined />
          导出Excel
        </a-button>
        <a-button type="primary" @click="handleCreateTask">
          新增监管任务
        </a-button>
        <a-button @click="handleTaskGuidance">
          任务导入
        </a-button>
        <a-button @click="handleBatchCreate">
          批量新增
        </a-button>
      </a-space>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <a-form layout="inline" :model="searchForm" @finish="handleSearch">
        <a-form-item>
          <a-input 
            v-model:value="searchForm.policyNumber" 
            placeholder="保单编号"
            allowClear
            style="width: 120px;"
          />
        </a-form-item>
        <a-form-item>
          <a-input 
            v-model:value="searchForm.customerName" 
            placeholder="客户姓名"
            allowClear
            style="width: 120px;"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit">
            <SearchOutlined />
            搜索
          </a-button>
        </a-form-item>
        <a-form-item>
          <a-button @click="handleReset">重置</a-button>
        </a-form-item>
      </a-form>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <a-table
        :columns="columns"
        :data-source="tableData"
        :pagination="pagination"
        :loading="loading"
        row-key="id"
        :row-selection="rowSelection"
        @change="handleTableChange"
        size="middle"
        :scroll="{ x: 1500 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-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="handleView(record)">
              查看
            </a-button>
            <a-button type="link" size="small" @click="handleEdit(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>

    <!-- 数据为空提示 -->
    <div v-if="!loading && tableData.length === 0" class="empty-data">
      <a-empty description="暂无数据" />
    </div>

    <!-- 分页信息 -->
    <div class="pagination-info">
      <span>共 {{ pagination.total }} 条</span>
      <span>页共 0 条</span>
    </div>

    <!-- 查看详情弹窗 -->
    <a-modal
      title="查看监管任务详情"
      :open="viewModalVisible"
      :width="900"
      @cancel="handleViewModalCancel"
      :footer="null"
    >
      <a-descriptions bordered :column="2" size="middle">
        <a-descriptions-item label="申请单号">
          {{ viewRecord.applicationNumber || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="保单编号">
          {{ viewRecord.policyNumber || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="产品名称">
          {{ viewRecord.productName || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="保险期间">
          {{ viewRecord.insurancePeriod || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="客户姓名">
          {{ viewRecord.customerName || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="证件类型">
          {{ viewRecord.idType || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="证件号码">
          {{ viewRecord.idNumber || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="适用金额">
          {{ viewRecord.applicableAmount ? formatAmount(viewRecord.applicableAmount) : '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="监管生资数量">
          {{ viewRecord.supervisorySuppliesQuantity || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="任务类型">
          <a-tag :color="getTaskTypeColor(viewRecord.taskType)">
            {{ getTaskTypeText(viewRecord.taskType) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="任务状态">
          <a-tag :color="getStatusColor(viewRecord.taskStatus)">
            {{ getStatusText(viewRecord.taskStatus) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="优先级">
          <a-tag :color="getPriorityColor(viewRecord.priority)">
            {{ getPriorityText(viewRecord.priority) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="创建时间" :span="2">
          {{ viewRecord.createdAt || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="更新时间" :span="2">
          {{ viewRecord.updatedAt || '-' }}
        </a-descriptions-item>
        <a-descriptions-item label="备注" :span="2">
          {{ viewRecord.remarks || '-' }}
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>

    <!-- 创建/编辑监管任务弹窗 -->
    <a-modal
      :title="modalTitle"
      :open="modalVisible"
      :width="800"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :confirmLoading="modalLoading"
    >
      <a-form
        ref="modalFormRef"
        :model="modalForm"
        :rules="modalRules"
        layout="vertical"
      >
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="申请单号" name="applicationNumber">
              <a-input v-model:value="modalForm.applicationNumber" placeholder="请输入申请单号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保单编号" name="policyNumber">
              <a-input v-model:value="modalForm.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="modalForm.productName" placeholder="请输入产品名称" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="保险期间" name="insurancePeriod">
              <a-input v-model:value="modalForm.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="modalForm.customerName" placeholder="请输入客户姓名" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="证件类型" name="idType">
              <a-select v-model:value="modalForm.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>
            </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="modalForm.idNumber" placeholder="请输入证件号码" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="适用金额" name="applicableAmount">
              <a-input-number 
                v-model:value="modalForm.applicableAmount" 
                placeholder="请输入适用金额"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="任务类型" name="taskType">
              <a-select v-model:value="modalForm.taskType" placeholder="请选择任务类型">
                <a-select-option value="new_application">新增监管任务</a-select-option>
                <a-select-option value="task_guidance">任务导入</a-select-option>
                <a-select-option value="batch_operation">批量新增</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="modalForm.priority" placeholder="请选择优先级">
                <a-select-option value="low">低</a-select-option>
                <a-select-option value="medium">中</a-select-option>
                <a-select-option value="high">高</a-select-option>
                <a-select-option value="urgent">紧急</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>

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

<script>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import { supervisionTaskApi } from '@/utils/api'

export default {
  name: 'SupervisionTaskManagement',
  components: {
    SearchOutlined,
    DownloadOutlined
  },
  setup() {
    const loading = ref(false)
    const tableData = ref([])
    const selectedRowKeys = ref([])
    const modalVisible = ref(false)
    const modalLoading = ref(false)
    const modalFormRef = ref()
    const editingId = ref(null)
    const viewModalVisible = ref(false)
    const viewRecord = ref({})

    // 搜索表单
    const searchForm = reactive({
      policyNumber: '',
      customerName: ''
    })

    // 分页配置
    const pagination = reactive({
      current: 1,
      pageSize: 10,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
    })

    // 弹窗表单
    const modalForm = reactive({
      applicationNumber: '',
      policyNumber: '',
      productName: '',
      insurancePeriod: '',
      customerName: '',
      idType: '',
      idNumber: '',
      supervisorySuppliesQuantity: null,
      taskStatus: '',
      priority: '中',
      notes: ''
    })

    // 表单验证规则
    const modalRules = {
      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 modalTitle = computed(() => {
      return editingId.value ? '编辑监管任务' : '新增监管任务'
    })

    // 表格列配置
    const columns = [
      {
        title: '申请单号',
        dataIndex: 'applicationNumber',
        key: 'applicationNumber',
        width: 120,
        fixed: 'left'
      },
      {
        title: '保单编号',
        dataIndex: 'policyNumber',
        key: 'policyNumber',
        width: 120
      },
      {
        title: '产品名称',
        dataIndex: 'productName',
        key: 'productName',
        width: 150
      },
      {
        title: '保险期间',
        dataIndex: 'insurancePeriod',
        key: 'insurancePeriod',
        width: 120
      },
      {
        title: '客户姓名',
        dataIndex: 'customerName',
        key: 'customerName',
        width: 100
      },
      {
        title: '证件类型',
        dataIndex: 'idType',
        key: 'idType',
        width: 100
      },
      {
        title: '证件号码',
        dataIndex: 'idNumber',
        key: 'idNumber',
        width: 150
      },
      {
        title: '监管生资数量',
        dataIndex: 'supervisorySuppliesQuantity',
        key: 'supervisorySuppliesQuantity',
        width: 120
      },
      {
        title: '任务状态',
        dataIndex: 'taskStatus',
        key: 'taskStatus',
        width: 100
      },
      {
        title: '优先级',
        dataIndex: 'priority',
        key: 'priority',
        width: 80
      },
      {
        title: '操作',
        key: 'action',
        width: 150,
        fixed: 'right'
      }
    ]

    // 行选择配置
    const rowSelection = {
      selectedRowKeys: selectedRowKeys,
      onChange: (keys) => {
        selectedRowKeys.value = keys
      }
    }

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

    const getStatusText = (status) => {
      return status || '待处理'
    }

    const getTaskTypeColor = (taskType) => {
      const colorMap = {
        new_application: 'blue',
        task_guidance: 'green',
        batch_operation: 'purple'
      }
      return colorMap[taskType] || 'default'
    }

    const getTaskTypeText = (taskType) => {
      const textMap = {
        new_application: '新增监管任务',
        task_guidance: '任务导入',
        batch_operation: '批量新增'
      }
      return textMap[taskType] || taskType
    }

    const getPriorityColor = (priority) => {
      const colorMap = {
        '低': 'green',
        '中': 'blue',
        '高': 'orange',
        '紧急': 'red'
      }
      return colorMap[priority] || 'default'
    }

    const getPriorityText = (priority) => {
      return priority || '中'
    }

    const formatAmount = (amount) => {
      if (!amount) return '0.00'
      return new Intl.NumberFormat('zh-CN', {
        style: 'currency',
        currency: 'CNY'
      }).format(amount)
    }

    // 数据加载
    const loadData = async () => {
      loading.value = true
      try {
        const params = {
          page: pagination.current,
          limit: pagination.pageSize,
          policyNumber: searchForm.policyNumber,
          customerName: searchForm.customerName
        }

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

    // 事件处理方法
    const handleSearch = () => {
      pagination.current = 1
      loadData()
    }

    const handleReset = () => {
      searchForm.policyNumber = ''
      searchForm.customerName = ''
      pagination.current = 1
      loadData()
    }

    const handleTableChange = (paginationConfig) => {
      pagination.current = paginationConfig.current
      pagination.pageSize = paginationConfig.pageSize
      loadData()
    }

    const handleCreateTask = () => {
      editingId.value = null
      resetModalForm()
      modalVisible.value = true
    }

    const handleTaskGuidance = () => {
      message.info('任务导入功能开发中...')
    }

    const handleBatchCreate = () => {
      message.info('批量新增功能开发中...')
    }

    const handleView = (record) => {
      console.log('查看详情:', record)
      viewRecord.value = { ...record }
      viewModalVisible.value = true
    }

    const handleViewModalCancel = () => {
      viewModalVisible.value = false
      viewRecord.value = {}
    }

    const handleEdit = (record) => {
      editingId.value = record.id
      Object.assign(modalForm, record)
      modalVisible.value = true
    }

    const handleDelete = async (id) => {
      try {
        const response = await supervisionTaskApi.delete(id)
        if (response.code === 200) {
          message.success('删除成功')
          loadData()
        } else {
          message.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    }

    const resetModalForm = () => {
      Object.assign(modalForm, {
        applicationNumber: '',
        policyNumber: '',
        productName: '',
        insurancePeriod: '',
        customerName: '',
        idType: '',
        idNumber: '',
        supervisorySuppliesQuantity: null,
        taskStatus: '',
        priority: '中',
        notes: ''
      })
    }

    const handleModalOk = async () => {
      try {
        await modalFormRef.value.validate()
        modalLoading.value = true

        const apiMethod = editingId.value ? 
          supervisionTaskApi.update.bind(null, editingId.value) : 
          supervisionTaskApi.create
        
        const response = await supervisionTaskApi.create(modalForm)
        
        if (response.code === 201) {
          message.success(editingId.value ? '更新成功' : '创建成功')
          modalVisible.value = false
          loadData()
        } else {
          message.error(response.message || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        message.error('操作失败')
      } finally {
        modalLoading.value = false
      }
    }

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

    const handleExport = async () => {
      try {
        loading.value = true
        const params = {
          policyNumber: searchForm.policyNumber || undefined,
          customerName: searchForm.customerName || undefined
        }
        
        // 过滤掉undefined值
        Object.keys(params).forEach(key => {
          if (params[key] === undefined) {
            delete params[key]
          }
        })
        
        const response = await supervisionTaskApi.export(params)
        
        // 创建下载链接 - response.data已经是Blob对象，不需要再包装
        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(() => {
      loadData()
    })

    return {
      loading,
      tableData,
      selectedRowKeys,
      searchForm,
      pagination,
      columns,
      rowSelection,
      modalVisible,
      modalLoading,
      modalForm,
      modalFormRef,
      modalRules,
      modalTitle,
      viewModalVisible,
      viewRecord,
      getStatusColor,
      getStatusText,
      getTaskTypeColor,
      getTaskTypeText,
      getPriorityColor,
      getPriorityText,
      formatAmount,
      handleSearch,
      handleReset,
      handleTableChange,
      handleCreateTask,
      handleTaskGuidance,
      handleBatchCreate,
      handleView,
      handleViewModalCancel,
      handleEdit,
      handleDelete,
      handleModalOk,
      handleModalCancel,
      handleExport
    }
  }
}
</script>

<style scoped>
.supervision-task-page {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}

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

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

.action-buttons {
  margin-bottom: 16px;
}

.search-area {
  margin-bottom: 16px;
  padding: 16px;
  background: #fafafa;
  border-radius: 6px;
}

.table-container {
  margin-bottom: 16px;
}

.empty-data {
  text-align: center;
  padding: 40px 0;
}

.pagination-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  color: #666;
}
</style>