<template>
  <main class="safety-platform-container__main">
    <div class="page-container">
      <!-- 标题 -->
      <el-card shadow="never" class="mb-16">
        <h2 class="title">
          {{ details.trainingPlanName }}
        </h2>
        <div class="meta">
          <span>分类名称：{{ details.categoryName }}</span>
          <span>创建人：{{ details.createdByName }}</span>
          <span>创建时间：{{ details.createdAt }}</span>
        </div>
      </el-card>

      <!-- 基本信息 -->
      <el-card shadow="never" class="mb-16">
        <template #header>
          <strong>基本信息</strong>
        </template>

        <el-descriptions :column="2" border>
          <el-descriptions-item label="教育培训计划名称">
            {{ details.trainingPlanName }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag type="success">{{ details.statusName }}</el-tag>
          </el-descriptions-item>

          <el-descriptions-item label="培训对象">
            {{ details.trainingObject }}
          </el-descriptions-item>
          <el-descriptions-item label="培训人数"> {{ details.trainingCount }}人 </el-descriptions-item>

          <el-descriptions-item label="培训时间">
            {{ details.trainingTime }}
          </el-descriptions-item>
          <el-descriptions-item label="培训方式">
            {{ details.trainingMethod }}
          </el-descriptions-item>

          <el-descriptions-item label="考核方式">
            {{ details.assessmentMethod }}
          </el-descriptions-item>
          <el-descriptions-item label="培训责任部门">
            {{ details.deptName }}
          </el-descriptions-item>

          <el-descriptions-item label="学时"> {{ details.studyHours }} </el-descriptions-item>
          <el-descriptions-item label="培训分组">
            {{ details.groupName }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 培训课程信息 -->
      <el-card shadow="never">
        <template #header>
          <strong>培训课程信息</strong>
        </template>

        <!-- 查询区 -->
        <el-form :inline="true" class="mb-12">
          <el-form-item>
            <el-input v-model="tableQuery.queryParam.courseName" placeholder="搜索培训课程名称" clearable />
          </el-form-item>

          <el-form-item>
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSearch"> 查询 </el-button>
            <el-button type="primary" @click="handleAdd"> 新增课程 </el-button>
            <el-button @click="handleExport"> 导出 </el-button>
          </el-form-item>
        </el-form>

        <!-- 表格 -->
        <el-table :data="tableData" border stripe>
          <el-table-column prop="id" label="编号" width="80" fixed="left" />
          <el-table-column prop="courseName" label="培训课程名称" width="240" fixed="left" />
          <el-table-column prop="trainingDate" width="230" label="培训时间" />
          <el-table-column prop="courseTypeName" label="课程所属分类" width="180" />
          <el-table-column prop="trainingMethod" label="培训方式" width="120" />
          <!-- <el-table-column prop="courseIntroduction" label="培训课程简述" /> -->
          <el-table-column prop="trainingTeacher" label="培训课程讲师" width="140" />
          <el-table-column prop="groupOfParticipantsDesc" label="计划参与人数所属分组" width="200" />
          <el-table-column prop="planNumOfParticipants" label="计划参与人数" width="140" />
          <el-table-column prop="signInNum" label="签到人数" width="120" />

          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <el-button link type="primary" @click="handleEdit(row)"> 编辑 </el-button>
              <el-button link type="danger" @click="handleDelete(row)"> 删除 </el-button>
              <el-button link @click="handleView(row)"> 查看 </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="page.current"
            v-model:page-size="page.size"
            :page-sizes="[10, 20, 50, 100]"
            :total="page.total"
            layout="total, sizes, prev, pager, next, jumper"
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
          />
        </div>
      </el-card>
    </div>
    <AddTrainingInformation :state="type" v-model:visible="showAddTrainingInfo" :currentId="currentTableId" @save-success="handleSearch" />
  </main>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import {
    queryTrainingTableData,
    queryEducationAndTrainingProgramDetail,
    deleteTrainingInformation,
    type TableParamsType,
  } from '@/api/production-education-training-plan-dept';
  import AddTrainingInformation from './addTrainingInformation.vue';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { id, pa } from 'element-plus/es/locale';
  const router = useRouter();
  const route = useRoute();

  const operate = computed(() => (route.query.operate as string) || 'education-training-plan-management-dept-view');
  const currentId = computed(() => Number(route.query.id));

  const isViewMode = computed(() => operate.value === 'education-training-plan-management-dept-view');
  const query = ref({
    name: '',
    time: [],
  });
  const details = reactive({
    trainingPlanName: '',
    categoryName: '',
    trainingObject: '',
    trainingCount: '',
    trainingTime: '',
    trainingMethod: '',
    assessmentMethod: '',
    responsibleNames: '',
    studyHours: '',
    groupName: '',
    statusName: '',
    createdByName: '',
    createdAt: '',
    deptName: '',
  });
  const page = ref({
    current: 1,
    size: 10,
    total: 0,
  });

  const tableData = ref([]);
  const type = ref('add');
  const showAddTrainingInfo = ref(false);
  const currentTableId = ref('');
  // 搜索和筛选相关
  const dateRange = ref([]);

  const tableQuery = reactive<QueryPageRequest<TableParamsType>>({
    pageNumber: page.value.current,
    pageSize: page.value.size,
    queryParam: {
      petpiId: currentId.value,
      courseName: '',
      dateStart: dateRange.value[0],
      dateEnd: dateRange.value[1],
    },
  });

  const handlePageChange = (current) => {
    page.value.current = current;
    getTableList();
  };

  const handleSizeChange = (size) => {
    page.value.size = size;
    page.value.current = 1;
    getTableList();
  };

  const handleSearch = () => {
    page.value.current = 1;
    tableQuery.pageNumber = 1;
    getTableList();
  };

  const handleExport = () => {
    ElMessage.success('点击了导出');
  };

  const handleAdd = () => {
    type.value = 'add';
    currentTableId.value = String(currentId.value);
    showAddTrainingInfo.value = true;
  };

  const handleEdit = (row) => {
    type.value = 'edit';
    currentTableId.value = row.id;
    showAddTrainingInfo.value = true;
  };

  const handleView = (row) => {
    type.value = 'view';
    currentTableId.value = row.id;
    showAddTrainingInfo.value = true;
  };

  const handleDelete = (row) => {
    ElMessageBox.confirm(`确认删除课程「${row.courseName}」吗？`, '提示', { type: 'warning' }).then(async () => {
      await deleteTrainingInformation(row.id);
      // 删除操作逻辑
      ElMessage.success('删除成功');
      getTableList(); // 重新获取列表数据
    });
  };
  const getTableList = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryTrainingTableData(tableQuery);
      if (res) {
        tableData.value = res.records || [];
        page.value.total = res.total || 0;
      }
    } catch (e) {
      ElMessage.error('获取培训课程列表失败');
    }
  };
  const getDetail = async () => {
    if (!currentId.value) return;
    try {
      const res = await queryEducationAndTrainingProgramDetail(currentId.value);
      if (res) {
        Object.assign(details, res);
      }
    } catch (e) {
      ElMessage.error('获取详情失败');
    }
  };

  onMounted(() => {
    getDetail();
    getTableList();
  });
</script>

<style scoped lang="scss">
  @use '@/styles/page-details-layout.scss' as *;

  .page-container {
    padding: 16px;
  }

  .pagination {
    width: 100%;
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .title {
    margin: 0 0 8px;
  }

  .meta {
    font-size: 13px;
    color: #666;
    display: flex;
    gap: 24px;
    margin-top: 20px;
  }

  .mb-12 {
    margin-bottom: 12px;
  }

  .mb-16 {
    margin-bottom: 16px;
  }
</style>
