<template>
  <div class="training-plan-container">
    <!-- 搜索表单 -->
    <a-card class="search-card" :bordered="false">
      <a-form layout="inline" :model="searchForm" @submit="handleSearch">
        <a-form-item label="计划名称">
          <a-input
            v-model:value="searchForm.planName"
            placeholder="请输入计划名称"
            allow-clear
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="培训类型">
          <a-select
            v-model:value="searchForm.trainingType"
            :options="trainingTypeOptions"
            placeholder="请选择培训类型"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="培训级别">
          <a-select
            v-model:value="searchForm.trainingLevel"
            :options="trainingLevelOptions"
            placeholder="请选择培训级别"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchForm.status"
            :options="statusOptions"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading">
            <template #icon>
              <IconSearch />
            </template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <template #icon>
              <IconRefresh />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card class="table-card" :bordered="false">
      <template #title>
        <div class="card-title">
          <span>培训计划列表</span>
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <IconPlus />
            </template>
            新增计划
          </a-button>
        </div>
      </template>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        row-key="planId"
        @change="handleTableChange"
      >
        <template #trainingType="{ record }">
          <a-tag :color="getTrainingTypeColor(record.trainingType)">
            {{ getTrainingTypeText(record.trainingType) }}
          </a-tag>
        </template>
        <template #trainingLevel="{ record }">
          <a-tag :color="getTrainingLevelColor(record.trainingLevel)">
            {{ getTrainingLevelText(record.trainingLevel) }}
          </a-tag>
        </template>
        <template #status="{ record }">
          <a-tag :color="getStatusColor(record.status)">
            {{ getStatusText(record.status) }}
          </a-tag>
        </template>
        <template #participants="{ record }">
          <span>{{ record.currentParticipants || 0 }}/{{ record.maxParticipants || '-' }}</span>
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleView(record)">
              查看
            </a-button>
            <a-button
              v-if="record.status === 'DRAFT'"
              type="text"
              size="small"
              @click="handleEdit(record)"
            >
              编辑
            </a-button>
            <a-button
              v-if="record.status === 'DRAFT'"
              type="text"
              size="small"
              @click="handlePublish(record)"
            >
              发布
            </a-button>
            <a-button
              v-if="['DRAFT', 'PUBLISHED', 'IN_PROGRESS'].includes(record.status)"
              type="text"
              size="small"
              danger
              @click="handleCancel(record)"
            >
              取消
            </a-button>
            <a-button
              v-if="record.status === 'DRAFT'"
              type="text"
              size="small"
              danger
              @click="handleDelete(record)"
            >
              删除
            </a-button>
            <a-button type="text" size="small" @click="handleDetail(record)">详情</a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <TrainingPlanModal
      v-model:visible="modalVisible"
      :plan-data="currentPlan"
      @success="handleModalSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { Modal } from '@arco-design/web-vue'
import { IconPlus, IconRefresh, IconSearch } from '@arco-design/web-vue/es/icon'
import message from '@arco-design/web-vue/es/message'
import TrainingPlanModal from './components/TrainingPlanModal.vue'
import {
  cancelTrainingPlan,
  deleteTrainingPlan,
  pageTrainingPlan,
  publishTrainingPlan,
} from '@/apis/training'
import type { TrainingPlanPageQuery, TrainingPlanResp } from '@/types/training.d'
import router from '@/router'

defineOptions({ name: 'TrainingPlan' })

// 搜索表单
const searchForm = reactive<TrainingPlanPageQuery>({
  planName: '',
  trainingType: '',
  trainingLevel: '',
  status: '',
})

