<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

// 抽屉可见性
const drawerVisible = ref(false);

// 考试设置表单数据
const examForm = reactive({
  name: '',
  category: '',
  description: '',
  totalScore: '',
  passingScore: '',
  startTime: '',
  endTime: '',
  duration: '',
  executorCount: 23, // 模拟已选择23人
});

// 考试分类选项
const categoryOptions = [
  { label: '基础知识', value: 'basic' },
  { label: '框架知识', value: 'framework' },
  { label: '前端基础', value: 'frontend' },
  { label: '后端基础', value: 'backend' },
  { label: '综合测试', value: 'comprehensive' },
];

// 试卷分类选项
const paperCategoryOptions = [
  { label: '基础知识', value: 'basic' },
  { label: '框架知识', value: 'framework' },
  { label: '前端基础', value: 'frontend' },
  { label: '后端基础', value: 'backend' },
  { label: '综合测试', value: 'comprehensive' },
];

// 试卷名称选项
const paperNameOptions = [
  { label: '基础知识测试卷', value: '1', category: '基础知识', creator: '管理员', totalScore: 100, questionCount: 20, updateDate: '2024-01-15' },
  { label: 'Vue框架测试卷', value: '2', category: '框架知识', creator: '教师1', totalScore: 120, questionCount: 25, updateDate: '2024-01-16' },
  { label: '前端综合测试卷', value: '3', category: '前端基础', creator: '教师2', totalScore: 150, questionCount: 30, updateDate: '2024-01-17' },
  { label: '后端综合测试卷', value: '4', category: '后端基础', creator: '教师3', totalScore: 120, questionCount: 25, updateDate: '2024-01-18' },
  { label: '全栈综合测试卷', value: '5', category: '综合测试', creator: '管理员', totalScore: 200, questionCount: 40, updateDate: '2024-01-19' },
];

// 已选择的试卷
const selectedPapers = ref([
  { id: '1', name: '基础知识测试卷', category: '基础知识', creator: '管理员', totalScore: 100, questionCount: 20, updateDate: '2024-01-15' },
  { id: '2', name: 'Vue框架测试卷', category: '框架知识', creator: '教师1', totalScore: 120, questionCount: 25, updateDate: '2024-01-16' },
]);

// 选中的试卷分类
const selectedPaperCategory = ref('');

// 选中的试卷名称
const selectedPaperNames = ref([]);

// 打开抽屉
const openDrawer = () => {
  drawerVisible.value = true;
};

// 关闭抽屉
const closeDrawer = () => {
  drawerVisible.value = false;
};

// 执行人选择弹框可见性
const executorDialogVisible = ref(false);

// 执行人树数据
const executorTreeData = ref([
  {
    label: '部门一',
    value: 'dept1',
    children: [
      {
        label: '组1',
        value: 'group1',
        children: [
          { label: '张三', value: 'user1' },
          { label: '张三', value: 'user2' },
          { label: '张三', value: 'user3' },
          { label: '张三', value: 'user4' },
          { label: '张三', value: 'user5' },
          { label: '张三', value: 'user6' },
          { label: '张三', value: 'user7' },
          { label: '张三', value: 'user8' },
          { label: '张三', value: 'user9' },
          { label: '张三', value: 'user10' },
          { label: '张三', value: 'user11' },
          { label: '张三', value: 'user12' },
          { label: '张三', value: 'user13' },
          { label: '张三', value: 'user14' },
          { label: '张三', value: 'user15' },
        ],
      },
      {
        label: '组2',
        value: 'group2',
        children: [],
      },
    ],
  },
  {
    label: '部门二',
    value: 'dept2',
    children: [
      {
        label: '组1',
        value: 'group3',
        children: [
          { label: '1-1-1-1-1', value: 'user16' },
        ],
      },
    ],
  },
]);

// 已选择的执行人
const selectedExecutors = ref(['dept1', 'group1', 'user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9', 'user10', 'user11', 'user12', 'user13', 'user14', 'user15']);

// 选择考试执行人
const selectExecutors = () => {
  executorDialogVisible.value = true;
};

// 提交执行人选择
const submitExecutorSelection = () => {
  // 统计已选择的用户数量
  const getUserCount = (nodes, selectedKeys) => {
    let count = 0;
    nodes.forEach(node => {
      if (node.children && node.children.length > 0) {
        count += getUserCount(node.children, selectedKeys);
      } else if (selectedKeys.includes(node.value)) {
        count++;
      }
    });
    return count;
  };
  
  const userCount = getUserCount(executorTreeData.value, selectedExecutors.value);
  examForm.executorCount = userCount;
  executorDialogVisible.value = false;
  ElMessage.success('已选择' + userCount + '人');
};

