<template>
  <el-row :gutter="20">
    <!-- 左侧部门树 -->
    <el-col :span="4" :xs="24">
      <ContentWrap style="height: 30%; overflow-y: auto">
        <SpecialtyTree @node-click="handleSpecialtyNodeClick" />
      </ContentWrap>
      <ContentWrap style="height: 30%; overflow-y: auto">
        <DeptTree @node-click="handleDeptNodeClick" />
      </ContentWrap>
    </el-col>

    <el-col :span="20" :xs="24">
      <!-- 搜索 -->
      <ContentWrap>
        <el-form
          class="-mb-15px"
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="试题编号" prop="quNum">
              <el-input
                v-model="queryParams.quNum"
                placeholder="请输入试题编号"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
          </el-form-item>
          <el-form-item label="题干" prop="content">
              <el-input
                v-model="queryParams.content"
                placeholder="请输入题干"
                clearable
                @keyup.enter="handleQuery"
                class="!w-240px"
              />
          </el-form-item>        
          <el-form-item label="状态" prop="examStatus">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择状态"
              clearable
              class="!w-240px"
            >
              <el-option label="启用" :value="0" />
              <el-option label="禁用" :value="1" />
            </el-select>
          </el-form-item>
        
          <!--          <el-form-item label="手机号码" prop="mobile">-->
          <!--            <el-input-->
          <!--              v-model="queryParams.mobile"-->
          <!--              placeholder="请输入手机号码"-->
          <!--              clearable-->
          <!--              @keyup.enter="handleQuery"-->
          <!--              class="!w-240px"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <!-- <el-form-item label="审核状态" prop="audit">
                      <el-select
                        v-model="queryParams.audit"
                        placeholder="请选择审核状态"
                        class="!w-240px"
                        clearable
                      >
                        <el-option
                          v-for="dict in getIntDictOptions(DICT_TYPE.QUESTION_AUDIT)"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        />
                      </el-select>
                    </el-form-item> -->
          <el-form-item>
            <!-- 状态切换单独一行 -->
            <el-radio-group v-model="queryParams.audit" @change="handleQuery">
              <el-radio-button :label="''">全部</el-radio-button>
              <el-radio-button :label="'0'">审核通过</el-radio-button>
              <el-radio-button :label="'1'">未审核</el-radio-button>
              <!-- <el-radio-button :label="'2'">待审核</el-radio-button> -->
              <el-radio-button :label="'3'">审核未通过</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <!--          <el-form-item label="创建时间" prop="createTime">-->
          <!--            <el-date-picker-->
          <!--              v-model="queryParams.createTime"-->
          <!--              value-format="YYYY-MM-DD HH:mm:ss"-->
          <!--              type="datetimerange"-->
          <!--              start-placeholder="开始日期"-->
          <!--              end-placeholder="结束日期"-->
          <!--              class="!w-240px"-->
          <!--            />-->
          <!--          </el-form-item>-->
          <el-form-item>
            <el-button @click="handleQuery"><Icon icon="ep:search" />搜索</el-button>
            <el-button @click="resetQuery"><Icon icon="ep:refresh" />重置</el-button>
            <el-button
              type="danger"
              class="ele-btn-del"
              :disabled="!selections.length"
              @click="handleDeletes()"
            >
              批量删除
            </el-button>
            <el-button type="warning" plain @click="handleImport">
              <Icon icon="ep:upload" /> 导入
            </el-button>
            <el-button type="primary" plain @click="openForm('create')">
              <Icon icon="ep:plus" /> 新增
            </el-button>

            <el-button @click="connectTent()">连接服务器</el-button>
            <el-button @click="connectTong()">同步试题</el-button>
            <!--            <el-button-->
            <!--              type="warning"-->
            <!--              plain-->
            <!--              @click="handleImport"-->
            <!--              v-hasPermi="['system:user:import']"-->
            <!--            >-->
            <!--              <Icon icon="ep:upload" /> 导入-->
            <!--            </el-button>-->
            <!--            <el-button-->
            <!--              type="success"-->
            <!--              plain-->
            <!--              @click="handleExport"-->
            <!--              :loading="exportLoading"-->
            <!--              v-hasPermi="['system:user:export']"-->
            <!--            >-->
            <!--              <Icon icon="ep:download" />导出-->
            <!--            </el-button>-->
          </el-form-item>
          <!-- 审核按钮单独显示在下一行 -->
          <el-form-item>
            <el-button
              v-if="queryParams.audit === '1' && sendAudio"
              type="primary"
              plain
              @click="handleAudit()"
            >
              <Icon icon="ep:plus" /> 推送审核试题
            </el-button>
            <el-button
              v-if="queryParams.audit === '1' && audioTrue"
              type="primary"
              plain
              @click="handleAuditTrue('True')"
            >
              <Icon icon="ep:check" /> 审核通过试题
            </el-button>
              <el-button
              v-if="queryParams.audit === '1' && audioTrue"
              type="primary"
              plain
              @click="handleAuditTrue('False')"
            >
              <Icon icon="ep:close-bold" /> 审核不通过试题
            </el-button>
            <el-button
              v-if="queryParams.audit === '' || queryParams.audit === '0'"
              type="primary"
              plain
              @click="handleTUI()"
              v-hasPermi="['question:create']"
            >
              <Icon icon="ep:top" />推送试题
            </el-button>
          </el-form-item>
        </el-form>
      </ContentWrap>
      <ContentWrap>
        <el-table v-loading="loading" :data="list" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column
            label="试题编号"
            align="center"
            prop="quNum"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="题干" align="center" prop="content" width="120">
            <template #default="{ row }">
                   {{ getFirstNChineseChars(row.content, 5) }}
            </template>
          </el-table-column>
          <el-table-column label="专业" align="center" prop="specialtyName" width="120" />
          <el-table-column
            label="课程"
            align="center"
            prop="courseName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="章节名称"
            align="center"
            prop="chapteridDictTextVo"
            :show-overflow-tooltip="true"
          />
          <!-- <el-table-column
            label="用户昵称"
            align="center"
            prop="nickname"
            :show-overflow-tooltip="true"
          /> -->
          <el-table-column label="难度" align="center" prop="quLevel" :show-overflow-tooltip="true">
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.EXAM_QUE_DIFF" :value="scope.row.quLevel" />
            </template>
          </el-table-column>

          <el-table-column
            label="知识点"
            align="center"
            prop="pointNamesVo"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="审核状态"
            align="center"
            prop="audit"
            :show-overflow-tooltip="true"
          >
            <template #default="scope">
              <dict-tag :type="DICT_TYPE.QUESTION_AUDIT" :value="scope.row.audit" />
            </template>
          </el-table-column>

          <!-- <el-table-column
              label="来源"
              align="center"
              prop="resource"
              :show-overflow-tooltip="true"
          />
          <el-table-column
              label="类别"
              align="center"
              prop="type"
              :show-overflow-tooltip="true"
          /> -->
          <!-- <el-table-column
              label="试题版本"
              align="center"
              prop="version"
              :show-overflow-tooltip="true"
          /> -->
          <el-table-column label="状态" key="status" :show-overflow-tooltip="true">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column
            label="归属"
            align="center"
            prop="schoolName"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="创建教师"
            align="center"
            prop="createTeacher"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            :label="tenantId === 1 ? '创建时间' : '更新时间'"
            align="center"
            width="180"
          >
            <template #default="scope">
              <span>
                {{ dateFormatter(scope.row, null, tenantId === 1 ? scope.row.createTime : scope.row.updateTime) }}
              </span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="160">
            <template #default="scope">
              <div class="flex items-center justify-center">
                <el-button type="primary" link @click="openForm('update', scope.row.quId)">
                  <Icon icon="ep:edit" />修改
                </el-button>
                <el-button type="primary" link @click="handleDelete(scope.row.quId)">
                  <Icon icon="ep:delete" />删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        <Pagination
          :total="total"
          v-model:page="queryParams.pageNo"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <!-- 同步弹框 -->
  <el-dialog
    v-model="syncDialogVisible"
    :title="'选择推送考点服务器'"
    width="500px"
    :before-close="handleCloseSyncDialog"
  >
    <ContentWrap>
      <!-- 搜索表单 -->
      <el-form
        class="-mb-15px"
        :model="queryParamsSchool"
        ref="queryFormRefSchool"
        :inline="true"
        label-width="68px"
      >
        <el-form-item label="" prop="name">
          <el-input
            v-model="queryParamsSchool.name"
            placeholder="请输入考点服务器"
            clearable
            class="!w-190px"
            @keyup.enter="handleQuerySchool"
          />
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuerySchool">
            <Icon icon="ep:search" class="mr-5px" /> 搜索
          </el-button>
          <el-button @click="resetQuerySchool"><Icon icon="ep:refresh" />重置</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <el-table
        v-loading="loadingSchool"
        :data="listSchool"
        @selection-change="handleSelectionChangeSchool"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" align="center" prop="id" width="60" />
        <el-table-column label="考点服务器" align="center" prop="name" />
      </el-table>
      <Pagination
        :total="totalSchool"
        v-model:page="queryParamsSchool.pageNo"
        v-model:limit="queryParamsSchool.pageSize"
        @pagination="getSchoolList"
      />
    </ContentWrap>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseSyncDialog">取消</el-button>
        <el-button @click="connectSchoolAll">测试连接</el-button>
        <el-button type="primary" @click="confirmSync">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 添加或修改选择题 -->
  <ChoiceForm ref="formRef" @success="getList" />
  <!-- 添加或修改C语言程序设计 -->
  <CdesignForm ref="cformRef" @success="getList" />

  <!-- 用户导入对话框 -->
  <UserImportForm ref="importFormRef" @success="getList" />
  <!-- 分配角色 -->
  <UserAssignRoleForm ref="assignRoleFormRef" @success="getList" />

  <MdesignForm ref="mformRef" @success="getList" />

  <BdesignForm ref="bformRef" @success="getList" />
  <FdesignForm ref="fformRef" @success="getList" />
  <WpsWordForm ref="wformRef" @success="getList" />
  <WpsPptxForm ref="pformRef" @success="getList" />
  <SettingForm ref="setformRef" @success="getList" />
  <WindowsSystemSettingForm ref="windowsSystemFormRef" @success="getList" />
  <EmailForm ref="emailformRef" @success="getList" />
  <WpsXlsxForm ref="xlsxformRef" @success="getList" />
  <PsForm ref="psformRef" @success="getList" />