// 表格数据
const tableData = ref<TrainingPlanResp[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive<any>({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
  showJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 弹窗控制
const modalVisible = ref(false)
const currentPlan = ref<TrainingPlanResp | null>(null)

// 表格列配置
const columns = [
  {
    title: '计划名称',
    dataIndex: 'planName',
    key: 'planName',
    width: 200,
  },
  {
    title: '培训类型',
    dataIndex: 'trainingType',
    key: 'trainingType',
    slotName: 'trainingType',
    width: 120,
  },
  {
    title: '培训级别',
    dataIndex: 'trainingLevel',
    key: 'trainingLevel',
    slotName: 'trainingLevel',
    width: 120,
  },
  {
    title: '培训讲师',
    dataIndex: 'trainer',
    key: 'trainer',
    width: 120,
  },
  {
    title: '培训地点',
    dataIndex: 'trainingLocation',
    key: 'trainingLocation',
    width: 150,
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    key: 'startTime',
    width: 150,
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    slotName: 'status',
    width: 100,
  },
  {
    title: '参训人数',
    dataIndex: 'participants',
    key: 'participants',
    slotName: 'participants',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    slotName: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 下拉选项
const trainingTypeOptions = [
  { label: '安全教育', value: 'SAFETY' },
  { label: '技能培训', value: 'SKILL' },
  { label: '企业文化', value: 'CULTURE' },
]
const trainingLevelOptions = [
  { label: '现场级', value: 'SITE' },
  { label: '部门级', value: 'DEPARTMENT' },
  { label: '公司级', value: 'COMPANY' },
]
const statusOptions = [
  { label: '草稿', value: 'DRAFT' },
  { label: '已发布', value: 'PUBLISHED' },
  { label: '进行中', value: 'IN_PROGRESS' },
  { label: '已完成', value: 'COMPLETED' },
  { label: '已取消', value: 'CANCELLED' },
]

// 获取培训类型文本
const getTrainingTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    SAFETY: '安全教育',
    SKILL: '技能培训',
    CULTURE: '企业文化',
    安全教育: '安全教育',
    技能培训: '技能培训',
    企业文化: '企业文化',
  }
  return typeMap[type] || type
}

// 获取培训类型颜色
const getTrainingTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    SAFETY: 'red',
    SKILL: 'blue',
    CULTURE: 'green',
    安全教育: 'red',
    技能培训: 'blue',
    企业文化: 'green',
  }
  return colorMap[type] || 'default'
}

// 获取培训级别文本
const getTrainingLevelText = (level: string) => {
  const levelMap: Record<string, string> = {
    SITE: '现场级',
    DEPARTMENT: '部门级',
    COMPANY: '公司级',
    现场级: '现场级',
    部门级: '部门级',
    公司级: '公司级',
  }
  return levelMap[level] || level
}

// 获取培训级别颜色
const getTrainingLevelColor = (level: string) => {
  const colorMap: Record<string, string> = {
    SITE: 'orange',
    DEPARTMENT: 'purple',
    COMPANY: 'cyan',
    现场级: 'orange',
    部门级: 'purple',
    公司级: 'cyan',
  }
  return colorMap[level] || 'default'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    DRAFT: '草稿',
    PUBLISHED: '已发布',
    IN_PROGRESS: '进行中',
    COMPLETED: '已完成',
    CANCELLED: '已取消',
  }
  return statusMap[status] || status
}

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    DRAFT: 'default',
    PUBLISHED: 'blue',
    IN_PROGRESS: 'processing',
    COMPLETED: 'success',
    CANCELLED: 'error',
  }
  return colorMap[status] || 'default'
}