// 取消执行人选择
const cancelExecutorSelection = () => {
  executorDialogVisible.value = false;
};

// 删除已选择的试卷
const removePaper = (id) => {
  selectedPapers.value = selectedPapers.value.filter(paper => paper.id !== id);
};

// 发布考试
const publishExam = () => {
  // 表单验证
  if (!examForm.name) {
    ElMessage.error('请输入考试名称');
    return;
  }
  if (!examForm.category) {
    ElMessage.error('请选择考试分类');
    return;
  }
  if (!examForm.totalScore) {
    ElMessage.error('请输入考试总分');
    return;
  }
  if (!examForm.passingScore) {
    ElMessage.error('请输入及格分');
    return;
  }
  if (!examForm.startTime || !examForm.endTime) {
    ElMessage.error('请选择考试时间');
    return;
  }
  if (!examForm.duration) {
    ElMessage.error('请输入答卷时长');
    return;
  }
  if (selectedPapers.value.length === 0) {
    ElMessage.error('请选择至少一张试卷');
    return;
  }
  
  // 模拟发布考试
  console.log('发布考试:', examForm);
  console.log('选择的试卷:', selectedPapers.value);
  ElMessage.success('考试发布成功');
  closeDrawer();
};

// 监听试卷名称选择变化
const handlePaperNameChange = (values) => {
  // 模拟根据选择的试卷名称获取试卷信息
  selectedPapers.value = paperNameOptions
    .filter(paper => values.includes(paper.value))
    .map(paper => ({
      id: paper.value,
      name: paper.label,
      category: paper.category,
      creator: paper.creator,
      totalScore: paper.totalScore,
      questionCount: paper.questionCount,
      updateDate: paper.updateDate,
    }));
};

// 暴露方法给父组件
defineExpose({
  openDrawer,
});
</script>

