<template>
  <div class="completed-task-management">
    <div class="page-header">
      <h1>监管任务结项管理</h1>
      <p>查看和管理已完成的监管任务</p>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-input
            v-model:value="searchForm.taskName"
            placeholder="请输入任务名称"
            allow-clear
          >
            <template #prefix>
              <SearchOutlined />
            </template>
          </a-input>
        </a-col>
        <a-col :span="6">
          <a-select
            v-model:value="searchForm.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 100%"
          >
            <a-select-option value="completed">已完成</a-select-option>
            <a-select-option value="archived">已归档</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="6">
          <a-range-picker
            v-model:value="searchForm.dateRange"
            style="width: 100%"
            :placeholder="['开始日期', '结束日期']"
          />
        </a-col>
        <a-col :span="6">
          <a-space>
            <a-button @click="handleExport">
              <DownloadOutlined />
              导出Excel
            </a-button>
            <a-button type="primary" @click="handleSearch">
              <SearchOutlined />
              搜索
            </a-button>
            <a-button @click="handleReset">
              <ReloadOutlined />
              重置
            </a-button>
          </a-space>
        </a-col>
      </a-row>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-section">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="总结项任务"
              :value="stats.total"
              :value-style="{ color: '#3f8600' }"
            >
              <template #prefix>
                <CheckCircleOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="本月结项"
              :value="stats.thisMonth"
              :value-style="{ color: '#1890ff' }"
            >
              <template #prefix>
                <CalendarOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="已归档任务"
              :value="stats.archived"
              :value-style="{ color: '#722ed1' }"
            >
              <template #prefix>
                <FolderOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card>
            <a-statistic
              title="平均处理时长"
              :value="stats.avgDuration"
              suffix="天"
              :value-style="{ color: '#fa8c16' }"
            >
              <template #prefix>
                <ClockCircleOutlined />
              </template>
            </a-statistic>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 任务列表 -->
    <div class="table-section">
      <a-table
        :columns="columns"
        :data-source="taskList"
        :loading="loading"
        :pagination="pagination"
        @change="handleTableChange"
        row-key="id"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'taskStatus'">
            <a-tag :color="getStatusColor(record.taskStatus)">
              {{ getStatusText(record.taskStatus) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'priority'">
            <a-tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </a-tag>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                <EyeOutlined />
                查看
              </a-button>
              <a-button type="link" size="small" @click="handleDownload(record)">
                <DownloadOutlined />
                下载报告
              </a-button>
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <a-menu-item key="archive" @click="handleArchive(record)">
                      <FolderOutlined />
                      归档
                    </a-menu-item>
                    <a-menu-item key="export" @click="handleExport(record)">
                      <ExportOutlined />
                      导出
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="link" size="small">
                  更多
                  <DownOutlined />
                </a-button>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </a-table>
    </div>

    <!-- 任务详情模态框 -->
    <a-modal
      v-model:open="detailModalVisible"
      title="任务详情"
      width="800px"
      :footer="null"
    >
      <div v-if="selectedTask" class="task-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="申请单号">
            {{ selectedTask.applicationNumber || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="保单编号">
            {{ selectedTask.policyNumber || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="产品名称">
            {{ selectedTask.productName || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="保险期间">
            {{ selectedTask.insurancePeriod || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="客户姓名">
            {{ selectedTask.customerName || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="证件类型">
            {{ selectedTask.idType || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="证件号码">
            {{ selectedTask.idNumber || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="监管生资数量">
            {{ selectedTask.supervisorySuppliesQuantity || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="优先级">
            <a-tag :color="getPriorityColor(selectedTask.priority)">
              {{ getPriorityText(selectedTask.priority) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(selectedTask.taskStatus)">
              {{ getStatusText(selectedTask.taskStatus) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="负责人">
            {{ selectedTask.assignedUser?.real_name || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建人">
            {{ selectedTask.creator?.real_name || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ selectedTask.createdAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ selectedTask.updatedAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="完成时间">
            {{ selectedTask.completedAt || '-' }}
          </a-descriptions-item>
          <a-descriptions-item label="处理时长">
            {{ calculateDuration(selectedTask) }}
          </a-descriptions-item>
          <a-descriptions-item label="备注" :span="2">
            {{ selectedTask.notes || '-' }}
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  SearchOutlined,
  ReloadOutlined,
  CheckCircleOutlined,
  CalendarOutlined,
  FolderOutlined,
  ClockCircleOutlined,
  EyeOutlined,
  DownloadOutlined,
  ExportOutlined,
  DownOutlined
} from '@ant-design/icons-vue'
import { supervisionTaskApi } from '@/utils/api'

// 响应式数据
const loading = ref(false)
const taskList = ref([])
const detailModalVisible = ref(false)
const selectedTask = ref(null)

// 搜索表单
const searchForm = reactive({
  taskName: '',
  status: undefined,
  dateRange: undefined
})

// 统计数据
const stats = reactive({
  total: 0,
  thisMonth: 0,
  archived: 0,
  avgDuration: 0
})

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

// 表格列配置
const columns = [
  {
    title: '任务编号',
    dataIndex: 'applicationNumber',
    key: 'applicationNumber',
    width: 120
  },
  {
    title: '任务名称',
    dataIndex: 'productName',
    key: 'productName',
    ellipsis: true
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    key: 'priority',
    width: 100
  },
  {
    title: '状态',
    dataIndex: 'taskStatus',
    key: 'taskStatus',
    width: 100
  },
  {
    title: '负责人',
    key: 'assignee',
    width: 120,
    customRender: ({ record }) => record.assignedUser?.real_name || '-'
  },
  {
    title: '完成时间',
    dataIndex: 'completedAt',
    key: 'completedAt',
    width: 150,
    customRender: ({ text }) => text || '-'
  },
  {
    title: '处理时长',
    key: 'duration',
    width: 100,
    customRender: ({ record }) => {
      if (!record.completedAt || !record.createdAt) return '-'
      const created = new Date(record.createdAt)
      const completed = new Date(record.completedAt)
      const days = Math.ceil((completed - created) / (1000 * 60 * 60 * 24))
      return `${days} 天`
    }
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    '待处理': 'orange',
    '处理中': 'blue',
    '已完成': 'green',
    '已取消': 'red',
    '已归档': 'purple',
    // 英文兼容
    'completed': 'green',
    'archived': 'purple'
  }
  return colorMap[status] || 'default'
}

// 获取状态文本
const getStatusText = (status) => {
  // 如果已经是中文，直接返回
  if (['待处理', '处理中', '已完成', '已取消', '已归档'].includes(status)) {
    return status
  }
  // 英文转中文
  const textMap = {
    'pending': '待处理',
    'processing': '处理中',
    'completed': '已完成',
    'rejected': '已取消',
    'archived': '已归档'
  }
  return textMap[status] || status
}

// 获取优先级颜色
const getPriorityColor = (priority) => {
  const colorMap = {
    '低': 'blue',
    '中': 'green',
    '高': 'orange',
    '紧急': 'red',
    // 英文兼容
    'low': 'blue',
    'medium': 'green',
    'high': 'orange',
    'urgent': 'red'
  }
  return colorMap[priority] || 'default'
}

// 获取优先级文本
const getPriorityText = (priority) => {
  // 如果已经是中文，直接返回
  if (['低', '中', '高', '紧急'].includes(priority)) {
    return priority
  }
  // 英文转中文
  const textMap = {
    'low': '低',
    'medium': '中',
    'high': '高',
    'urgent': '紧急'
  }
  return textMap[priority] || priority
}

// 计算处理时长
const calculateDuration = (task) => {
  if (!task.completedAt || !task.createdAt) return '-'
  try {
    const created = new Date(task.createdAt)
    const completed = new Date(task.completedAt)
    const days = Math.ceil((completed - created) / (1000 * 60 * 60 * 24))
    return `${days} 天`
  } catch (error) {
    return '-'
  }
}

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

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'status' ? undefined : ''
  })
  pagination.current = 1
  fetchTaskList()
}

const handleExport = async () => {
  try {
    loading.value = true
    const params = {
      taskName: searchForm.taskName || undefined,
      status: searchForm.status || undefined
    }
    
    // 过滤掉undefined值
    Object.keys(params).forEach(key => {
      if (params[key] === undefined) {
        delete params[key]
      }
    })
    
    const response = await supervisionTaskApi.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 handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  fetchTaskList()
}

// 查看详情
const handleView = (record) => {
  selectedTask.value = record
  detailModalVisible.value = true
}

// 下载报告
const handleDownload = async (record) => {
  try {
    message.loading(`正在下载 ${record.taskName} 的报告...`, 0)
    
    const response = await supervisionTaskApi.downloadReport(record.id)
    
    // 创建下载链接
    const url = window.URL.createObjectURL(response.data)
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', `${record.taskName}_报告_${new Date().getTime()}.pdf`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    
    message.destroy()
    message.success('报告下载成功')
  } catch (error) {
    message.destroy()
    console.error('下载报告失败:', error)
    message.error('下载报告失败，请稍后重试')
  }
}

// 归档任务
const handleArchive = async (record) => {
  try {
    const response = await supervisionTaskApi.archive(record.id)
    if (response.data && response.data.status === 'success') {
      message.success(`任务 ${record.taskName} 已归档`)
      fetchTaskList()
    } else {
      message.error(response.data?.message || '归档失败')
    }
  } catch (error) {
    console.error('归档任务失败:', error)
    message.error('归档任务失败，请稍后重试')
  }
}

  // 导出单个任务（此功能已合并到handleExport）
  // const handleExportSingle = (record) => {
  //   message.info(`正在导出 ${record.taskName} 的数据...`)
  // }

// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      limit: pagination.pageSize,
      taskStatus: 'completed' // 只获取已完成的任务
    }
    
    // 添加搜索条件
    if (searchForm.taskName) {
      params.taskName = searchForm.taskName
    }
    if (searchForm.status) {
      params.status = searchForm.status
    }
    if (searchForm.dateRange && searchForm.dateRange.length === 2) {
      params.startDate = searchForm.dateRange[0].format('YYYY-MM-DD')
      params.endDate = searchForm.dateRange[1].format('YYYY-MM-DD')
    }
    
    const response = await supervisionTaskApi.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 || 0
      console.log('监管任务结项数据设置成功:', taskList.value.length, '条')
    } else {
      console.log('监管任务结项响应格式错误:', response)
      message.error(response.data?.message || '获取任务列表失败')
    }
    
    // 获取统计数据
    await fetchStats()
    
  } catch (error) {
    console.error('获取任务列表失败:', error)
    message.error('获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    const response = await supervisionTaskApi.getStats()
    console.log('统计数据响应:', response)
    
    if (response.data && response.data.status === 'success') {
      const statsData = response.data.data
      
      // 从statusStats中获取已完成任务数
      const statusStats = statsData.statusStats || []
      const completedStat = statusStats.find(s => s.status === '已完成')
      stats.total = completedStat ? completedStat.count : 0
      
      // 这些数据暂时从总数获取，后续可以从API补充
      stats.thisMonth = 0
      stats.archived = 0
      stats.avgDuration = 0
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

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

<style scoped>
.completed-task-management {
  padding: 24px;
}

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

.page-header h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #666;
}

.search-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stats-section {
  margin-bottom: 16px;
}

.stats-section .ant-card {
  text-align: center;
}

.table-section {
  background: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.task-detail .ant-descriptions {
  margin-top: 16px;
}
</style>