<template>
  <div class="app-container training-page">
    <div v-if="!showForm && !showLearnData" class="flex gap-4 h-full main-wrapper">
      <!-- 左侧分类侧边栏 -->
      <div class="category-sidebar bg-white rounded p-4 flex flex-col shrink-0">
        <div class="sidebar-header mb-4">
          <span class="font-bold text-base">培训分类</span>
        </div>
        <div class="category-list flex-1 overflow-y-auto">
          <div
            v-for="item in categories"
            :key="item.id"
            :class="['category-item', activeCategory === item.id ? 'active' : '']"
            @click="switchCategory(item.id)"
          >
            <div class="flex items-center gap-2 overflow-hidden">
              <el-icon v-if="item.id === 'video'"><i-ep-video-play /></el-icon>
              <el-icon v-else-if="item.id === 'offline'"><i-ep-location /></el-icon>
              <el-icon v-else-if="item.id === 'live'"><i-ep-video-camera /></el-icon>
              <span class="truncate">{{ item.name }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧列表内容 -->
      <div class="flex-1 bg-white rounded p-4 flex flex-col overflow-hidden content-area">
        <div class="header-bar flex justify-between items-center mb-4">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入"
            style="width: 320px"
            clearable
            class="search-input"
            @keyup.enter="handleQuery"
          >
            <template #append>
              <el-button @click="handleQuery">
                <el-icon><i-ep-search /></el-icon>
              </el-button>
            </template>
          </el-input>

          <el-button type="primary" @click="handleAdd" class="create-btn">创建培训</el-button>
        </div>

        <!-- 视频培训表格 -->
        <el-table
          v-if="activeCategory === 'video'"
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          header-cell-class-name="custom-header"
          class="custom-table flex-1"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="ID" prop="id" width="80" />
          <el-table-column label="视频名称" min-width="220">
            <template #default="scope">
              <div class="flex items-center">
                <div class="video-thumb mr-3 shrink-0">
                  <img v-if="scope.row.thumbnailUrl" :src="scope.row.thumbnailUrl" alt="" class="w-full h-full object-cover" />
                  <div v-else class="w-full h-full flex items-center justify-center bg-gray-100 text-gray-400">
                    <el-icon><i-ep-picture /></el-icon>
                  </div>
                  <div class="play-overlay">
                    <el-icon><i-ep-video-play /></el-icon>
                  </div>
                </div>
                <el-link type="primary" :underline="false" class="truncate">{{ scope.row.name }}</el-link>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="岗位类型" prop="jobType" width="100" />
          <el-table-column label="岗位等级" prop="jobLevel" width="100" />
          <el-table-column label="学习记录" width="100" align="center">
            <template #default="scope">
              <el-link type="primary" :underline="false" @click="handleData(scope.row)">{{ scope.row.learnCount || 0 }}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="课程状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="时长" prop="duration" width="100" />
          <el-table-column label="上架时间" prop="publishTime" width="180" />
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <div class="operation-links">
                <el-link type="primary" :underline="false" @click="handleData(scope.row)">数据</el-link>
                <el-link type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
                <el-link type="primary" :underline="false" @click="handleToggleStatus(scope.row)">{{ scope.row.status === 1 ? '下架' : '上架' }}</el-link>
                <el-link type="primary" :underline="false" class="delete-link" @click="handleDelete(scope.row)">删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 线下培训表格 -->
        <el-table
          v-if="activeCategory === 'offline'"
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          header-cell-class-name="custom-header"
          class="custom-table flex-1"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="ID" prop="id" width="80" />
          <el-table-column label="培训名称" prop="name" min-width="180" />
          <el-table-column label="岗位类型" prop="jobType" width="120" />
          <el-table-column label="岗位等级" prop="jobLevel" width="100" />
          <el-table-column label="时间" min-width="240">
            <template #default="scope">
              {{ formatTimeRange(scope.row.trainingStartTime, scope.row.trainingEndTime) }}
            </template>
          </el-table-column>
          <el-table-column label="地点" min-width="150">
            <template #default="scope">
              {{ [scope.row.city, scope.row.area, scope.row.addressDetail].filter(Boolean).join('') }}
            </template>
          </el-table-column>
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="参与人数" width="100" align="center">
            <template #default="scope">
              <span>{{ scope.row.participantCount || 0 }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template #default="scope">
              <div class="operation-links">
                <el-link type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
                <el-link type="primary" :underline="false" class="delete-link" @click="handleDelete(scope.row)">删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 直播培训表格 -->
        <el-table
          v-if="activeCategory === 'live'"
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          header-cell-class-name="custom-header"
          class="custom-table flex-1"
        >
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="培训名称" prop="name" min-width="200" />
          <el-table-column label="岗位类型" prop="jobType" width="150" />
          <el-table-column label="岗位等级" prop="jobLevel" width="120" />
          <el-table-column label="状态" width="100" align="center">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220" fixed="right">
            <template #default="scope">
              <div class="operation-links">
                <el-link type="primary" :underline="false" @click="handleCopy(scope.row)">复制测评</el-link>
                <el-link type="primary" :underline="false" @click="handleEdit(scope.row)">编辑</el-link>
                <el-link type="primary" :underline="false" class="delete-link" @click="handleDelete(scope.row)">删除</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页栏 -->
        <div class="pagination-wrapper mt-4 flex justify-end items-center">
          <span class="total-text mr-4">共 {{ total }} 条</span>
          <span class="page-size-select mr-4">
            显示
            <el-select v-model="queryParams.pageSize" size="small" style="width: 70px" @change="handleSizeChange">
              <el-option :label="10" :value="10" />
              <el-option :label="20" :value="20" />
              <el-option :label="50" :value="50" />
            </el-select>
            条
          </span>
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :total="total"
            background
            layout="prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 创建/编辑培训表单 -->
    <TrainForm
      v-else-if="showForm"
      :initial-data="currentTrain"
      :type="activeCategory"
      @cancel="showForm = false"
      @submit="handleFormSubmit"
    />

    <!-- 学习数据详情 -->
    <learnData
      v-else-if="showLearnData"
      :train-id="currentTrain?.id"
      :train-name="currentTrain?.name"
      :train-type="currentTrain?.trainingType"
      @back="showLearnData = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import TrainForm from './TrainForm.vue';
import learnData from './learnData.vue';
import { listTraining, listOfflineTraining, getTraining, getOfflineTraining, addTraining, updateTraining, delTraining, delOfflineTraining, updateTrainingStatus, updateOfflineTrainingStatus } from '@/api/main/training';
import type { TrainingVO, TrainingForm } from '@/api/main/training/types';

const loading = ref(false);
const total = ref(0);
const activeCategory = ref('video');
const showForm = ref(false);
const showLearnData = ref(false);
const currentTrain = ref<TrainingVO | null>(null);
const tableData = ref<TrainingVO[]>([]);

const categories = [
  { id: 'video', name: '视频培训', icon: 'VideoPlay' },
  { id: 'offline', name: '线下培训', icon: 'Location' },
  { id: 'live', name: '直播培训', icon: 'VideoCamera' }
];

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: '',
  trainingType: 'video'
});

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    queryParams.trainingType = activeCategory.value;
    const res = activeCategory.value === 'offline'
      ? await listOfflineTraining(queryParams)
      : await listTraining(queryParams);
    tableData.value = res.rows || [];
    total.value = res.total || 0;
  } catch (e) {
    console.error('查询培训列表失败', e);
  } finally {
    loading.value = false;
  }
};