<template>
  <div>
    <!-- 发布考试抽屉 -->
    <el-drawer
      v-model="drawerVisible"
      title="发布考试"
      size="1200px"
      destroy-on-close
    >
      <div class="exam-publish-drawer">
        <!-- 第一部分：考试设置 -->
        <div class="exam-setting-section">
          <h3 class="section-title">考试设置</h3>
          
          <el-form
            :model="examForm"
            label-position="top"
            class="grid-cols-1 md:grid-cols-2 gap-4">
            <!-- 考试名称 -->
            <el-form-item label="考试名称" class="form-item-with-border">
              <el-input
                v-model="examForm.name"
                placeholder="请输入考试名称"
                maxlength="30"
                show-word-limit
              />
            </el-form-item>
            
            <!-- 考试分类 -->
            <el-form-item label="考试分类" class="form-item-with-border">
              <el-select
                v-model="examForm.category"
                placeholder="请选择考试分类"
                style="width: 100%"
              >
                <el-option
                  v-for="option in categoryOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            
            <!-- 考试说明 -->
            <el-form-item label="考试说明" class="form-item-with-border md:col-span-2">
              <el-input
                v-model="examForm.description"
                type="textarea"
                placeholder="请输入考试说明"
                rows="3"
              />
            </el-form-item>
            
            <!-- 考试总分 -->
            <el-form-item label="考试总分" class="form-item-with-border">
              <el-input
                v-model="examForm.totalScore"
                placeholder="请输入考试总分"
                type="number"
                min="1"
              >
                <template #append>分</template>
              </el-input>
            </el-form-item>
            
            <!-- 及格分 -->
            <el-form-item label="及格分" class="form-item-with-border">
              <el-input
                v-model="examForm.passingScore"
                placeholder="请输入及格分"
                type="number"
                min="1"
              >
                <template #append>分</template>
              </el-input>
            </el-form-item>
            
            <!-- 考试时间 -->
            <el-form-item label="考试时间" class="form-item-with-border">
              <el-date-picker
                v-model="examForm.startTime"
                type="datetime"
                placeholder="开始时间"
                style="width: calc(50% - 15px)"
              />
              <span style="margin: 0 6px;">至</span>
              <el-date-picker
                v-model="examForm.endTime"
                type="datetime"
                placeholder="结束时间"
                style="width: calc(50% - 15px)"
              />
            </el-form-item>
            
            <!-- 答卷时长 -->
            <el-form-item label="答卷时长" class="form-item-with-border">
              <el-input
                v-model="examForm.duration"
                placeholder="请输入答卷时长"
                type="number"
                min="1"
              >
                <template #append>分钟</template>
              </el-input>
            </el-form-item>
            
            <!-- 考试执行人 -->
            <el-form-item label="考试执行人" class="form-item-with-border md:col-span-2">
              <el-button @click="selectExecutors">
                选择考试执行人
              </el-button>
              <span style="margin-left: 10px; color: #86909c;">已选择{{ examForm.executorCount }}人</span> 
            </el-form-item>
          </el-form>
        </div>
        
        <!-- 第二部分：选择试卷 -->
        <div class="select-paper-section">
          <h3 class="section-title">选择试卷</h3>
          
          <div class="grid-cols-1 md:grid-cols-2 gap-4 mb-4">
            <!-- 选择试卷分类 -->
            <el-form-item label="选择试卷分类" class="form-item-with-border">
              <el-select
                v-model="selectedPaperCategory"
                placeholder="请选择试卷分类"
                filterable
                allow-create
                default-first-option
                style="width: 100%"
              >
                <el-option
                  v-for="option in paperCategoryOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
            
            <!-- 选择试卷名称 -->
            <el-form-item label="选择试卷名称" class="form-item-with-border">
              <el-select
                v-model="selectedPaperNames"
                multiple
                filterable
                allow-create
                default-first-option
                placeholder="请选择试卷名称"
                style="width: 100%"
                @change="handlePaperNameChange"
              >
                <el-option
                  v-for="option in paperNameOptions"
                  :key="option.value"
                  :label="option.label"
                  :value="option.value"
                />
              </el-select>
            </el-form-item>
          </div>
          
          <!-- 选择的试卷列表 -->
          <div class="selected-papers-list" v-if="selectedPapers.length > 0">
            <el-table :data="selectedPapers" style="width: 100%" :header-cell-style="{ backgroundColor: '#F7F9FA', color: '#000' }">
              <el-table-column prop="name" label="试卷名称" min-width="200" />
              <el-table-column prop="category" label="类别" min-width="120" />
              <el-table-column prop="creator" label="创建人" min-width="120" />
              <el-table-column prop="totalScore" label="试卷总分" min-width="100" />
              <el-table-column prop="questionCount" label="试题总数" min-width="100" />
              <el-table-column prop="updateDate" label="更新日期" min-width="120" />
              <el-table-column label="操作" width="80" fixed="right">
                <template #default="{ row }">
                  <el-button
                    link
                    type="warning"
                    size="small"
                    @click="removePaper(row.id)"
                    class="custom-delete-btn"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
        
        <!-- 操作按钮 -->
        <div class="action-buttons">
          <el-button @click="closeDrawer">取消</el-button>
          <el-button type="primary" @click="publishExam">发布</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 选择考试执行人弹框 -->
    <el-dialog
      v-model="executorDialogVisible"
      :title="`考试执行人 已选择 ${examForm.executorCount} 人`"
      width="400px"
      top="200px"
      append-to-body
    >
      <el-tree
        v-model="selectedExecutors"
        :data="executorTreeData"
        show-checkbox
        node-key="value"
        default-expand-all
        style="max-height: 500px; overflow-y: auto;"
      />
      <template #footer>
        <div style="display: flex; gap: 12px; justify-content: flex-end;">
          <el-button @click="cancelExecutorSelection">取消</el-button>
          <el-button type="primary" @click="submitExecutorSelection">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.exam-publish-drawer {
  padding: 20px;
}

:deep(.el-drawer__header) {

  .el-drawer__title {
    color: #000;
  }
}

.section-title {
  position: relative;
  padding-left: 12px;
  margin-bottom: 20px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  
  &::before {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    width: 3px;
    content: '';
    background-color: #409eff;
    border-radius: 2px;
  }
}

:deep(.form-item-with-border) {
  .el-form-item__label {
    position: relative;
    padding-left: 12px;
    font-weight: 500;
    color: #000;
    
  }
}

.grid-cols-1 {
  display: grid;
  grid-template-columns: 1fr;
}

.md\:grid-cols-2 {
  @media (min-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.md\:col-span-2 {
  @media (min-width: 768px) {
    grid-column: span 2;
  }
}

.gap-4 {
  gap: 1rem;
}

.mb-4 {
  margin-bottom: 1rem;
}

.action-buttons {
  display: flex;
  gap: 12px;
  justify-content: flex-start;
  margin-top: 30px;
}

.selected-papers-list {
  margin-top: 20px;
}

.custom-delete-btn {
  color: #F0864D;
}
</style>
