<template>
  <div class="app-container learn-data-page bg-white p-6 rounded">
    <div class="header-bar flex justify-between items-center mb-6">
      <div class="flex items-center">
        <el-button link @click="handleBack" class="mr-4 text-gray-600" style="width:60px; height: 30px;">
          <el-icon><i-ep-arrow-left /></el-icon>
          返回
        </el-button>
        <span class="font-bold text-lg text-gray-800">学习数据</span>
      </div>
      <el-button type="default" :disabled="selectedIds.length === 0" @click="handleExport">批量导出</el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      header-cell-class-name="custom-header"
      class="custom-table"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="用户信息" min-width="200">
        <template #default="scope">
          <div class="flex items-center">
            <el-avatar :size="36" :src="scope.row.avatarUrl || scope.row.avatar" class="mr-3 shrink-0" />
            <div class="user-info flex flex-col justify-center">
              <div class="name font-medium text-blue-500 cursor-pointer text-sm mb-1">{{ scope.row.name }}</div>
              <div class="mobile text-gray-500 text-xs">{{ scope.row.mobile }}</div>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="!isOffline" label="已学习时长 (分钟)" width="150" align="center">
        <template #default="scope">{{ formatMinutes(scope.row.learnedTime) }}</template>
      </el-table-column>
      <el-table-column v-if="!isOffline" label="剩余时长 (分钟)" width="150" align="center">
        <template #default="scope">{{ formatMinutes(scope.row.remainingTime) }}</template>
      </el-table-column>
      <el-table-column v-if="!isOffline" label="学习进度" min-width="200">
        <template #default="scope">
          <div class="flex items-center gap-3">
            <el-progress 
              :percentage="calculateProgress(scope.row)" 
              :stroke-width="8" 
              color="#67c23a" 
              class="flex-1" 
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column v-if="!isOffline" label="完成时间" prop="finishTime" width="180" align="center" />
      <el-table-column v-if="!isOffline" label="上次学习时间" prop="lastLearnTime" width="180" align="center" />
      <el-table-column v-if="isOffline" label="报名时间" prop="enrollTime" width="180" align="center" />
      <el-table-column v-if="isOffline" label="签到时间" prop="checkInTime" width="180" align="center">
        <template #default="scope">
          {{ scope.row.checkInTime || '-' }}
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper mt-8 text-gray-500 text-sm">
      <div class="page-total text-gray-400 mb-4 text-center">
        共 {{ total }} 条记录 第 {{ queryParams.pageNum }} / {{ Math.max(1, Math.ceil(total / queryParams.pageSize)) }} 页
      </div>
      <div class="pagination-center">
        <el-pagination
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          :total="total"
          background
          layout="prev, pager, next, sizes, jumper"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, reactive, onMounted, watch } from 'vue';
import FileSaver from 'file-saver';
import { ElMessage } from 'element-plus';
import { listTrainingLearnRecords, listOfflineTrainingParticipants, exportTrainingLearnRecords, exportOfflineTrainingParticipants } from '../../../api/main/training/index';
import type { TrainingParticipantVO, TrainingLearnRecordVO } from '../../../api/main/training/types';

const props = defineProps<{
  trainId?: string | number;
  trainName?: string;
  trainType?: string;
}>();

const emit = defineEmits(['back']);

const loading = ref(false);
const total = ref(0);
const isOffline = computed(() => props.trainType === 'offline');
const selectedIds = ref<Array<string | number>>([]);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10
});

const formatMinutes = (value?: number) => {
  return Number(value || 0);
};

const calculateProgress = (row: TrainingLearnRecordVO) => {
  const learned = Number(row.learnedTime) || 0;
  const remaining = Number(row.remainingTime) || 0;
  const totalTime = learned + remaining;
  if (totalTime === 0) return 0;
  return Math.max(0, Math.min(100, Math.floor((learned / totalTime) * 100)));
};

const tableData = ref<Array<TrainingParticipantVO | TrainingLearnRecordVO>>([]);

const handleBack = () => {
  emit('back');
};

const handleExport = async () => {
  if (!props.trainId || selectedIds.value.length === 0) {
    ElMessage.warning('请先勾选需要导出的数据');
    return;
  }
  const fileName = `${props.trainName || '学习数据'}_${new Date().getTime()}.xlsx`;
  const blob = isOffline.value
    ? await exportOfflineTrainingParticipants(props.trainId, selectedIds.value)
    : await exportTrainingLearnRecords(props.trainId, selectedIds.value);
  FileSaver.saveAs(blob as unknown as Blob, fileName);
  ElMessage.success('导出成功');
};

const handleSelectionChange = (selection: Array<TrainingParticipantVO | TrainingLearnRecordVO>) => {
  selectedIds.value = selection.map(item => item.studentId!).filter(Boolean);
};

const handleSizeChange = (size: number) => {
  queryParams.pageSize = size;
  queryParams.pageNum = 1;
  getList();
};

const handleCurrentChange = (page: number) => {
  queryParams.pageNum = page;
  getList();
};

const getList = async () => {
  if (!props.trainId) {
    tableData.value = [];
    total.value = 0;
    return;
  }
  loading.value = true;
  try {
    if (isOffline.value && props.trainId) {
      const res: any = await listOfflineTrainingParticipants(props.trainId, queryParams);
      tableData.value = (res.rows || []) as TrainingParticipantVO[];
      total.value = res.total || 0;
      selectedIds.value = [];
      return;
    }
    const res: any = await listTrainingLearnRecords(props.trainId, queryParams);
    tableData.value = (res.rows || []).map((item: TrainingLearnRecordVO) => ({
      ...item,
      progress: calculateProgress(item)
    }));
    total.value = res.total || 0;
    selectedIds.value = [];
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  getList();
});

watch(() => [props.trainId, props.trainType, queryParams.pageNum, queryParams.pageSize], () => {
  getList();
});
</script>

<style scoped lang="scss">
.learn-data-page {
  min-height: calc(100vh - 84px);
  display: flex;
  flex-direction: column;
  
  .header-bar {
    .el-button {
      border-color: #dcdfe6;
      color: #606266;
    }
  }

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

  .custom-table {
    :deep(.el-table__inner-wrapper::before) {
      display: none;
    }
    :deep(.el-table__row) {
      td {
        border-bottom: 1px solid #ebeef5;
      }
    }
  }

  :deep(.el-progress-bar__outer) {
    background-color: #f2f3f5;
  }

  .pagination-wrapper {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: auto;
    margin-bottom: 40px;

    .page-total {
      width: 100%;
      text-align: left;
      margin-bottom: -20px;
    }

    .pagination-center {
      display: flex;
      justify-content: center;
      width: 100%;
    }

    :deep(.el-pagination) {
      justify-content: center;
      .el-pagination__sizes {
        margin-right: 16px;
      }
      .el-pagination__jump {
        margin-left: 16px;
      }
    }
  }
}
</style>