/** 切换分类 */
const switchCategory = (id: string) => {
  activeCategory.value = id;
  queryParams.pageNum = 1;
  queryParams.name = '';
  getList();
};

/** 搜索 */
const handleQuery = () => {
  queryParams.pageNum = 1;
  getList();
};

const handleSizeChange = () => {
  queryParams.pageNum = 1;
  getList();
};
const handleCurrentChange = () => getList();

/** 新增 */
const handleAdd = () => {
  currentTrain.value = null;
  showForm.value = true;
};

/** 编辑 */
const handleEdit = async (row: TrainingVO) => {
  try {
    const res = activeCategory.value === 'offline'
      ? await getOfflineTraining(row.id)
      : await getTraining(row.id);
    currentTrain.value = res.data;
    showForm.value = true;
  } catch (e) {
    // 如果详情接口报错，用列表数据兜底
    currentTrain.value = { ...row };
    showForm.value = true;
  }
};

/** 表单提交 */
const handleFormSubmit = async (formData: TrainingForm) => {
  try {
    if (formData.id) {
      await updateTraining(formData);
      ElMessage.success('修改成功');
    } else {
      formData.trainingType = activeCategory.value;
      await addTraining(formData);
      ElMessage.success('创建成功');
    }
    showForm.value = false;
    getList();
  } catch (e) {
    console.error('提交失败', e);
  }
};

/** 数据/学习记录 */
const handleData = (row: TrainingVO) => {
  showLearnData.value = true;
  currentTrain.value = row;
};

