<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!-- 分类树 -->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <div class="tree-header">
            <span>测评分类</span>
            <el-button link type="primary" :icon="Plus" @click="handleCategoryAdd"></el-button>
          </div>
          <el-tree
            :data="categoryOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="categoryTreeRef"
            node-key="id"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span class="tree-label">{{ node.label }}</span>
                <span class="tree-btn-group">
                  <el-button link type="primary" :icon="Edit" @click.stop="handleCategoryEdit(data)"></el-button>
                  <el-button link type="danger" :icon="Minus" @click.stop="handleCategoryDelete(data)"></el-button>
                  <el-button link type="primary" :icon="Plus" @click.stop="handleCategoryAdd(data)"></el-button>
                  <el-button link type="primary" :icon="Rank" class="drag-handler"></el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </div>
      </el-col>

      <!-- 题目列表 -->
      <el-col :span="20" :xs="24">
        <div class="search-container mb20">
          <div class="search-left">
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" class="search-form">
              <el-form-item label="" prop="questionTitle">
                <el-input
                  v-model="queryParams.questionTitle"
                  placeholder="请输入题目名称"
                  clearable
                  style="width: 240px"
                  @keyup.enter="handleQuery"
                  class="search-input"
                >
                  <template #suffix>
                    <el-icon class="search-icon" @click="handleQuery"><Search /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="" prop="questionType">
                <el-select v-model="queryParams.questionType" placeholder="题型选择" clearable style="width: 120px">
                  <el-option label="单选题" value="1" />
                  <el-option label="多选题" value="2" />
                  <el-option label="问答题" value="3" />
                </el-select>
              </el-form-item>
              <el-form-item label="" prop="abilityId">
                <el-select v-model="queryParams.abilityId" placeholder="测评能力" clearable style="width: 120px">
                  <el-option
                    v-for="item in abilityOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>

          <div class="operation-group">
            <el-button link type="primary" class="link-btn" @click="handleBatchMove">批量移动</el-button>
            <el-button link type="primary" class="link-btn" @click="handleLevelConfig">级别配置</el-button>
            <el-button type="primary" :icon="Plus" class="add-btn" @click="handleAdd">添加</el-button>
            <el-button plain type="primary" class="import-btn" @click="handleImport">批量导入</el-button>
            <el-button plain type="primary" class="delete-batch-btn" :disabled="multiple" @click="handleDelete">批量删除</el-button>
          </div>
        </div>

        <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange" class="question-table">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="题目名称" align="left" prop="questionTitle" :show-overflow-tooltip="true" />
          <el-table-column label="题型" align="center" prop="questionType" width="100">
            <template #default="scope">
              <span v-if="scope.row.questionType == '1'">单选题</span>
              <span v-else-if="scope.row.questionType == '2'">多选题</span>
              <span v-else-if="scope.row.questionType == '3'">问答题</span>
            </template>
          </el-table-column>
          <el-table-column label="回答次数" align="center" prop="answerCount" width="100" />
          <el-table-column label="错误率" align="center" prop="errorRate" width="100" />
          <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
          <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
            <template #default="scope">
              <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button link type="primary" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 级别配置对话框 -->
    <el-dialog title="岗位级别设置" v-model="levelOpen" width="800px" append-to-body>
      <el-table :data="levelList">
        <el-table-column label="级别" prop="levelName" />
        <el-table-column label="说明" prop="remark" />
        <el-table-column label="题目数" prop="questionCount" />
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleGroupConfig(scope.row)">组题配置</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="levelOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitLevelConfig">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 组题配置对话框 -->
    <el-dialog title="组题配置" v-model="groupOpen" width="900px" append-to-body>
      <div class="group-config-header mb20">
        <span>岗位级别：{{ currentLevel.levelName }}</span>
      </div>
      <el-table :data="groupList" border>
        <el-table-column label="岗位类别" width="100">
          <template #default="scope">
            {{ scope.row.categoryName || '岗位类别' + (scope.$index + 1) }}
          </template>
        </el-table-column>
        <el-table-column label="组题能力" min-width="200">
          <template #default="scope">
             <el-cascader
              v-model="scope.row.abilityIds"
              :options="categoryOptions"
              :props="{ label: 'label', value: 'id', children: 'children', multiple: true }"
              placeholder="请选择能力"
              style="width: 100%"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column label="出题数" width="150">
          <template #default="scope">
            <el-input-number v-model="scope.row.questionCount" :min="1" size="small" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template #default="scope">
            <el-button link type="danger" :icon="Close" @click="removeGroup(scope.$index)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="mt10">
        <el-button type="primary" link icon="Plus" @click="addGroup">继续配置</el-button>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="groupOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitGroupConfig">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Question">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue';