// 数据转换函数
const transformBackendData = (data: any[]) => {
  console.log('转换前的数据:', data)
  return data.map((item) => {
    console.log('处理单个项目:', item)
    return {
      planId: item.planId || item.id,
      planName: item.planName || item.name,
      trainingType: item.trainingType || item.type,
      trainingLevel: item.trainingLevel || item.level,
      trainingContent: item.trainingContent || item.content,
      trainer: item.trainer,
      trainingLocation: item.trainingLocation || item.location,
      startTime: item.startTime ? new Date(item.startTime).toLocaleString() : '',
      endTime: item.endTime ? new Date(item.endTime).toLocaleString() : '',
      status: item.status,
      maxParticipants: item.maxParticipants || item.maxParticipantsNum,
      currentParticipants: item.currentParticipants || item.currentParticipantsNum || 0,
      requirements: item.requirements,
      remark: item.remark,
      createTime: item.createTime ? new Date(item.createTime).toLocaleString() : '',
      createBy: item.createBy || item.createByUser,
    }
  })
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageSize: pagination.pageSize,
      page: pagination.current,
      ...searchForm, // 添加搜索条件
    }
    const res = await pageTrainingPlan(params)

    console.log('API响应:', res)

    // 兼容不同的响应格式
    if (res.success || res.status === 200 || res.code === 200) {
      // 处理数据，确保数据格式正确
      let dataList: any[] = []

      // 检查不同的数据字段
      if (Array.isArray(res.data)) {
        dataList = res.data
      } else if (res.data && Array.isArray((res as any).rows)) {
        dataList = (res as any).rows
      } else if (res.data && Array.isArray((res.data as any).records)) {
        dataList = (res.data as any).records
      } else if (res.data && Array.isArray((res.data as any).list)) {
        dataList = (res.data as any).list
      }

      console.log('处理后的数据列表:', dataList)

      if (dataList.length > 0) {
        const transformedData = transformBackendData(dataList)
        console.log('转换后的数据:', transformedData)
        tableData.value = transformedData
      } else {
        tableData.value = []
      }

      // 设置总数
      pagination.total = (res as any).total || (res.data as any)?.total || dataList.length || 0
      console.log('总数:', pagination.total)
    } else {
      message.error(res.msg || '加载数据失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    planName: '',
    trainingType: '',
    trainingLevel: '',
    status: '',
  })
  pagination.current = 1
  loadData()
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current || 1
  pagination.pageSize = pag.pageSize || 10
  loadData()
}

// 新增
const handleAdd = () => {
  currentPlan.value = null
  modalVisible.value = true
}

// 查看
const handleView = (record: TrainingPlanResp) => {
  currentPlan.value = record
  modalVisible.value = true
}

// 编辑
const handleEdit = (record: TrainingPlanResp) => {
  currentPlan.value = record
  modalVisible.value = true
}

// 发布
const handlePublish = async (record: TrainingPlanResp) => {
  try {
    await publishTrainingPlan(record.planId)
    message.success('发布成功')
    loadData()
  } catch (error) {
    console.error('发布失败:', error)
    message.error('发布失败')
  }
}

// 取消
const handleCancel = async (record: TrainingPlanResp) => {
  Modal.confirm({
    title: '确认取消',
    content: `确定要取消培训计划"${record.planName}"吗？`,
    onOk: async () => {
      try {
        await cancelTrainingPlan(record.planId)
        message.success('取消成功')
        loadData()
      } catch (error) {
        console.error('取消失败:', error)
        message.error('取消失败')
      }
    },
  })
}

// 删除
const handleDelete = async (record: TrainingPlanResp) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除培训计划"${record.planName}"吗？`,
    onOk: async () => {
      try {
        await deleteTrainingPlan(record.planId)
        message.success('删除成功')
        loadData()
      } catch (error) {
        console.error('删除失败:', error)
        message.error('删除失败')
      }
    },
  })
}

// 详情
const handleDetail = (record: TrainingPlanResp) => {
  // 跳转到培训详情页面，并传递 planId
  router.push({ name: 'TrainingDetail', params: { id: record.planId } })
}

// 弹窗成功回调
const handleModalSuccess = () => {
  modalVisible.value = false
  loadData()
}

// 监听表格数据变化
watch(tableData, (_newData) => {
  // 数据变化监听
}, { deep: true })

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.training-plan-container {
  padding: 16px;
  background: #f5f5f5;
  min-height: 100vh;

  .search-card {
    margin-bottom: 16px;
  }

  .table-card {
    .card-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>