</template>
<script lang="ts" setup>
import { getAccessToken, getRefreshToken, getTenantId, removeToken, setToken } from '@/utils/auth'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as UserApi from '@/api/system/user'
import * as QuestionApi from '@/api/paper/question'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import ChoiceForm from './ChoiceForm.vue'
import CdesignForm from './CdesignForm.vue'
import MdesignForm from './MysqlForm.vue'
import BdesignForm from './BrowerForm.vue'
import FdesignForm from './FileForm.vue'
import UserImportForm from './UserImportForm.vue'
import WpsWordForm from './WpsWordForm.vue'
import WpsPptxForm from './WpsPptxForm.vue'
import SettingForm from './SettingForm.vue'
import WindowsSystemSettingForm from './WindowsSystemSettingForm.vue'
import WpsXlsxForm from './WpsXlsxForm.vue'
import PsForm from './PsForm.vue'
import EmailForm from './EmailForm.vue'
import UserAssignRoleForm from './UserAssignRoleForm.vue'
import DeptTree from './DeptTree.vue'
import SpecialtyTree from './SpecialtyTree.vue'
import { handleTree } from '@/utils/tree'
import * as SpecialtyApi from '@/api/points'
import { useSettingStore } from '@/store/modules/settings'
import { TaskStatusEnum } from '@/api/bpm/task'
import { status } from 'nprogress'
const settingStore = useSettingStore()
defineOptions({ name: 'SystemUser' })
const tenantId = getTenantId()
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数