import { useRouter } from 'vue-router';
import { Plus, Edit, Minus, Search, Delete, Download, Close, Rank } from '@element-plus/icons-vue';
import { listQuestion, delQuestion, getCategoryTree, getLevelConfig, saveLevelConfig } from '@/api/system/question';
import { ElMessageBox, ElMessage } from 'element-plus';

const router = useRouter();
const { proxy } = getCurrentInstance();

const categoryTreeRef = ref();

/** 过滤节点 */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.includes(value);
};

const questionList = ref([]);
const categoryOptions = ref([]);
const abilityOptions = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const multiple = ref(true);
const levelOpen = ref(false);
const groupOpen = ref(false);
const levelList = ref([]);
const groupList = ref([]);
const currentLevel = ref({});

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  questionTitle: undefined,
  questionType: undefined,
  abilityId: undefined,
  categoryId: undefined
});

const defaultProps = {
  children: 'children',
  label: 'label'
};

/** 查询题目列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    // 模拟数据用于演示，如果接口不通
    questionList.value = [
      { id: 1, questionTitle: '下列各项中，不属于注册会计师执行财务报表审计的“总体目标”的是？', questionType: '1', answerCount: 1243, errorRate: '10%', createTime: '2021-02-28 10:30', updateTime: '2021-02-28 10:30' },
      { id: 2, questionTitle: '注册会计师函证应收账款的主要目的是验证', questionType: '2', answerCount: 1243, errorRate: '10%', createTime: '2021-02-28 10:30', updateTime: '2021-02-28 10:30' },
      { id: 3, questionTitle: '在了解被审计单位及其环境时，注册会计师应当从哪些方面评估重大错...', questionType: '3', answerCount: 1243, errorRate: '10%', createTime: '2021-02-28 10:30', updateTime: '2021-02-28 10:30' }
    ];
    total.value = 3;
  });
}

/** 查询分类树 */
function getTree() {
  getCategoryTree().then(response => {
    categoryOptions.value = response.data;
  }).catch(() => {
    // 模拟分类树
    categoryOptions.value = [
      { id: 1, label: 'A1', children: [{ id: 11, label: '能力1' }, { id: 12, label: '能力2' }, { id: 13, label: '能力3', children: [{ id: 131, label: '能力3-1' }, { id: 132, label: '能力3-2' }] }] },
      { id: 2, label: 'A2' },
      { id: 3, label: 'A3' }
    ];
  });
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.categoryId = data.id;
  handleQuery();
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection) {
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  router.push('/system/question/detail');
}