/** Switch 状态变更 */
const handleStatusChange = async (row: TrainingVO) => {
  try {
    if (row.trainingType === 'offline') {
      await updateOfflineTrainingStatus(row.id, row.status);
    } else {
      await updateTrainingStatus(row.id, row.status);
    }
    ElMessage.success(row.status === 1 ? '上架成功' : '下架成功');
    getList();
  } catch (e) {
    // 恢复到之前的状态
    row.status = row.status === 1 ? 0 : 1;
    console.error('状态更新失败', e);
  }
};

/** 操作列的上架/下架按钮 */
const handleToggleStatus = (row: TrainingVO) => {
  const action = row.status === 1 ? '下架' : '上架';
  ElMessageBox.confirm(`确定${action}该课程吗？`, '提示', { type: 'warning' }).then(async () => {
    const newStatus = row.status === 1 ? 0 : 1;
    try {
      if (row.trainingType === 'offline') {
        await updateOfflineTrainingStatus(row.id, newStatus);
      } else {
        await updateTrainingStatus(row.id, newStatus);
      }
      ElMessage.success(`${action}成功`);
      getList();
    } catch (e) {
      console.error(`${action}失败`, e);
    }
  }).catch(() => {});
};

/** 删除 */
const handleDelete = (row: TrainingVO) => {
  ElMessageBox.confirm(
    '删除后将无法恢复，确定删除吗？',
    '删除培训',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      buttonSize: 'default'
    }
  ).then(async () => {
    try {
      if (row.trainingType === 'offline') {
        await delOfflineTraining(row.id);
      } else {
        await delTraining(row.id);
      }
      ElMessage.success('删除成功');
      getList();
    } catch (e) {
      console.error('删除失败', e);
    }
  }).catch(() => {});
};

/** 复制测评 */
const handleCopy = (row: TrainingVO) => {
  ElMessage.success('测评链接已复制');
};

/** 格式化时间范围 */
const formatTimeRange = (start?: string, end?: string) => {
  if (!start || !end) return '';
  return `${start} —— ${end}`;
};

onMounted(() => {
  getList();
});
</script>

<style scoped lang="scss">
.training-page {
  height: calc(100vh - 84px);
  padding: 20px;
  background-color: #f0f2f5;

  .main-wrapper {
    @media (max-width: 992px) {
      flex-direction: column;
      height: auto;
    }
  }

  .category-sidebar {
    width: 240px;
    height: 100%;
    @media (max-width: 992px) {
      width: 100%;
      height: auto;
      margin-bottom: 20px;
    }

    .category-list {
      .category-item {
        display: flex;
        align-items: center;
        padding: 12px 16px;
        cursor: pointer;
        border-radius: 4px;
        margin-bottom: 4px;
        transition: all 0.3s;
        color: #606266;

        &:hover {
          background-color: #f5f7fa;
        }

        &.active {
          background-color: #ecf5ff;
          color: #409eff;
          position: relative;
          
          &::before {
            content: '';
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 3px;
            height: 16px;
            background-color: #409eff;
            border-radius: 0 2px 2px 0;
          }
        }
      }
    }
  }

  .content-area {
    min-width: 0;
  }

  .search-input {
    :deep(.el-input-group__append) {
      background-color: #409eff;
      border-color: #409eff;
      color: #fff;
      padding: 0;
      .el-button {
        border: none;
        margin: 0;
        padding: 0 15px;
        color: #fff;
        &:hover {
          background-color: #66b1ff;
        }
      }
    }
  }

  .create-btn {
    background-color: #4079ff;
    border-color: #4079ff;
  }

  .video-thumb {
    width: 60px;
    height: 36px;
    background-color: #000;
    border-radius: 2px;
    overflow: hidden;
    position: relative;

    .play-overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0, 0, 0, 0.3);
      color: #fff;
      font-size: 16px;
    }
  }

  :deep(.custom-header th) {
    background-color: #f7f8fa !important;
    color: #4e5969;
    font-weight: 500;
    padding: 12px 0;
    border-bottom: none !important;
  }

  .custom-table {
    :deep(.el-table__inner-wrapper::before) {
      display: none;
    }
  }

  .operation-links {
    display: flex;
    gap: 12px;
    
    .delete-link {
      color: #409eff;
      &:hover {
        color: #f56c6c;
      }
    }
  }

  .pagination-wrapper {
    color: #606266;
    font-size: 14px;
    
    .total-text, .page-size-select {
      color: #606266;
    }

    :deep(.el-pagination) {
      --el-pagination-button-bg-color: #fff;
      --el-pagination-hover-color: #409eff;
      
      .el-pager li {
        &.is-active {
          background-color: #ecf5ff !important;
          color: #409eff !important;
          font-weight: bold;
        }
      }
    }
  }
}
</style>