const queryParams = reactive({
  chapteridDictTextVo: '',
  pointNamesVo: '',
  specialtyName: '',
  courseName: '',
  subjectName: '',
  pointNames: '',
  chapteridDictText: '',
  pageNo: 1,
  pageSize: 10,
  audit: '',
  status:'',
  quNum:'',
  content:''
})
const queryFormRef = ref() // 搜索的表单
const specialtyList = ref<Tree[]>([]) // 树形结构
const respoint = ref<Tree[]>([]) // 树形结构
const sendAudio = ref(false) // 是否显示推送审核试题按钮
const audioTrue = ref(false) // 是否显示审核试题按钮

/** 获得部门树 */
const getTree = async () => {
  const res = await UserApi.getSpecialtyByUserId()
  specialtyList.value = []
  specialtyList.value.push(...handleTree(res))
}
const getTreePoint = async () => {
  const res = await SpecialtyApi.listPoints()
  respoint.value = []
  respoint.value.push(...handleTree(res))
}

const syncDialogVisible = ref(false)

/** 查询列表 */
const getList = async () => {
  await getTree()
  await getTreePoint()
  loading.value = true
  try {
    const params = {
      ...queryParams,
      pointNames: queryParams.pointNamesVo,
      chapteridDictText: queryParams.chapteridDictTextVo
    }
    const data = await QuestionApi.getQuestionList(params)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
  settingStore.clearSettingData() // 清除设置数据
}
/** 用户导入 */
const handleImport = () => {
  importFormRef.value.open()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}
const choosePointsType = ref('')
/** 处理部门被点击 */
const handleDeptNodeClick = async (row) => {
  choosePointsType.value = row.name
  // 判断点击的层级结构，进行入参
  if (!row.children != null) {
  }
  const specArr: any = findIdPathFromTreeList(respoint.value, row.id)
  console.log(specArr + 'specArr')

  console.log(specArr[1].name + 'specArr[1].name')
  console.log(specArr[1].id + 'specArr[1].name')

  // 判断长度赋值
  if (specArr.length == 1) {
  }
  if (specArr.length == 2) {
  }
  if (specArr.length == 3) {
    queryParams.chapteridDictText = specArr[1].name
    queryParams.pointNames = specArr[2].name

    queryParams.chapteridDictTextVo = specArr[1].id
    queryParams.pointNamesVo = specArr[2].id
  }
  await getList()
}

/** 处理专业被点击 */
const chooseQuestionType = ref('')
const handleSpecialtyNodeClick = async (row: any) => {
  chooseQuestionType.value = row.name
  // 判断点击的层级结构，进行入参
  if (!row.children != null) {
    // 说明是题型
    queryParams.courseName = row.name
  }
  const specArr: any = findNamePathFromTreeList(specialtyList.value, row.id)
  // 判断长度赋值
  if (specArr.length == 1) {
    // 说明是题型
    queryParams.specialtyName = specArr[0]
  }
  if (specArr.length == 2) {
    queryParams.specialtyName = specArr[0]
    queryParams.courseName = specArr[1]
  }
  if (specArr.length == 3) {
    queryParams.specialtyName = specArr[0]
    queryParams.courseName = specArr[1]
    queryParams.subjectName = specArr[2]
  }
  await getList()
}

/** 表格选中数据 */
const selections = ref([])
const handleSelectionChange = (rows) => {
  selections.value = rows
}

const selectedSchool = ref<any>([])

const handleSelectionChangeSchool = (rows) => {
  selectedSchool.value = rows
}

const selectedRows = ref<string[]>([])
const handleAudit = async () => {
  try {
    const rows = selections.value
    if (!rows.length) {
      message.error('请至少选择一条数据')
      return
    }
    selectedRows.value = rows.map((d: any) => d.quId)
    const requestBody = {
      type: '1',
      queueNames: '1_Queue',
      questionIds: selectedRows.value
    }
    await QuestionApi.auditQuestion(requestBody)
    message.success(t('推送成功'))
    // 刷新列表
    await getList()
  } catch {}
}
// 审核试题
const handleAuditTrue = async (status: string) => {
  try {
    if (!connectTentStatus.value) {
      message.error('请先连接服务器')
      return
    }
    const rows = selections.value
    if (!rows.length) {
      message.error('请至少选择一条数据')
      return
    }
    selectedRows.value = rows.map((d: any) => d.quId)
    const requestBody = {
      type: status,
      quIds: selectedRows.value
    }
    await QuestionApi.auditQuestionTrue(requestBody)
    message.success(t('审核成功'))
    // 刷新列表
    await getList()
  } catch {}
}
const queryParamsSchool = reactive({
  name: '',
  pageNo: 1,
  pageSize: 10
})
const totalSchool = ref(0) // 列表的总页数
const listSchool = ref([]) // 列表的数
const schoolNameList = ref()
const loadingSchool = ref(true)
const connectTentStatus = ref(false)
const handleTUI = async () => {
  try {
    const rows = selections.value
    if (!rows.length) {
      message.error('请至少选择一条数据')
      return
    }

    selectedRows.value = rows.map((d: any) => d.quId)
    getSchoolList()
    syncDialogVisible.value = true
  } catch {}
}
const getSchoolList = async () => {
  loadingSchool.value = true
  try {
    const data = await QuestionApi.getSchoolName(queryParamsSchool)

    listSchool.value = data.list
    totalSchool.value = data.total
  } finally {
    loadingSchool.value = false
  }
}
const handleQuerySchool = () => {
  queryParamsSchool.pageNo = 1
  getSchoolList()
}
const resetQuerySchool = () => {
  queryParamsSchool.name = ''
}

const handleCloseSyncDialog = () => {
  syncDialogVisible.value = false
  queryParamsSchool.name = ''
  listSchool.value = []
  totalSchool.value = 0
}
const confirmSync = () => {
  if (selectedSchool.value.length === 0) {
    ElMessage.warning('请先选择要同步的学校')
    return
  }

  const selectedIds = selectedSchool.value.map((item) => item.ququeName)
  console.log('选中的ID:', selectedIds)

  const rows = selections.value
  selectedRows.value = rows.map((d: any) => d.quId)
  console.log(selectedRows.value + '选中的试题')

  const payload = {
    queueNames: selectedIds,
    questionIds: selectedRows.value
  }
  console.log(payload + 'payload')
  QuestionApi.doPush(payload)
    .then(() => {
      ElMessage.success('推送成功')
      syncDialogVisible.value = false
      getList()
    })
    .catch(() => {
      ElMessage.error('推送失败')
    })
}
const connectSchoolAll = () => {
  if (selectedSchool.value.length === 0) {
    ElMessage.warning('请先选择要连接的学校')
    return
  }
  const selectedIds = selectedSchool.value.map((item) => item.ququeName)
  console.log('选中的ID:', selectedIds)

  QuestionApi.connectSchoolAll(selectedIds)
    .then(() => {
      ElMessage.success('连接成功')
    })
    .catch(() => {
      ElMessage.error('同步失败')
    })
}

const connectTent = async () => {
  try {
    const res = await QuestionApi.rabbitmqConnect()
    message.success(t(res))
    connectTentStatus.value = true
  } catch (error) {
    message.error(t(`连接失败: ${error?.message || '未知错误'}`))
  }
}
// 同步试题
const connectTong = async () => {
  if (!connectTentStatus.value) {
    message.error('请先连接服务器')
    return
  }
  try {
    const res = await QuestionApi.receiveAll()
    message.success(t('同步成功'))
  } catch (error: any) {
    message.error(t(`连接失败: ${error?.message || '未知错误'}`))
  }
}

interface Tree {
  id: number
  name: string
  children?: Tree[] | any[]
}
/**
 * 递归查找路径
 */
/** 递归查找路径（根据 ID 返回 name 路径） */
const findNamePath = (node: Tree, targetId: number, path: string[] = []): string[] | null => {
  const currentPath = [...path, node.name]
  if (node.id === targetId) {
    return currentPath
  }
  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      const result = findNamePath(child, targetId, currentPath)
      if (result) return result
    }
  }
  return null
}
// 递归查找路径，返回包含 id 和 name 的路径数组
const findIdNamePath = (
  node: Tree,
  targetId: number,
  path: Array<{ id: number; name: string }> = []
): Array<{ id: number; name: string }> | null => {
  const currentPath = [...path, { id: node.id, name: node.name }]
  if (node.id === targetId) {
    return currentPath
  }
  if (node.children && node.children.length > 0) {
    for (const child of node.children) {
      const result = findIdNamePath(child, targetId, currentPath)
      if (result) return result
    }
  }
  return null
}