/** 修改按钮操作 */
function handleUpdate(row) {
  router.push({
    path: '/system/question/detail',
    query: { id: row.id }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const ids = row.id || proxy.getSelectIds(questionList.value, 'id');
  ElMessageBox.confirm('删除后不可恢复，确认要删除吗？', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
    icon: 'Warning'
  }).then(() => {
    // return delQuestion(ids);
    ElMessage.success('删除成功');
    getList();
  }).catch(() => {});
}

/** 级别配置 */
function handleLevelConfig() {
  levelOpen.value = true;
  getLevelConfig().then(response => {
    levelList.value = response.data;
  }).catch(() => {
    levelList.value = [
      { levelName: 'A1', remark: '说明2123', questionCount: 12, groups: [] }
    ];
  });
}

/** 组题配置 */
function handleGroupConfig(row) {
  currentLevel.value = row;
  groupList.value = row.groups && row.groups.length > 0 ? row.groups : [{ abilityIds: [], questionCount: 1 }];
  groupOpen.value = true;
}

function addGroup() {
  groupList.value.push({
    abilityIds: [],
    questionCount: 1
  });
}

function removeGroup(index) {
  groupList.value.splice(index, 1);
}

function submitLevelConfig() {
  levelOpen.value = false;
  ElMessage.success('保存成功');
}

function submitGroupConfig() {
  currentLevel.value.groups = groupList.value;
  groupOpen.value = false;
  ElMessage.success('组题配置已暂存');
}

function handleCategoryAdd(data) {
  ElMessage.info('分类添加逻辑');
}

function handleCategoryEdit(data) {
  ElMessage.info('分类编辑逻辑');
}

function handleCategoryDelete(data) {
  ElMessage.info('分类删除逻辑');
}

function handleBatchMove() {
  ElMessage.info('批量移动逻辑');
}

function handleImport() {
  ElMessage.info('批量导入逻辑');
}

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

<style scoped lang="scss">
.head-container {
  border: 1px solid #409eff;
  border-radius: 4px;
  background: #fff;
  min-height: calc(100vh - 120px);
  padding: 0;
}

.tree-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 15px;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
  height: 40px;
  
  &:hover {
    .tree-btn-group {
      display: inline-flex;
    }
  }
}

.tree-label {
  color: #606266;
}

.tree-btn-group {
  display: none;
  align-items: center;
  gap: 8px;
  
  .el-button {
    padding: 0;
    font-size: 16px;
    color: #409eff;
    
    &.el-button--danger {
      color: #f56c6c;
    }
  }
  
  .drag-handler {
    cursor: move;
    color: #909399;
  }
}

:deep(.el-tree-node__content) {
  height: 40px;
  
  &:hover {
    background-color: #f5f7fa;
  }
}

:deep(.el-tree--highlight-current .el-tree-node.is-current > .el-tree-node__content) {
  background-color: #f0f7ff;
  color: #409eff;
  
  .tree-label {
    color: #409eff;
    font-weight: bold;
  }
}

.search-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  background: #fff;
  padding: 12px 20px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.search-left {
  flex: 1;
}

.search-form {
  display: flex;
  align-items: center;
  gap: 15px;
  
  .el-form-item {
    margin-bottom: 0 !important;
    margin-right: 0 !important;
  }
}

.search-input {
  width: 240px;
  
  :deep(.el-input__wrapper) {
    background-color: #f5f7fa;
    box-shadow: none !important;
    border: 1px solid #dcdfe6;
    
    &.is-focus {
      border-color: #409eff;
    }
  }

  .search-icon {
    cursor: pointer;
    color: #909399;
    font-size: 16px;
    
    &:hover {
      color: #409eff;
    }
  }
}

.operation-group {
  display: flex;
  align-items: center;
  gap: 15px;
  
  .link-btn {
    font-size: 14px;
    color: #409eff;
    padding: 0;
    font-weight: normal;
  }
  
  .add-btn {
    background-color: #409eff;
    border-color: #409eff;
    color: #fff;
    height: 32px;
    padding: 0 18px;
    
    &:hover {
      background-color: #66b1ff;
      border-color: #66b1ff;
    }
  }
  
  .import-btn {
    background-color: #eef5fe;
    color: #409eff;
    border-color: #eef5fe;
    height: 32px;
    padding: 0 15px;
    
    &:hover {
      background-color: #d9ecff;
    }
  }
  
  .delete-batch-btn {
    background-color: #f5f7fa;
    color: #c0c4cc;
    border: 1px solid #e4e7ed;
    height: 32px;
    padding: 0 15px;
    
    &:not(.is-disabled) {
      background-color: #fef0f0;
      color: #f56c6c;
      border-color: #fde2e2;
    }
  }
}

.question-table {
  border: 1px solid #ebeef5;
  border-radius: 4px;

  :deep(.el-table__header) {
    th {
      background-color: #f8f9fb;
      color: #606266;
      font-weight: bold;
      height: 45px;
    }
  }
  
  :deep(.el-table__row) {
    height: 45px;
  }
  
  .el-button--link {
    font-size: 13px;
    padding: 0 5px;
  }
}

.dialog-footer {
  text-align: right;
  padding-top: 10px;
}

.group-config-header {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}
</style>
