<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>

        <!-- 查询区 -->
        <div  style="margin-bottom: 20px" v-if="details.status < 3">
            <el-button type="primary" :icon="Plus" @click="handleAdd"> 新增课程 </el-button>
        </div>
        <el-form :inline="true" class="mb-12 flex align-middle act-search">
            <section class="select-box">
                <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="结束时间"
                        value-format="YYYY-MM-DD"
                        format="YYYY-MM-DD"
                    />
                </el-form-item>
            </section>
          <el-form-item class="search-btn">
            <el-button type="primary" @click="handleSearch"> 查询 </el-button>
            <el-button @click="handleReset"> 重置 </el-button>
            <el-button @click="handleExport"> 导出 </el-button>
          </el-form-item>
        </el-form>

        <!-- 表格 -->
         <div class="batch-table">
          <BasicTable
            ref="basicTableRef"
            :tableData="tableData"
            :tableConfig="tableConfig"
            @update:pageSize="handleSizeChange"
            @update:pageNumber="handleCurrentChange"
          >
            <template #action="scope">
              <div class="action-container--div" style="justify-content: left">
                <el-button link type="primary" @click="handleEdit(scope.row)"> 编辑 </el-button>
                <el-button link type="primary" @click="handleDelete(scope.row)"> 删除 </el-button>
                <el-button link type="primary" @click="handleView(scope.row)"> 查看 </el-button>
              </div>
            </template>
          </BasicTable>
        </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,
    exportEducationTrainingPlanCourseData,
    type TableParamsType,
  } from '@/api/production-education-training-plan-dept';
  import AddTrainingInformation from './addTrainingInformation.vue';
  import type { QueryPageRequest } from '@/types/basic-query';
  import { downloadByData } from '@/utils/file/download';
  import { Plus } from '@element-plus/icons-vue';
  import BasicTable from '@/components/BasicTable.vue';
  import useTableConfig from '@/hooks/useTableConfigHook';
  import { TABLE_OPTIONS, COURSE_TABLE_COLUMNS } from '../configs/tables';

  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 details = reactive({
    trainingPlanName: '',
    categoryName: '',
    trainingObject: '',
    trainingCount: '',
    trainingTime: '',
    trainingMethod: '',
    assessmentMethod: '',
    responsibleNames: '',
    studyHours: '',
    groupName: '',
    statusName: '',
    createdByName: '',
    createdAt: '',
    deptName: '',
    status: 0
  });

  // 表格
  const basicTableRef = ref<InstanceType<typeof BasicTable>>();

  const { tableConfig, pagination } = useTableConfig(COURSE_TABLE_COLUMNS, TABLE_OPTIONS);

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

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

  const handleCurrentChange = (value: number) => {
    pagination.pageNumber = value;
    tableQuery.pageNumber = value;
    getTableList();
  };

  const handleSizeChange = (value: number) => {
    pagination.pageSize = value;
    tableQuery.pageSize = value;
    getTableList();
  };

  const handleSearch = () => {
    showAddTrainingInfo.value = false
    pagination.pageNumber = 1;
    tableQuery.pageNumber = 1;
    getTableList();
  };
  const handleReset = ()=>{
    pagination.pageNumber = 1;
    pagination.pageSize = 20;
    Object.assign(tableQuery, {
      pageNumber: 1,
      pageSize: pagination.pageSize,
      queryParam: {
        petpiId: currentId.value,
        courseName: undefined,
        dateStart: undefined,
        dateEnd: undefined,
      },
    });
    dateRange.value = [];
    handleSearch();
  }
  const handleExport = async () => {
    try {
      const response = await exportEducationTrainingPlanCourseData(tableQuery.queryParam)
      if (response) {
          const fileName = `培训课程信息_${new Date().toISOString().split('T')[0]}.xlsx`;
          downloadByData(response, fileName);
          ElMessage.success('导出成功');
      }
    } catch (e) {
      console.error('导出培训课程信息失败:', e);
      ElMessage.error('导出失败，请重试');
    }
  };

  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 () => {
    tableConfig.loading = true;
    if (!currentId.value) return;
    try {
      tableQuery.queryParam.dateStart = dateRange.value ? dateRange.value[0]: undefined
      tableQuery.queryParam.dateEnd = dateRange.value ? dateRange.value[1]: undefined
      const res = await queryTrainingTableData(tableQuery);
      if (res) {
        tableData.value = res.records || [];
        pagination.total = res.totalRow;
      }
    } catch (e) {
      tableData.value = [];
      pagination.total = 0;
    } finally {
      tableConfig.loading = false;
    }
  };
  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;
  }
  .align-middle {
    justify-content: space-between;
  }

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