/** 入口函数：支持根节点是数组的情况 */
const findNamePathFromTreeList = (treeList: Tree[], targetId: number): string[] | null => {
  for (const tree of treeList) {
    const result = findNamePath(tree, targetId)
    if (result) return result
  }
  return null
}

// 遍历树列表查找路径
const findIdPathFromTreeList = (
  treeList: Tree[],
  targetId: number
): Array<{ id: number; name: string }> | null => {
  for (const tree of treeList) {
    const result = findIdNamePath(tree, targetId)
    if (result) return result
  }
  return null
}
/** 添加/修改操作 */
const formRef = ref()
const cformRef = ref()
const mformRef = ref()
const bformRef = ref()
const fformRef = ref()
const wformRef = ref()
const pformRef = ref()
const setformRef = ref()
const windowsSystemFormRef = ref()
const emailformRef = ref()
const xlsxformRef = ref()
const psformRef = ref()
const openForm = (type: string, id?: number) => {
  console.log(queryParams)
  if (queryParams.subjectName == '') {
    return message.confirm('请选择题型！')
  }
  if (chooseQuestionType.value.includes('选择题')) {
    formRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('编程题')) {
    cformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('程序设计')) {
    mformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('网络题')) {
    bformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('文件处理')) {
    fformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('文字')) {
    wformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('演示')) {
    pformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('windows网络设置')) {
    setformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('windows系统设置')) {
    windowsSystemFormRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('邮箱')) {
    emailformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('表格')) {
    xlsxformRef.value.open(queryParams, type, id)
  } else if (chooseQuestionType.value.includes('图像处理')) {
    psformRef.value.open(queryParams, type, id)
  }
}

/** 用户导入 */
const importFormRef = ref()

/** 修改用户状态 */
const handleStatusChange = async (row: any) => {
  try {
    // 修改状态的二次确认
    await message.confirm('确认要修改' + row.quNum + '"试题状态吗?')
    // 发起修改状态
    QuestionApi.updateQuStatus(row.quId, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const exportLoading = ref(false)

/** 操作分发 */
const handleCommand = (command: string, row: UserApi.UserVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleRole':
      handleRole(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await ElMessageBox.confirm('只能删除未被使用的试题,是否确认删除？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 发起删除
    const res = await QuestionApi.removeQuestions(id)
    if (res == '删除成功') {
      message.success(res)
    } else {
      message.error(res)
    }
    // 刷新列表
    await getList()
  } catch {}
}

const handleDeletes = async () => {
  try {
    const rows = selections.value
    if (!rows.length) {
      message.error('请至少选择一条数据')
      return
    }
    // 删除的二次确认
    await ElMessageBox.confirm('只能删除未被使用的试题,是否确认删除？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    selectedRows.value = rows.map((d: any) => d.quId) // 保存选中的行数据
    const res = await QuestionApi.removeQuestions(selectedRows.value)
    if (res == '删除成功') {
      message.success(res)
    } else {
      message.error(res)
    }
    // 刷新列表
    await getList()
  } catch {}
}

/** 重置密码 */
const handleResetPwd = async (row: UserApi.UserVO) => {
  try {
    // 重置的二次确认
    const result = await message.prompt(
      '请输入"' + row.username + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await UserApi.resetUserPassword(row.id, password)
    message.success('修改成功，新密码是：' + password)
  } catch {}
}

/** 分配角色 */
const assignRoleFormRef = ref()
const handleRole = (row: UserApi.UserVO) => {
  assignRoleFormRef.value.open(row)
}


function getFirstNChineseChars(htmlStr) {
  if (!htmlStr) return ''

  // 将 HTML 转为纯文本
  const tempDiv = document.createElement('div')
  tempDiv.innerHTML = htmlStr
  let text = tempDiv.textContent || tempDiv.innerText || ''

  // 去掉空格和换行
  text = text.replace(/\s+/g, '')

  // 匹配汉字
  const match = text.match(/[\u4e00-\u9fa5]/g)
  if (!match) return ''

  return match.slice(0, 6).join('')
}
/** 初始化 */
onMounted(() => {
  getList()
  if (getTenantId() == 1) {
    sendAudio.value = false
    audioTrue.value = true
  } else {
    sendAudio.value = true
    audioTrue.value = false
  }
})
</script>
