<template>
  <div class="position-detail-container">
    <div class="header-container">
      <page-header title="测试" @back="goBack" />
      <div class="header-actions">
        <el-button type="primary" @click="handleEdit">保存</el-button>
        <el-button @click="handleShare">分享职位</el-button>
      </div>
    </div>
    
    <div class="detail-content">
      <!-- 左侧详情信息 -->
      <el-card class="detail-card">
        <div class="section-title">
          <div class="section-line"></div>
          <span>职位详情</span>
        </div>
        
        <div class="detail-item">
          <div class="detail-label">职位名称</div>
          <div class="detail-value" v-if="!isEditingTitle">
            {{ positionData.title }}
            <el-button type="text" class="edit-title-btn" @click="startEditTitle">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-input 
              v-model="editingTitle" 
              placeholder="请输入职位名称" 
              maxlength="20"
              show-word-limit
            />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditTitle">取消</el-button>
              <el-button size="small" type="primary" @click="saveTitle">保存</el-button>
            </div>
          </div>
        </div>
        
        <!-- 工作地点 -->
        <div class="detail-item">
          <div class="detail-label">工作地点</div>
          <div class="detail-value" v-if="!isEditingLocation">
            {{ 
              (() => {
                if (!positionData.location) return '暂无';
                if (Array.isArray(positionData.location)) return positionData.location.join(',');
                if (typeof positionData.location === 'string') {
                  try {
                    // 移除方括号并分割字符串
                    const cleanStr = positionData.location.replace(/[\[\]']/g, '');
                    return cleanStr.split(',').map(item => item.trim()).join(',');
                  } catch (e) {
                    return positionData.location;
                  }
                }
                return positionData.location;
              })()
            }}
            <el-button type="text" class="edit-title-btn" @click="startEditLocation">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <!-- <el-input 
              v-model="editingLocation" 
              placeholder="请输入工作地点" 
              maxlength="50"
              show-word-limit
            /> -->
            <el-cascader
            v-model="editingLocation"
            :options="locationOptions"
            :props="{ 
              expandTrigger: 'hover',
              checkStrictly: false,
              value: 'code',
              label: 'name'
            }"
            style="width: 100%"
            placeholder="请选择工作地点"
            clearable
            @change="handleLocationChange"
          />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditLocation">取消</el-button>
              <el-button size="small" type="primary" @click="saveLocation">保存</el-button>
            </div>
          </div>
        </div>
        
        <!-- 职位薪资 -->
        <div class="detail-item">
          <div class="detail-label">职位薪资</div>
          <div class="detail-value" v-if="!isEditingSalary">
            {{ positionData.salary_range || '暂无' }}
            <el-button type="text" class="edit-title-btn" @click="startEditSalary">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-input 
              v-model="editingSalary" 
              placeholder="请输入职位薪资" 
              maxlength="30"
              show-word-limit
            />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditSalary">取消</el-button>
              <el-button size="small" type="primary" @click="saveSalary">保存</el-button>
            </div>
          </div>
        </div>
        
        <!-- 工作经验 -->
        <div class="detail-item">
          <div class="detail-label">工作经验</div>
          <div class="detail-value" v-if="!isEditingExperience">
            {{ positionData.work_experience_required || '暂无' }}
            <el-button type="text" class="edit-title-btn" @click="startEditExperience">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-select v-model="editingExperience" placeholder="请选择工作经验" style="width: 100%">
              <el-option label="不限" value="不限" />
              <el-option label="应届毕业生" value="应届毕业生" />
              <el-option label="1年以下" value="1年以下" />
              <el-option label="1-3年" value="1-3年" />
              <el-option label="3-5年" value="3-5年" />
              <el-option label="5-10年" value="5-10年" />
              <el-option label="10年以上" value="10年以上" />
            </el-select>
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditExperience">取消</el-button>
              <el-button size="small" type="primary" @click="saveExperience">保存</el-button>
            </div>
          </div>
        </div>
        
        <!-- 学历要求 -->
        <div class="detail-item">
          <div class="detail-label">学历要求</div>
          <div class="detail-value" v-if="!isEditingEducation">
            {{ positionData.education_required || '暂无' }}
            <el-button type="text" class="edit-title-btn" @click="startEditEducation">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-select v-model="editingEducation" placeholder="请选择学历要求" style="width: 100%">
              <el-option label="不限" value="不限" />
              <el-option label="高中" value="高中" />
              <el-option label="大专" value="大专" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditEducation">取消</el-button>
              <el-button size="small" type="primary" @click="saveEducation">保存</el-button>
            </div>
          </div>
        </div>
        
        <!-- 所属部门 -->
        <div class="detail-item">
          <div class="detail-label">所属部门</div>
          <div class="detail-value" v-if="!isEditingDepartment">
            {{ positionData.department || '暂无' }}
            <el-button type="text" class="edit-title-btn" @click="startEditDepartment">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-input 
              v-model="editingDepartment" 
              placeholder="请输入所属部门" 
              maxlength="30"
              show-word-limit
            />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditDepartment">取消</el-button>
              <el-button size="small" type="primary" @click="saveDepartment">保存</el-button>
            </div>
          </div>
        </div>
        
        <div class="detail-item">
          <div class="detail-label">职位状态</div>
          <div class="detail-value">
            <el-tag :type="getStatusType(positionData.status)">
              {{ getStatusText(positionData.status) }}
            </el-tag>
          </div>
        </div>
        
        <div class="detail-item">
          <div class="detail-label">截止日期</div>
          <div class="detail-value" v-if="!isEditingEndDate">
            {{ positionData.end_date || '暂无' }}
            <el-button type="text" class="edit-title-btn" @click="startEditEndDate">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-date-picker
              v-model="editingEndDate"
              type="date"
              placeholder="请选择截止日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditEndDate">取消</el-button>
              <el-button size="small" type="primary" @click="saveEndDate">保存</el-button>
            </div>
          </div>
        </div>
           
        <div class="detail-item" >
          <div class="detail-label">职位要求</div>
          <div class="detail-value html-content" v-if="!isEditingRequirements" v-html="positionData.requirements"></div>
          <el-button type="text" class="edit-title-btn" @click="startEditRequirements" v-if="!isEditingRequirements">
            <el-icon><Edit /></el-icon>
          </el-button>
          <div class="title-edit-container" v-else>
            <el-input
              v-model="editingRequirements"
              type="textarea"
              rows="6"
              placeholder="请输入职位要求"
              maxlength="1000"
              show-word-limit
            />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditRequirements">取消</el-button>
              <el-button size="small" type="primary" @click="saveRequirements">保存</el-button>
            </div>
          </div>
        </div>
        <div style="width: 100%; border-bottom: 1px solid #e5e5e5;"></div>
        <div class="detail-item">
          <div class="detail-label">职位描述</div>
          <div class="detail-value html-content" v-if="!isEditingDescription" v-html="positionData.description"></div>
          <el-button type="text" class="edit-title-btn" @click="startEditDescription" v-if="!isEditingDescription">
            <el-icon><Edit /></el-icon>
          </el-button>
          <div class="title-edit-container" v-else>
            <el-input
              v-model="editingDescription"
              type="textarea"
              rows="6"
              placeholder="请输入职位描述"
              maxlength="1000"
              show-word-limit
            />
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditDescription">取消</el-button>
              <el-button size="small" type="primary" @click="saveDescription">保存</el-button>
            </div>
          </div>
        </div>

        <!-- 在 detail-item 列表中添加能力标签部分 -->
        <div class="detail-item">
          <div class="detail-label">能力标签</div>
          <div class="detail-value" v-if="!isEditingCompetency">
            <el-tag
              v-for="tag in positionData.competency_tags"
              :key="tag.id"
              effect="plain"
              class="competency-tag"
            >
              {{ tag.name }}
            </el-tag>
            <el-button type="text" class="edit-title-btn" @click="startEditCompetency">
              <el-icon><Edit /></el-icon>
            </el-button>
          </div>
          <div class="title-edit-container" v-else>
            <el-select
              v-model="selectedCompetencies"
              multiple
              filterable
              placeholder="请选择能力标签"
              style="width: 100%"
            >
              <el-option
                v-for="tag in competencyTagOptions"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
              >
              </el-option>
            </el-select>
            <div class="title-edit-actions">
              <el-button size="small" @click="cancelEditCompetency">取消</el-button>
              <el-button size="small" type="primary" @click="saveCompetency">保存</el-button>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 右侧状态信息 -->
      <div class="status-cards">
        <el-card class="status-card">
          <div class="section-title">
            <div class="section-line"></div>
            <span>职位状态</span>
          </div>
          <div class="status-switch">
            <el-switch
              v-model="positionStatus"
              inactive-text=""
              @change="handleStatusChange"
            />
            <span class="status-text">{{ positionStatus ? '已启用' : '待启用' }}</span>
          </div>
        </el-card>
        
        <el-card class="status-card">
          <div class="section-title">
            <div class="section-line"></div>
            <span>职位性质</span>
            <el-button type="text" class="edit-btn" @click="startEditJobType" v-if="!isEditingJobType">编辑</el-button>
          </div>
          <div class="usage-content">
           <!--  <div class="usage-label">职位用途</div> -->
            <div class="usage-value" v-if="!isEditingJobType">{{ getJobTypeText(positionData.job_type) }}</div>
            
            <!-- 编辑模式 -->
            <div v-if="isEditingJobType" class="title-edit-container">
              <el-select v-model="editingJobType" placeholder="请选择职位性质" style="width: 100%;">
                <el-option label="全职" :value="0"></el-option>
                <el-option label="兼职" :value="1"></el-option>
                <el-option label="实习" :value="2"></el-option>
                <el-option label="其他" :value="3"></el-option>
              </el-select>
              <div class="title-edit-actions">
                <el-button size="small" @click="cancelEditJobType">取消</el-button>
                <el-button size="small" type="primary" @click="saveEditJobType">保存</el-button>
              </div>
            </div>
          </div>
        </el-card>
        
        <el-card class="status-card">
          <div class="section-title">
            <div class="section-line"></div>
            <span>招聘流程</span>
            <el-button type="text" class="edit-btn" @click="handleEditProcess">设置流程</el-button>
          </div>
          <div class="process-steps">
            <div 
              v-for="(step, index) in recruitmentProcess" 
              :key="step.id" 
              class="process-step" 
              :class="{ 'disabled': !step.active }"
              v-show="step.visible"
            >
              <div class="step-number">{{ index + 1 }}</div>
              <div class="step-content">
                <div class="step-title">{{ step.name }}</div>
                <!-- <div class="step-desc">{{ step.description }}</div> -->
              </div>
            </div>
          </div>
        </el-card>
        <el-card class="status-card">
          <div class="section-title">
            <div class="section-line"></div>
            <span>面试设置</span>
            <el-button type="text" class="edit-btn" @click="handleEditInterview">编辑</el-button>
          </div>
        </el-card>
      </div>
    </div>

    <!-- 添加招聘流程编辑对话框 -->
    <el-dialog
      title="设置招聘流程"
      v-model="showProcessDialog"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="process-dialog-content">
        <div v-for="(step, index) in recruitmentProcess" :key="step.id" v-show="step.visible">
          <!-- 添加在每个步骤上方的加号按钮，最后两个步骤不显示加号 -->
          <div class="add-process-btn-top" v-if="index < recruitmentProcess.length - 1">
            <el-button type="text" @click="showStepOptions(index, $event)">
              <el-icon><Plus /></el-icon>
            </el-button>
          </div>
          
          <div 
            class="process-edit-item"
            :class="{ 'highlight': step.active }"
          >
            <div class="process-number">{{ index + 1 }}</div>
            <div class="process-edit-content">
              <div>{{ step.name }}</div>
              <div class="process-edit-desc">{{ step.description }}</div>
            </div><!--  v-if="step.name=='AI考察'" -->
            <div class="process-edit-btn">
               <el-button 
                type="info" 
                size="small" 
                plain 
                @click="editProcessStep(step, index)"
              >
                修改
              </el-button>
            <el-button 
              type="danger" 
              size="small" 
              plain 
             style="margin-top: 10px;margin-left: 0px;"
              @click="deleteProcessStep(step,index)"
            >
              删除
            </el-button>
            </div>
           
          </div>
        </div>
        
        <!-- 最后一个步骤下方的加号按钮 -->
        <div class="add-process-btn">
         <!--  <el-button type="text" @click="showStepOptions(recruitmentProcess.length, $event)">
            <el-icon><Plus /></el-icon>
          </el-button> -->
        </div>
      </div>
      
      <!-- 添加选项菜单 -->
      <div 
        v-if="showOptionsMenu" 
        class="process-options-menu"
        :style="{ top: menuPosition.top, left: menuPosition.left }"
        @click.stop
      >
        <div class="close-btn" @click="showOptionsMenu = false">
          <el-icon><Close /></el-icon>
        </div>
        <div 
          v-for="option in processStepOptions" 
          :key="option.value"
          class="process-option-item"
          @click="addSelectedStepType(option.value, option.label)"
        >
          {{ option.label }}
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelEditProcess">取消</el-button>
          <el-button type="primary" @click="saveProcess">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- AI考察配置对话框 -->
    <el-drawer
      title="AI考察"
      v-model="showAIVideoDialog"
      direction="rtl"
      size="60%"
      :close-on-click-modal="false"
      class="ai-video-drawer"
      :destroy-on-close="false"
    >
      <!-- 步骤指示器 -->
      <div class="ai-video-steps">
        <div class="step-item" :class="{ 'active': currentStep === 1 }" @click="jumpToStep(1)">
          <div class="step-number">1</div>
          <div class="step-title" :class="{ 'active-title': currentStep === 1 }">考察能力</div>
        </div>
        <div class="step-line" :class="{ 'active-line': currentStep >= 2 }"></div>
        <div class="step-item" :class="{ 'active': currentStep === 2 }" @click="jumpToStep(2)">
          <div class="step-number">2</div>
          <div class="step-title" :class="{ 'active-title': currentStep === 2 }">面试题目</div>
        </div>
        <div class="step-line" :class="{ 'active-line': currentStep >= 3 }"></div>
        <div class="step-item" :class="{ 'active': currentStep === 3 }" @click="jumpToStep(3)">
          <div class="step-number">3</div>
          <div class="step-title" :class="{ 'active-title': currentStep === 3 }">系统设置</div>
        </div>
      </div>

      <!-- 步骤1：考察能力 -->
      <div v-if="currentStep === 1" class="ai-video-content" v-loading="competencyLoading" element-loading-text="正在生成能力标签...">
        <div class="ai-video-options">
        <div class="ai-video-options-header">
          <div class="ai-video-options-header-title">
            <span>AI根据岗位信息生成的能力，创建完步骤后，会自动将选择的胜任力考核维度加入到该职位的考察能力列表中。</span>
          </div>
          <!-- <div class="right_btn">
            <el-button type="primary" class="custom-btn" plain size="small" @click="handleAddCompetency">重新生成</el-button>
          </div> -->
        </div>
          <!-- <p class="option-tip">AI根据岗位信息生成的能力，创建完步骤后，会自动将选择的新智能能力加入到该职位的考察能力列表中。</p> -->
          
          <!-- <div class="new-feature-tip">
            下面是奇才智能算法推荐的胜任力考核维度，请结合您的需求增删，确认后点击「下一步」出题
            <span class="new-tag">NEW</span>
            AI根据岗位信息生成的能力，创建完步骤后，会自动将选择的新智能能力加入到该职位的考察能力列表中。
          </div> -->
          
          <!-- 推荐的考核维度 -->
          <div class="recommended-dimensions">
           <!--  <h3>推荐考核维度</h3> -->
            <div class="dimension-grid" >
              <el-checkbox 
                v-for="item in competencyTags.slice(0,10)" 
                :key="item.id" 
                v-model="item.selected"
                @change="(val: boolean) => handleCompetencyChange(item, val)"
                class="custom-checkbox"
              >
                <div class="ability-label">
                  <span>{{ item.name }}</span>
                  <img src="../../../assets/sheng.png" alt="" class="sheng">
                </div>
              </el-checkbox>
            </div>
          </div>

          <!-- 备选考核维度 -->
          <div class="optional-dimensions">
                    <div class="header-row">
            <h3 style="color: #808080;">备选考核维度</h3>
            <div class="right_btn">
              <el-button type="primary" class="custom-btn" plain size="small" @click="handleAddCompetency">重新生成</el-button>
            </div>
          </div>
            <div class="dimension-grid">
              <el-checkbox 
               v-for="item in competencyTags.slice(10,50)" 
                :key="item.id" 
                 v-model="item.selected"
                 @change="(val: boolean) => handleCompetencyChange(item, val)" 
                  class="custom-checkbox">
                <div class="ability-label">
                  <span>{{ item.name }}</span>
                 <!--  <span v-if="item.isCustom" class="custom-tag">自定义</span> -->
                <!--   <el-tooltip content="考察候选人的XXXX能力" placement="top">
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip> -->
                </div>
              </el-checkbox>
              
              <!-- 显示自定义维度 -->
              <!-- <div 
               v-for="item in competencyTags.filter(tag => tag.isCustom)" 
                :key="'custom-' + item.id" 
                class="custom-dimension-item">
                <el-checkbox 
                 v-model="item.selected"
                 @change="(val: boolean) => handleCompetencyChange(item, val)" 
                  class="custom-checkbox">
                  <div class="ability-label">
                    <span>{{ item.name }}</span>
                    <span class="custom-tag">自定义</span>
                    <el-tooltip :content="item.description" placement="top" v-if="item.description">
                      <el-icon><QuestionFilled /></el-icon>
                    </el-tooltip>
                  </div>
                </el-checkbox>
                <el-button 
                  type="text" 
                  size="small" 
                  class="delete-custom-btn" 
                  @click="deleteCustomDimension(item)"
                  title="删除自定义维度">
                  <el-icon><Close /></el-icon>
                </el-button>
              </div> -->
            </div>
          </div>

          <!-- 自定义维度 -->
          <div class="custom-dimensions">
            <h3 style="color: #808080;">自定义维度</h3>
            <div class="dimension-form">
              <div class="dimension-row">
                <div class="dimension-input">
                 <!--  <div class="input-label">维度名称：</div> -->
                  <el-input style="width: 150px;" v-model="customDimension" placeholder="请输入维度名称" />
                </div>
                <div class="dimension-input">
                  <div class="input-label">特征描述：</div>
                  <el-input v-model="customDescription" style="width: 500px;" type="textarea" placeholder="请输入特征描述" />
                </div>
              </div>
              <div class="dimension-actions">
               <!--  <el-checkbox v-model="continueAdd"  class="custom-checkbox">
                  <div class="ability-label">
                  <span>继续新增</span>
                 
                </div>
                </el-checkbox>  -->
                <el-button type="primary" @click="addDimension" >添加</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 步骤2：面试题目 -->
      <div v-if="currentStep === 2" class="ai-video-content">
        <div class="interview-settings">
          <div class="interview-header">
             <div class="interview-actions">
              <el-button  plain class="custom-btn" @click="handleImportQuestion"><!-- @click="handleAddQuestion" -->
                  <el-icon><Plus /></el-icon>
                  自定义题目
              </el-button>
              <el-button  plain class="custom-btn" >
                  <el-icon><Document /></el-icon>
                  导入题目
              </el-button>
              <el-button 
                v-if="chatQuestions.length > 0"
                type="primary" 
                plain 
                class="custom-btn"
                :loading="autoGenerateLoading"
                @click="handleAutoGenerate"
              >
                <el-icon><Refresh /></el-icon>
                重新生成
              </el-button>
                
              <!-- 添加得分题和色盲题开关 -->
              <div class="question-switches">
                <!-- 添加题目数量控制 -->
                <div class="switch-item">
                  <span class="switch-label">开放题数量</span>
                  <el-input-number
                    v-model="questionCountSettings.openQuestionsCount"
                    :min="1"
                    :max="10"
                    size="small"
                    @change="handleQuestionCountChange"
                  />
                </div>
                <div class="switch-item">
                  <span class="switch-label">选择题数量</span>
                  <el-input-number
                    v-model="questionCountSettings.choiceQuestionsCount"
                    :min="1"
                    :max="20"
                    size="small"
                    @change="handleQuestionCountChange"
                  />
                </div>
               <!--  <div class="switch-item">
                  <span class="switch-label">得分题</span>
                  <el-switch 
                  style="margin-top:0px;"
                    v-model="questionSettings.enableScoreQuestions" 
                    @change="handleScoreQuestionsChange"
                  />
                </div>
                <div class="switch-item">
                  <span class="switch-label">色盲题</span>
                  <el-switch 
                  style="margin-top:0px;"
                    v-model="questionSettings.enableColorBlindQuestions" 
                    @change="handleColorBlindQuestionsChange"
                  />
                </div> -->
              </div>
            </div>
            <div class="interview-duration">
              <span>预计面试时长: </span>
              <span class="duration-value">{{ formatDuration }}</span>
              <span class="duration-tip">拖动试题卡片可改变试题顺序</span>
            </div>
          </div>
          
          <!-- <div class="interview-mode">
            <span>面试问答方式: </span>
            <span class="mode-value">传统读题模式</span>
            <el-button type="primary" plain size="small" class="customize-btn">定制面试间</el-button>
          </div> -->
            <div class="interview-content">
               <div class="interview-questions-container" v-loading="autoGenerateLoading" element-loading-text="AI正在生成题目...">
                <div class="no-questions" v-if="chatQuestions.length === 0">
                  <p>暂无题目</p>
                  <p class="ai-tip">点击"AI自动组题"按钮</p>
                  <p class="ai-tip">可根据您选择的能力类型一键组题</p>
                  <el-button 
                    type="success" 
                    class="auto-generate-btn" 
                    :loading="autoGenerateLoading"
                    @click="handleAutoGenerate"
                  >
                    AI自动组题
                  </el-button>
                  <el-button 
                    v-if="autoGenerateLoading && pollingController"
                    type="warning" 
                    plain
                    size="small"
                    @click="handleCancelGenerate"
                    style="margin-left: 10px;"
                  >
                    取消生成
                  </el-button>
                </div>
             <!-- :component-data="{
                  tag: 'transition-group',
                  name: !drag ? 'flip-list' : null
                }" -->
            <div class="question-list" v-else>
              <draggable 
                v-model="chatQuestions"
                item-key="id"
                handle=".drag-handle"
                @start="handleDragStart"
                @end="handleDragEnd"
                animation="200"
                ghost-class="sortable-ghost"
                chosen-class="sortable-chosen"
                drag-class="sortable-drag"
              >
                <template #item="{ element }">
                  <div class="question-card">
                      <div class="drag-handle">
                          <img src="../../../assets/dorp.png" alt="" class="dorp">
                        </div>
                    <div class="question-header">
                      <div class="question-title">
                      
                        <div class="title-content">
                          <div class="question-content">
                            <span class="question-number">题目{{ chatQuestions.indexOf(element) + 1 }}</span>
                            <span><span style="color: #0017ab;">{{ '「'+element.question_form_name +'」'}}</span>{{ element.title }}</span>
                          </div>
                          <div class="question-tags">
                            <el-tag
                              v-for="(tag, index) in (element.competency_tag_info || element.competency_tags || []).slice(0, 2)"
                              :key="tag.id"
                              effect="plain"
                              class="competency-tag"
                              size="small"
                            >
                              {{ tag.name }}
                            </el-tag>
                            <span 
                              v-if="(element.competency_tag_info ||element.competency_tags || []).length > 2" 
                              class="more-tags-indicator"
                            >
                              +{{ (element.competency_tag_info || element.competency_tags || []).length - 2 }}
                            </span>
                          </div>
                        </div>
                      </div>
                      <div class="question-actions" style="margin-top: 0px;">
                        <el-button type="text" @click="editQuestion(chatQuestions.indexOf(element))">
                          <el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button type="text" @click="deleteQuestion(chatQuestions.indexOf(element))">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </div>
                    </div>
                    
                    <div class="question-info">
                      <div class="info-item">
                        <!-- <span class="info-label">考察能力：</span> -->
                        <span>{{ element.scoring_reference }}</span>
                      </div>
                      <!-- <div class="info-item">
                        <span class="info-label">面试内容：</span>
                        <span>{{ element.content }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">对话目标：</span>
                        <span>{{ element.target }}</span>
                      </div> -->
                    </div>
                    <div class="question-actions" v-if="element.question_form==0">
                        <!-- <div class="weight-control">
                          <span class="weight-label">权重占比:</span>
                          <el-input-number 
                            v-model="element.weight" 
                            :min="0" 
                            :max="100"
                            :step="1"
                            size="small"
                            controls-position="right"
                          >
                            <template #suffix>%</template>
                          </el-input-number>
                        </div> -->
                        <div class="answer-limit">
                          <el-switch 
                            style="margin-top:0px; "
                              v-model="element.enable_follow_up" 
                              @change="handleFollowUpChange"
                            />
                          <span class="answer-label">回答不充分追问</span>
                        </div>
                        <div class="answer-limit">
                          <span class="answer-label">追问轮数</span>
                          <el-select v-model="element.maxAnswers" size="small" placeholder="请选择">
                            <el-option label="1次" :value="1" />
                           <!--  <el-option label="2次" :value="2" />
                            <el-option label="3次" :value="3" /> -->
                          </el-select>
                        </div>
                       
                    </div>
                    <div class="question-actions" v-if="element.question_form==1">
                      <div class="answer-limit">
                        <span class="answer-label">是否为红线题:</span>
                        <el-select v-model="element.is_required_correct" @change="handleIsRequiredCorrectChange(element.id,element.is_required_correct)" size="small" placeholder="请选择">
                          <el-option label="是" :value="true" />
                          <el-option label="否" :value="false" />
                        </el-select>
                      </div>
                    </div>
                  </div>
                </template>
              </draggable>
            </div>
              </div>
              
              <div class="multi-dimension-questions">
                <div class="dimension-title">已选胜任力考核维度</div>
                <div class="dimension-list">
                  <div v-for="(ability, index) in selectedAbilities" :key="ability.value" class="dimension-item">
                    <div class="dimension-header">
                      <div class="dimension-info">
                        <span class="ability-name">{{ ability.label }}</span>
                        <img src="../../../assets/sheng.png"  alt=""class="sheng">
                      </div>
                    </div>
                    <div class="dimension-content" @click="removeSelectedAbility(index)" title="点击删除此胜任力标签">
                      <div class="ability-description">{{ "—" }}</div>
                     <!--  <el-icon class="delete-icon"><Delete /></el-icon> -->
                    </div>
                  </div>
                </div>
              </div>
            </div>
        </div>
      </div>

      <!-- 步骤3：系统设置 -->
      <div v-if="currentStep === 3" class="ai-video-content">
        <div class="system-settings">
          <!-- 面试官形象设置 -->
          <div class="setting-section">
            <div class="section-header">请选择面试官形象</div>
            <div style="    display: flex;align-items: flex-start;">
              <div style="width: 100px;height: 170px;background-color: #f2f2f2; margin-right: 30px;border-radius: 10px;overflow: hidden;">
                <img v-if="interviewerAvatar" 
                    :src="interviewerAvatar" 
                    alt="" 
                    style="width: 100%;height: 100%;object-fit: cover;transform: translateZ(0);backface-visibility: hidden;">
              </div>
              <div>
                 <div class="interviewer-avatars">
                  <div
                    v-for="avatar in interviewerAvatars"
                    :key="avatar.id"
                    class="avatar-item"
                    :class="{ active: selectedInterviewer.id === avatar.id }"
                    @click="handleInterviewerSelect(avatar)"
                  >
                    <div class="avatar-wrapper">
                      <div class="avatar-circle" :class="{ selected: selectedInterviewer.id === avatar.id }">
                        <img :src="avatar.avatar_url || avatar.image" :alt="avatar.name" />
                      </div>
                      <div class="avatar-name" :title="avatar.name">{{ avatar.name }}</div>
                    </div>
                  </div>
                </div>
                                 <div class="setting-item" style="border: none;">
                    <div class="setting-label">「追问风格」</div>
                    <div class="setting-options">
                      <el-select v-model="settings.followUpStyle" placeholder="请选择" @change="handleSettingChange('followUpStyle', settings.followUpStyle)">
                        <el-option label="温和" value="1" />
                        <el-option label="严厉" value="2" />
                        <el-option label="严谨" value="3" />
                      </el-select>
                    </div>
                    <div class="setting-desc"></div>
                  </div>
              </div>
              </div>
               
           

            <!-- 面试设置选项 -->
            <div class="interview-settings">
              <div class="setting-item">
                <div class="setting-label">
                  <p>「回答视频保留」</p>
                </div>
                 <div class="setting-desc">
                  <p>选取后，将在报告中展示候选人的回答视频</p>
                 </div>
                <el-switch 
                  v-model="settings.keepVideo" 
                  @change="(value: boolean) => handleSettingChange('keepVideo', value)"
                />
               
              </div>

              <div class="setting-item">
                <div class="setting-label">
                  <p>「中断后作答限制」</p>
                </div>
                <div class="setting-options">
                  <el-radio 
                    v-model="settings.interruptionMode" 
                    label="current"
                    @change="handleSettingChange('interruptionMode', settings.interruptionMode)"
                  >
                  从当前问题重新作答
                  </el-radio>
                  <el-radio 
                    v-model="settings.interruptionMode" 
                    label="previous"
                    @change="handleSettingChange('interruptionMode', settings.interruptionMode)"
                  >
                  从头作答
                  </el-radio>
                  
                </div>
                <div class="setting-desc" style="width: 40px;"></div>
              </div>

              <div class="setting-item">
                <div class="setting-label">
                  <p>「智慧追问」</p>
                </div>
                <div class="setting-desc">
                 <p>追问将结合候选人资料情况，综合分析发问</p>
                </div>
                <el-switch 
                  v-model="settings.smartFollowUp" 
                  @change="(value: boolean) => handleSettingChange('smartFollowUp', value)"
                />
                
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="drawer-footer">
          <el-button v-if="currentStep > 1"  size="small" @click="prevStep">上一步</el-button>
          <el-button @click="cancelAIVideoConfig"  size="small">取消</el-button>
          <el-button v-if="currentStep < 3" type="primary" size="small" @click="nextStep" style="background-color: #0419a3;border-color: #0419a3;">下一步</el-button>
          <el-button v-else type="success" @click="finishConfig" size="small" style="background-color: #0419a3;border-color: #0419a3;">新增</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 在 template 中添加视频宣讲弹窗 -->
    <el-dialog
      title="新增视频宣讲"
      v-model="showVideoLectureDialog"
      width="35%"
      :close-on-click-modal="false"
      class="video-lecture-dialog"
    >
      <div class="video-lecture-form">
       <!--  <div class="form-item">
          <div class="form-label">步骤名称</div>
          <el-input 
            v-model="videoLectureForm.title" 
            placeholder="请输入步骤名称"
            maxlength="30"
            show-word-limit
          />
        </div> -->
        
        <div class="form-item">
          <div class="form-label">上传视频</div>
          <el-upload
            class="video-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            accept="video/*"
          >
            <div class="upload-area">
              <el-icon><Plus /></el-icon>
              <div class="upload-text">上传文件大小不超过500M</div>
            </div>
          </el-upload>
        </div>
        
        <div class="form-item">
          <div class="form-label">视频简介</div>
          <el-input
            v-model="videoLectureForm.description"
            type="textarea"
            rows="4"
            placeholder="视频简介会显示在视频下方的标题下方"
            maxlength="200"
            show-word-limit
          />
        </div>
        
      <!--   <div class="form-item">
          <div class="form-label">播放设置</div>
          <el-radio-group v-model="videoLectureForm.broadcastType">
            <el-radio label="required">必须看完</el-radio>
            <el-radio label="optional">看过即可</el-radio>
          </el-radio-group>
        </div> -->
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelVideoLecture">取消</el-button>
          <el-button type="primary" @click="confirmVideoLecture">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- AI实时对话抽屉 -->
    <el-drawer
      title="AI实时对话"
      v-model="showAIChatDialog"
      direction="rtl"
      size="60%"
      :close-on-click-modal="false"
      class="ai-chat-drawer"
      :destroy-on-close="false"
    >
      <div class="ai-chat-content">
        <!-- AI实时对话的配置内容 -->
        <div class="chat-settings">
          <div class="section-title">
            <div class="section-line"></div>
            <span>对话设置</span>
          </div>
          
          <!-- 添加按钮组 -->
          <div class="chat-actions">
            <el-button type="primary" plain @click="handleAddQuestion">
              <el-icon><Plus /></el-icon>
              添加问题
            </el-button>
            <el-button type="success" plain @click="handleImportQuestion">
              <el-icon><Document /></el-icon>
              导入问题
            </el-button>
          </div>

          <!-- 添加问题列表容器 -->
          <div class="chat-questions">
            <div v-if="chatQuestions.length === 0" class="empty-questions">
              <p>暂无问题</p>
              <p class="tip-text">点击"添加问题"或"导入问题"添加面试问题</p>
            </div>
            <div v-else class="question-list">
              <draggable v-model="chatQuestions" item-key="id" handle=".drag-handle">
                <template #item="{ element, index }">
                  {{ element }}
                  <div class="question-card">
                    <div class="question-header">
                      <div class="question-title">
                        <span class="question-number">题目{{ index + 1 }}</span>
                        <span>{{ element.question }}</span>
                      </div>
                      <div class="question-actions">
                        <div class="weight-control">
                          <span class="weight-label">权重占比:</span>
                          <el-input-number 
                            v-model="element.weight" 
                            :min="0" 
                            :max="100"
                            :step="1"
                            size="small"
                            controls-position="right"
                          >
                            <template #suffix>%</template>
                          </el-input-number>
                        </div>
                        <div class="answer-limit">
                          <span class="answer-label">最多回答次数</span>
                          <el-select v-model="element.maxAnswers" size="small" placeholder="请选择">
                            <el-option label="1次" :value="1" />
                            <el-option label="2次" :value="2" />
                            <el-option label="3次" :value="3" />
                          </el-select>
                        </div>
                        <el-button type="text" @click="editQuestion(index)">
                          <el-icon><Edit /></el-icon>
                        </el-button>
                        <el-button type="text" @click="deleteQuestion(index)">
                          <el-icon><Delete /></el-icon>
                        </el-button>
                      </div>
                    </div>
                    
                    <div class="question-info">
                      <div class="info-item">
                        <span class="info-label">考察能力：</span>
                        <span>{{ element.ability }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">面试内容：</span>
                        <span>{{ element.content }}</span>
                      </div>
                      <div class="info-item">
                        <span class="info-label">对话目标：</span>
                        <span>{{ element.target }}</span>
                      </div>
                    </div>
                  </div>
                </template>
              </draggable>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="drawer-footer">
          <el-button @click="cancelAIChatConfig">取消</el-button>
          <el-button type="primary" @click="handleAIChatConfig">确认</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 在 template 中添加问题编辑弹框 -->
    <el-dialog
      title="编辑问题"
      v-model="showQuestionDialog"
      width="500px"
      :close-on-click-modal="false"
      class="question-dialog"
    >
      <div class="question-form">
        <div class="form-item">
          <div class="form-label">
            题目内容<span class="required">*</span>
          </div>
          <el-input 
            v-model="questionForm.content"
            type="textarea"
            rows="4"
            placeholder="请描述一次你如何在紧迫的时间内完成一个复杂的后端开发任务的经历"
            maxlength="300"
            show-word-limit
          />
        </div>

        <div class="form-item">
          <div class="form-label">胜任力标签</div>
          <el-select
            v-model="competencyTagsValue"
            placeholder="请选择胜任力标签"
            class="full-width"
            multiple
          >
            <el-option 
              v-for="tag in competencyTagOptions" 
              :key="tag.id"
              :label="tag.name"
              :value="tag.id"
            />
          </el-select>
          <div class="form-tip">选择胜任力标签和胜任力标签，可多选</div>
        </div>

        <div class="form-item">
          <div class="form-label">
            胜任力配置
          </div>
          <div class="competency-config">
            <div class="config-row">
              <span class="config-label">标签</span>
              <span class="config-label">权重</span>
              <!-- <el-button 
                type="text" 
                size="small" 
                @click="distributeWeightsEvenly"
                style="color: #409eff; font-size: 12px;"
              >
                平均分配
              </el-button> -->
             <!--  <span class="config-label">级别</span> -->
            </div>
            <div class="config-row" v-for="(tag, index) in questionForm.competency_tags" :key="tag.id">
              <span class="tag-name">{{ tag.name }}</span>
              <el-input-number 
                v-model="tag.weight" 
                :min="0" 
                :max="100" 
                :step="1" 
                controls-position="right"
                @change="(value) => handleWeightChange(index, value)"
              /> %
            <!--   <el-input-number v-model="tag.importance" :min="1" :max="5" :step="1" controls-position="right" /> -->
            </div>
          </div>
          <div class="form-tip">
            配置各个胜任力标签的权重，总和需要100%
            <span class="weight-sum" :class="{ 'weight-error': getTotalWeight() !== 100 }">
              (当前总计: {{ getTotalWeight() }}%)
            </span>
            <br/>
            <el-icon style="color: #409eff; margin-right: 4px; margin-top: 4px;"><InfoFilled /></el-icon>
            <span style="color: #909399; font-size: 11px;">
              修改任意权重时，其他权重会自动按比例调整以保持总和为100%。点击"平均分配"可快速平均分配所有权重。
            </span>
          </div>
        </div>

        <div class="form-item">
          <div class="form-label">题目形式</div>
          <el-select
            v-model="questionForm.type"
            placeholder="开放问题"
            class="full-width"
            @change="handleQuestionTypeChange"
          >
            <el-option label="开放问题" value="open" />
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="填空题" value="fill" />
            <el-option label="自言语" value="self" />
          </el-select>
          <div class="form-tip">选择题目的形式：开放问题、单选题、多选题、填空题、自言语</div>
        </div>

        <div class="form-item">
          <div class="form-label">适用职位</div>
          <el-select
            v-model="questionForm.position"
            placeholder="请选择适用职位类型"
            class="full-width"
            multiple
          >
            <el-option 
              v-for="pos in positionOptions" 
              :key="pos.value"
              :label="pos.label"
              :value="pos.value"
            />
          </el-select>
          <div class="form-tip">选择题目适用的职位类型，可多选</div>
        </div>
        <div class="form-item" v-if="questionForm.question_form === 1 || questionForm.question_form === 2">
          <div class="form-label">选项</div>
          <div>
            <div class="option-header" style="display: flex; margin-bottom: 10px; font-weight: bold;">
              <span style="flex: 1;">选项内容</span>
              <span style="width: 80px; text-align: center;">是否正确</span>
            </div>
            <div 
              v-for="(option, index) in questionForm.options" 
              :key="index" 
              class="option-item" 
              style="display: flex; align-items: center; margin-bottom: 10px;"
            >
              <el-input 
                v-model="option.text" 
                placeholder="请输入选项内容" 
                style="flex: 1; margin-right: 10px;"
              />
              <el-tooltip 
                content="设置为正确答案" 
                placement="top" 
                effect="light"
              >
                <div 
                  @click="() => {
                    if (questionForm.question_form === 1) {
                      // 单选题：只能有一个正确答案
                      questionForm.options.forEach((item, idx) => {
                        item.is_correct = (idx === index);
                      });
                    } else {
                      // 多选题：可以有多个正确答案
                      option.is_correct = !option.is_correct;
                    }
                  }"
                  style="cursor: pointer; width: 80px; text-align: center;"
                >
                  <template v-if="questionForm.question_form === 1">
                    <!-- 单选题使用单选按钮 -->
                    <el-radio 
                      v-model="option.is_correct"
                      :label="true"
                    />
                  </template>
                  <template v-else>
                    <!-- 多选题使用复选框 -->
                    <el-checkbox 
                      v-model="option.is_correct"
                    />
                  </template>
                </div>
              </el-tooltip>
            </div>
            <div style="display: flex; justify-content: space-between; margin-top: 10px;">
              <el-button 
                type="primary" 
                @click="() => {
                  // 确保options数组已初始化
                  if (!questionForm.options) {
                    questionForm.options = [];
                  }
                  // 添加新选项时自动设置排序值
                  const sort = questionForm.options.length > 0 ? 
                    Math.max(...questionForm.options.map(o => o.sort || 0)) + 1 : 1;
                  questionForm.options.push({ option_text: '', is_correct: false, sort });
                }"
              >
                添加选项
              </el-button>
              
              <el-button 
                v-if="questionForm.options && questionForm.options.length > 2"
                type="danger" 
                @click="() => {
                  questionForm.options.pop();
                }"
              >
                删除最后一项
              </el-button>
            </div>
          </div>
          <div class="form-tip">添加选项并设置正确答案，单选题只能有一个正确答案，多选题可以有多个正确答案</div>
        </div>

        <div class="form-item">
          <div class="form-label">分类</div>
          <el-select
            v-model="questionForm.category"
            placeholder="请选择题目分类"
            class="full-width"
          >
            <el-option 
              v-for="cat in categoryOptions" 
              :key="cat.value"
              :label="cat.label"
              :value="cat.value"
            />
          </el-select>
          <div class="form-tip">选择题目所属分类</div>
        </div>

        <div class="form-item">
          <div class="form-label">标签</div>
          <el-select
            v-model="questionForm.tags"
            placeholder="请选择标签"
            class="full-width"
            multiple
          >
            <el-option 
              v-for="tag in tagOptions" 
              :key="tag.value"
              :label="tag.label"
              :value="tag.value"
            />
          </el-select>
          <div class="form-tip">选择题目相关标签，可多选</div>
        </div>

        <div class="form-item">
          <div class="form-label">建议时长(秒)</div>
          <el-input-number 
            v-model="questionForm.suggestedDuration" 
            :min="0" 
            :step="1" 
            controls-position="right"
            placeholder="请输入建议回答时长"
            class="full-width"
          />
          <div class="form-tip">建议回答题目的时长，单位为秒</div>
        </div>
        <div class="form-item">
          <div class="form-label">评价标准</div>
          <el-input v-model="questionForm.scoring_reference"  type="textarea"
          rows="4" placeholder="评分标准说明，例如：【团队协作能力】1.优秀：xxxxxx。2.xxxx。3.一般：xxxxx。" class="full-width" />
          <div class="form-tip">评分标准说明，例如：【团队协作能力】1.优秀：xxxxxx。2.xxxx。3.一般：xxxxx。</div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelAddQuestion">取消</el-button>
          <el-button type="primary" @click="confirmAddQuestion">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加心理题选择对话框 -->
    <el-dialog
      title="选择题目"
      v-model="showQuestionSelectDialog"
      width="30%"
      :close-on-click-modal="false"
      class="question-select-dialog"
    >
      <div class="question-select-content">
        <!-- 搜索栏 -->
       <!--  <div class="search-bar">
          <div class="search-inputs">
            <el-input
              v-model="questionSearchKeyword"
              placeholder="请输入关键词搜索题目"
              clearable
              @clear="handleQuestionSearch"
              @keyup.enter="handleQuestionSearch"
              style="width: 300px; margin-right: 10px;"
            >
              <template #append>
                <el-button @click="handleQuestionSearch">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-select 
              v-model="questionListQuery.question_form" 
              placeholder="题目类型"
              clearable
              @change="handleQuestionSearch"
              style="width: 120px;"
            >
              <el-option label="开放问题" :value="0" />
              <el-option label="单选题" :value="1" />
            </el-select>
          </div>
        </div> -->

        <!-- 题目列表 -->
        <!-- <div class="question-lists">
          <el-table
            :data="questionList"
            style="width: 100%"
            @selection-change="handleQuestionSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column prop="question" label="题目标题" />
            <el-table-column prop="question_form_name" label="题目类型" width="100"/>
          </el-table>
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="questionListQuery.page"
              v-model:page-size="questionListQuery.pageSize"
              :total="totalQuestions"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleQuestionSizeChange"
              @current-change="handleQuestionPageChange"
            />
          </div>
        </div> -->
          <el-tree
          ref="treeRef"
          :data="treeData"
          node-key="id"
          :props="defaultProps"
          default-expand-all
          highlight-current
          @node-click="handleNodeClick"
        >
          <template #default="{ node, data }">
            <div class="custom-tree-node">
              <div class="node-label" style="display: flex;align-items: center;">
                <el-icon><Folder /></el-icon>
                <span class="ml-2">{{ data.title }}</span>
              </div>
            </div>
          </template>
        </el-tree>

      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelQuestionSelect">取消</el-button>
          <el-button type="primary" @click="confirmQuestionSelect" style="background-color: #ed7d31;border-color: #ed7d31;">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 自定义题目创建对话框 -->
    <el-dialog
      title="创建自定义题目"
      v-model="showQuestionBankFormDialog"
      width="40%"
      :close-on-click-modal="false"
      class="question-bank-form-dialog"
      :before-close="handleQuestionBankFormCancel"
    >
      <QuestionBankForm
        v-model="questionBankFormData"
        :is-edit="isEditingQuestion"
        @submit="handleQuestionBankFormSubmit"
        @cancel="handleQuestionBankFormCancel"
      />
    </el-dialog>

    <!-- 修改资料收集对话框模板 -->
    <el-dialog
      title="资料收集"
      v-model="showDataCollectionDialog"
      width="900px"
      :close-on-click-modal="false"
      class="data-collection-dialog"
    >
      <div class="data-collection-form">
        <!-- 字段配置面板 -->
        <div class="field-config-panel">
          <div class="panel-header">
            <h3>字段显示配置</h3>
            <!-- <el-button type="primary" size="small" @click="saveFieldConfig">保存配置</el-button> -->
          </div>
          <div class="field-config-list">
            <!-- 基本信息部分 -->
            <div class="section-title">基本信息</div>
            <el-row :gutter="20">
              <el-col :span="8" v-for="(field, key) in getBasicFields()" :key="key">
                <div class="field-config-item">
                  <span class="field-label">
                    {{ field.label }}
                   <!--  <el-tag v-if="field.required" size="small" type="danger" class="required-tag">必填</el-tag> -->
                  </span>
                  <el-tooltip
                    content="切换显示/隐藏"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      
                      class="custom-switch"
                    />
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>

            <!-- 家庭成员信息部分 -->
            <div class="section-title">家庭成员信息</div>
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="field-config-item">
                  <span class="field-label">
                    {{ fieldConfig.family_member.label }}
                    <el-tag v-if="fieldConfig.family_member.visible" size="small" type="success">已启用</el-tag>
                  </span>
                  <el-switch v-model="fieldConfig.family_member.visible" class="custom-switch" />
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="fieldConfig.family_member.visible">
              <el-col :span="8" v-for="(field, key) in fieldConfig.family_member.fields" :key="key">
                <div class="field-config-item sub-field">
                  <span class="field-label">
                    {{ field.label }}
                    <!-- <el-tag v-if="field.required" size="small" type="danger" class="required-tag">必填</el-tag> -->
                  </span>
                  <el-tooltip
                    content="切换显示/隐藏"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      class="custom-switch"
                    />
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>

            <!-- 教育经历部分 -->
            <div class="section-title">教育经历</div>
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="field-config-item">
                  <span class="field-label">
                    {{ fieldConfig.education.label }}
                    <el-tag v-if="fieldConfig.education.visible" size="small" type="success">已启用</el-tag>
                  </span>
                  <el-switch v-model="fieldConfig.education.visible" class="custom-switch" />
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="fieldConfig.education.visible">
              <el-col :span="8" v-for="(field, key) in fieldConfig.education.fields" :key="key">
                <div class="field-config-item sub-field">
                  <span class="field-label">
                    {{ field.label }}
                   <!--  <el-tag v-if="field.required" size="small" type="danger" class="required-tag">必填</el-tag> -->
                  </span>
                  <el-tooltip
                    content="切换显示/隐藏"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                    
                      class="custom-switch"
                    />
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>

            <!-- 专业技能部分 -->
            <div class="section-title">专业技能</div>
            <el-row :gutter="20">
              <el-col :span="8" v-for="(field, key) in getSkillFields()" :key="key">
                <div class="field-config-item">
                  <span class="field-label">
                    {{ field.label }}
                    <!-- <el-tag v-if="field.required" size="small" type="danger" class="required-tag">必填</el-tag> -->
                  </span>
                  <el-tooltip
                    content="切换显示/隐藏"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                    
                      class="custom-switch"
                    />
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>

            <!-- 工作经历部分 -->
            <div class="section-title">工作经历</div>
            <el-row :gutter="20">
              <el-col :span="24">
                <div class="field-config-item">
                  <span class="field-label">
                    {{ fieldConfig.work_experience.label }}
                    <el-tag v-if="fieldConfig.work_experience.visible" size="small" type="success">已启用</el-tag>
                  </span>
                  <el-switch v-model="fieldConfig.work_experience.visible" class="custom-switch" />
                </div>
              </el-col>
            </el-row>
            <el-row :gutter="20" v-if="fieldConfig.work_experience.visible">
              <el-col :span="8" v-for="(field, key) in fieldConfig.work_experience.fields" :key="key">
                <div class="field-config-item sub-field">
                  <span class="field-label">
                    {{ field.label }}
                   <!--  <el-tag v-if="field.required" size="small" type="danger" class="required-tag">必填</el-tag> -->
                  </span>
                  <el-tooltip
                    content="切换显示/隐藏"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      
                      class="custom-switch"
                    />
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelDataCollection">取消</el-button>
          <el-button type="primary" @click="saveFieldConfig">确认</el-button><!-- confirmDataCollection -->
                  </span>
      </template>
    </el-dialog>

    <!-- 添加简历收集对话框 -->
    <el-dialog
      title="简历收集"
      v-model="showResumeCollectionDialog"
      width="500px"
      :close-on-click-modal="false"
      class="resume-collection-dialog"
    >
      <div class="resume-collection-form">
        <div class="form-item">
          <div class="form-label">步骤名称</div>
          <el-input 
            v-model="resumeCollectionForm.title" 
            placeholder="请输入步骤名称"
            maxlength="30"
            show-word-limit
                  />
                </div>
        
        <!-- <div class="form-item">
          <div class="form-label">必填项</div>
          <el-switch v-model="resumeCollectionForm.isRequired" />
          <span class="switch-label">{{ resumeCollectionForm.isRequired ? '开启' : '关闭' }}</span>
        </div>
        
        <div class="resume-preview">
          <div class="preview-title">简历收集预览</div>
          <div class="preview-content">
            <div class="preview-item">
              <div class="item-label">姓名</div>
              <div class="item-input"></div>
              <div class="item-required" v-if="resumeCollectionForm.isRequired">*</div>
            </div>
            <div class="preview-item">
              <div class="item-label">手机号</div>
              <div class="item-input"></div>
              <div class="item-required" v-if="resumeCollectionForm.isRequired">*</div>
            </div>
            <div class="preview-item">
              <div class="item-label">邮箱</div>
              <div class="item-input"></div>
              <div class="item-required" v-if="resumeCollectionForm.isRequired">*</div>
            </div>
            <div class="preview-item">
              <div class="item-label">上传简历</div>
              <div class="item-upload">
                <el-icon><Plus /></el-icon>
              </div>
              <div class="item-required" v-if="resumeCollectionForm.isRequired">*</div>
            </div>
          </div>
        </div> -->
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelResumeCollection">取消</el-button>
          <el-button type="primary" @click="confirmResumeCollection">确认</el-button>
                    </span>
      </template>
    </el-dialog>

    <!-- 添加代码测试对话框 -->
    <el-dialog
      title="添加代码笔试步骤"
      v-model="showCodeTestDialog"
      width="500px"
      :close-on-click-modal="false"
      class="code-test-dialog"
    >
      <div class="code-test-form">
        <div class="form-item">
          <div class="form-label">步骤名称</div>
          <el-input 
            v-model="codeTestForm.title" 
            placeholder="请输入步骤名称"
            maxlength="30"
            show-word-limit
          />
        </div>
        
        <div class="form-item">
          <div class="form-label">自动评判试卷</div>
          <el-switch v-model="codeTestForm.autoJudge" />
          <span class="switch-label">{{ codeTestForm.autoJudge ? '开启' : '关闭' }}</span>
        </div>
        
        <div class="form-item">
          <div class="form-label">添加考试试卷</div>
          <div class="test-paper-selector">
            <div class="empty-paper" v-if="!codeTestForm.selectedPaper">
              <el-button type="primary" plain @click="handleSelectPaper">
                <el-icon><Plus /></el-icon>
                添加考卷
              </el-button>
              <p class="tip-text">多选时，考生会随机分配到一套试卷</p>
            </div>
            <div class="selected-paper" v-else>
              <div class="paper-info">
                <div class="paper-title">{{ codeTestForm.selectedPaper.title }}</div>
                <div class="paper-meta">
                  <span>{{ codeTestForm.selectedPaper.questionCount }}道题</span>
                  <span>{{ codeTestForm.selectedPaper.duration }}分钟</span>
                  <span>{{ codeTestForm.selectedPaper.difficulty }}</span>
                </div>
              </div>
              <div class="paper-actions">
                <el-button type="text" @click="handleViewPaper">查看</el-button>
                <el-button type="text" @click="handleChangePaper">更换</el-button>
                <el-button type="text" @click="handleRemovePaper">删除</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCodeTest">取消</el-button>
          <el-button type="primary" @click="confirmCodeTest">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加打字测试对话框 -->
    <el-drawer
      title="添加打字测试步骤"
      v-model="showTypingTestDialog"
      size="60%"
      :close-on-click-modal="false"
      class="typing-test-dialog"
      :destroy-on-close="false"
    >
      <div class="typing-test-form">
        <div class="form-item">
          <div class="form-label">选择文章</div>
          <div class="article-selection">
            <el-button type="primary" size="small" class="add-article-btn">
              <el-icon><Plus /></el-icon>
              添加文章
            </el-button>
          </div>
        </div>
        
        <div class="form-item">
          <div class="form-label">候选人选择文章方式</div>
          <el-radio-group v-model="typingTestForm.selectionMode">
            <el-radio label="random">随机抽取</el-radio>
            <el-radio label="self">候选人自主选择</el-radio>
          </el-radio-group>
        </div>
        
        <div class="form-item">
          <div class="form-label">测试时间</div>
          <div class="time-input-container">
            <el-input v-model="typingTestForm.duration" class="time-input" />
            <span class="time-unit">分钟</span>
          </div>
        </div>
        
        <div class="form-item">
          <div class="form-label">登录界面预览图（建议尺寸1024*768像素，最大不要超过5M）</div>
          <el-upload
            class="preview-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
          >
            <div class="upload-area">
              <el-icon><Plus /></el-icon>
              <div class="upload-text">添加图片</div>
            </div>
          </el-upload>
        </div>
        
        <div class="form-item">
          <div class="form-label">注意事项内容（在登录界面显示）</div>
          <el-input
            v-model="typingTestForm.notes"
            type="textarea"
            rows="4"
            placeholder="请输入注意事项内容"
            maxlength="300"
            show-word-limit
          />
        </div>
        
        <div class="form-item">
          <div class="form-label">测试页面标题</div>
          <el-input 
            v-model="typingTestForm.pageTitle" 
            placeholder="测试页面标题"
          />
        </div>
        
        <div class="form-item">
          <div class="form-label">视频监控</div>
          <el-checkbox v-model="typingTestForm.videoMonitoring">视频监控</el-checkbox>
        </div>
        
        <div class="form-item">
          <div class="form-label">通过标准</div>
          <div class="criteria-options">
            <el-checkbox v-model="typingTestForm.passCriteria.speed">速度</el-checkbox>
            <el-checkbox v-model="typingTestForm.passCriteria.accuracy">正确率</el-checkbox>
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelTypingTest">取消</el-button>
          <el-button type="primary" @click="confirmTypingTest">保存</el-button>
        </span>
      </template>
    </el-drawer>

    <!-- 面试设置弹窗 -->
    <el-dialog
      title="面试设置"
      v-model="showInterviewSettingsDialog"
      width="60%"
      :close-on-click-modal="false"
      class="interview-settings-dialog"
    >
      <div class="interview-settings-content">
        <!-- 防作弊设置 -->
        <div class="settings-section">
          <div class="section-header">
            <span class="section-title">防作弊设置</span>
          </div>
          
          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">「人脸一致性检测」</span>
              <p class="setting-desc">该强调，非本人操作人脸可视化提醒和警示，默认开启</p>
            </div>
            <el-switch v-model="interviewSettings.faceConsistency" :disabled="true"/>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">「 防截屏 / 录屏 」</span>
              <p class="setting-desc">该强调，非本人前来体验截屏录屏以上行为，为防止提醒</p>
            </div>
            <el-switch v-model="interviewSettings.preventScreenshot" :disabled="true"/>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">「 切 屏 预 制 」</span>
              <p class="setting-desc">该强调，非本人前使用切屏处理用页面，为防作弊警示</p>
            </div>
            <el-switch v-model="interviewSettings.screenSwitchAlert" :disabled="true">
              <span class="switch-desc">切屏超过 2 次关闭，作答本关面试</span>
            </el-switch>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">「 情 绪 识 别」</span>
              <p class="setting-desc">该现已，条件较差以及入侵过程中的作弊，条件等好等</p>
            </div>
            <el-switch v-model="interviewSettings.positionDetection" />
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">「 眼 动 检 测 」</span>
              <p class="setting-desc">视实检测候选人的眼动频率进行分析，页面等较等</p>
            </div>
            <el-switch v-model="interviewSettings.eyeMovementDetection" />
          </div>
        </div>

        <!-- 其他设置 -->
        <div class="settings-section">
          <div class="section-header">
            <span class="section-title">其他设置</span>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">重复面试</span>
              <div class="setting-desc-container">
                <p class="setting-desc" style="">选取后，将允许面试者进行重复面试</p>
                <el-switch v-model="interviewSettings.reviewInterview" />
              </div>
            </div>
           
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">开场词</span>
              <div v-if="!isEditingBeforeStart" class="setting-desc-container">
                <p class="setting-desc">{{ interviewSettings.beforeStartText }}</p>
                <el-button type="text" class="edit-desc-btn" @click="startEditBeforeStart">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
              <div v-else class="desc-edit-container">
                <el-input
                  v-model="editingBeforeStartText"
                  type="textarea"
                  rows="2"
                  placeholder="请输入开始前提示内容"
                  
                  show-word-limit
                /><!-- maxlength="100" -->
                <div class="desc-edit-actions">
                  <el-button size="small" @click="cancelEditBeforeStart">取消</el-button>
                  <el-button size="small" type="primary" @click="saveBeforeStart">保存</el-button>
                </div>
              </div>
            </div>
           <!--  <el-switch v-model="interviewSettings.beforeStart" /> -->
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">开始后提醒</span>
              <div v-if="!isEditingAfterStart" class="setting-desc-container">
                <p class="setting-desc">{{ interviewSettings.afterStartText }}</p>
                <el-button type="text" class="edit-desc-btn" @click="startEditAfterStart">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
              <div v-else class="desc-edit-container">
                <el-input
                  v-model="editingAfterStartText"
                  type="textarea"
                  rows="2"
                  placeholder="请输入开始后提醒内容"
                  maxlength="100"
                  show-word-limit
                />
                <div class="desc-edit-actions">
                  <el-button size="small" @click="cancelEditAfterStart">取消</el-button>
                  <el-button size="small" type="primary" @click="saveAfterStart">保存</el-button>
                </div>
              </div>
            </div>
           <!--  <el-switch v-model="interviewSettings.afterStartReminder" /> -->
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <span class="setting-name">结束语</span>
              <div v-if="!isEditingDisclaimer" class="setting-desc-container">
                <p class="setting-desc">{{ interviewSettings.disclaimerText }}</p>
                <el-button type="text" class="edit-desc-btn" @click="startEditDisclaimer">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </div>
              <div v-else class="desc-edit-container">
                <el-input
                  v-model="editingDisclaimerText"
                  type="textarea"
                  rows="2"
                  placeholder="请输入免责声明内容"
                  maxlength="200"
                  show-word-limit
                />
                <div class="desc-edit-actions">
                  <el-button size="small" @click="cancelEditDisclaimer">取消</el-button>
                  <el-button size="small" type="primary" @click="saveDisclaimer">保存</el-button>
                </div>
              </div>
            </div>
           <!--  <el-switch v-model="interviewSettings.disclaimer" /> -->
          </div>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelInterviewSettings">取消</el-button>
          <el-button type="primary" @click="confirmInterviewSettings">完成</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 绑定综合素质问题 -->
    <el-dialog
      title="选择题目"
      v-model="QuestionSelectDialog"
      width="70%"
      :close-on-click-modal="false"
      class="question-select-dialog"
    >
      <div class="question-select-content">
        
        <el-row class="document-el-row">
          <el-col :span="3">
            <div class="document-box document-left-box">
              <TreeList ref="treeListRef" :treeData="documentTreeData"
              @treeClick="handleTreeClick"
              @updateDocument="handleUpdateDocument"
              @deleteDocument="handleDeleteDocument" />
            </div>
          </el-col>
          <el-col :span="21">
            <!-- 搜索栏 -->
              <div class="search-bar">
                <div class="search-inputs">
                  <el-input
                    v-model="questionSearchKeyword"
                    placeholder="请输入关键词搜索题目"
                    clearable
                    @clear="handleQuestionSearch"
                    @keyup.enter="handleQuestionSearch"
                    style="width: 300px; margin-right: 10px;"
                  >
                    <template #append>
                      <el-button @click="handleQuestionSearch">
                        <el-icon><Search /></el-icon>
                      </el-button>
                    </template>
                  </el-input>
                  <el-select 
                    v-model="questionListQuery.question_form" 
                    placeholder="题目类型"
                    clearable
                    @change="handleQuestionSearch"
                    style="width: 120px;"
                  >
                    <el-option label="开放问题" :value="0" />
                    <el-option label="单选题" :value="1" />
                    <el-option label="多选题" :value="2" />
                    <el-option label="看图选答案" :value="3" />
                    <el-option label="得分题" :value="4" />
                    <el-option label="追加型开放问题" :value="5" />
                    <el-option label="填空题" :value="6" />
                  </el-select>
                </div>
              </div>
                <!-- 题目列表 -->
            <div class="question-lists">
              <el-table
                :data="questionList"
                style="width: 100%"
                @selection-change="handleQuestionSelectionChange"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="question" label="题目标题" />
                <el-table-column prop="question_form_name" label="题目类型" width="100"/>
                <!-- <el-table-column prop="content" label="面试内容" show-overflow-tooltip />
                <el-table-column prop="target" label="对话目标" show-overflow-tooltip /> -->
              </el-table>

              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="questionListQuery.page"
                  v-model:page-size="questionListQuery.pageSize"
                  :total="totalQuestions2"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next"
                  @size-change="handleQSizeChange"
                  @current-change="handleQPageChange"
                />
              </div>
            </div>
          </el-col>
		</el-row>

       
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelQuestionSelect">取消</el-button>
          <el-button type="primary" @click="confirmSelect" style="background-color: #ed7d31;border-color: #ed7d31;">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 候选人提问环节配置弹窗 -->
    <el-dialog
      :title="editingCandidateQuestionsIndex >= 0 ? '编辑候选人提问环节' : '配置候选人提问环节'"
      v-model="showCandidateQuestionsDialog"
      width="600px"
      :close-on-click-modal="false"
      class="candidate-questions-dialog"
    >
      <div class="candidate-questions-form">
        <div class="form-item">
          <div class="form-label">
            环节名称<span class="required">*</span>
          </div>
          <el-input 
            v-model="candidateQuestionsForm.title"
            placeholder="请输入环节名称"
            maxlength="30"
            show-word-limit
          />
        </div>

        <div class="form-item">
          <div class="form-label">
            提问时长<span class="required">*</span>
          </div>
          <el-input-number
            v-model="candidateQuestionsForm.duration"
            :min="1"
            :max="30"
            :step="1"
            controls-position="right"
            style="width: 200px"
          />
          <span class="form-unit">分钟</span>
          <div class="form-tip">候选人可用于提问的总时长</div>
        </div>

        <!-- <div class="form-item">
          <div class="form-label">
            最多提问数量<span class="required">*</span>
          </div>
          <el-input-number
            v-model="candidateQuestionsForm.maxQuestions"
            :min="1"
            :max="10"
            :step="1"
            controls-position="right"
            style="width: 200px"
          />
          <span class="form-unit">个</span>
          <div class="form-tip">候选人最多可以提出的问题数量</div>
        </div> -->

        <div class="form-item">
          <div class="form-label">环节描述</div>
          <el-input
            v-model="candidateQuestionsForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入环节描述"
            maxlength="200"
            show-word-limit
          />
          <div class="form-tip">向候选人说明此环节的目的和意义</div>
        </div>

       <!--  <div class="form-item">
          <div class="form-label">环节设置</div>
          <div class="form-checkboxes">
            <el-checkbox v-model="candidateQuestionsForm.isRequired">
              必须环节（候选人必须完成此环节）
            </el-checkbox>
            <el-checkbox v-model="candidateQuestionsForm.allowSkip">
              允许跳过（候选人可选择跳过此环节）
            </el-checkbox>
          </div>
        </div>

        <div class="form-item">
          <div class="form-label">提问指引</div>
          <div class="guidelines-list">
            <div 
              v-for="(guideline, index) in candidateQuestionsForm.guidelines" 
              :key="index"
              class="guideline-item"
            >
              <el-input
                v-model="candidateQuestionsForm.guidelines[index]"
                placeholder="请输入提问指引"
                maxlength="100"
              >
                <template #append>
                  <el-button 
                    type="danger" 
                    @click="removeGuideline(index)"
                    v-if="candidateQuestionsForm.guidelines.length > 1"
                  >
                    删除
                  </el-button>
                </template>
              </el-input>
            </div>
            <el-button 
              type="primary" 
              plain 
              @click="addGuideline"
              v-if="candidateQuestionsForm.guidelines.length < 5"
            >
              <el-icon><Plus /></el-icon>
              添加指引
            </el-button>
          </div>
          <div class="form-tip">为候选人提供提问的指导建议，最多5条</div>
        </div> -->
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelCandidateQuestions">取消</el-button>
          <el-button type="primary" @click="confirmCandidateQuestions">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 肢体检测配置对话框 -->
    <el-dialog
      v-model="bodyDetectionConfigVisible"
      title="肢体检测配置"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="bodyDetectionConfig" label-width="120px">
        <el-form-item label="检测时长">
          <el-input-number 
            v-model="bodyDetectionConfig.duration" 
            :min="1"
            :max="30"
            :step="1"
            controls-position="right"
          /> 分钟
        </el-form-item>
        <el-form-item label="检测项目">
          <el-checkbox-group v-model="bodyDetectionConfig.detectionItems">
            <el-checkbox label="face">面部表情</el-checkbox>
            <el-checkbox label="pose">肢体姿态</el-checkbox>
            <el-checkbox label="gesture">手势动作</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="提示文本">
          <el-input
            v-model="bodyDetectionConfig.promptText"
            type="textarea"
            :rows="3"
            placeholder="请输入提示文本"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelBodyDetectionConfig" size="small">取消</el-button>
          <el-button type="primary" @click="saveBodyDetectionConfig" size="small">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox, ElDrawer } from 'element-plus';
import * as api from '../list/api';
import { Plus, Document, ArrowDown, Edit, Delete, InfoFilled, QuestionFilled, Search, Rank, Close } from '@element-plus/icons-vue';
import { GetList } from '../../questionBank/classList/api';
import { GetCompetencyList,GetQuestionList,GenerateQuestions,
  GetDraftList,SaveDraft,GetDigitalList,
  CreateConfig,GetConfig,UpdateConfig,AddDocument,
  GetOpeningSpeech,GetVideo,BatchBind,BatchUnbind,UpdateObj,
  GenerateCompetency,SaveCompetency,GetPositionTags,
  UpdateQuestion,GetPositionQuestions,CreateCompetency,
  BatchUpdateTags} from './api';
import draggable from 'vuedraggable';
import { updateFieldConfig } from './utils';
import type { ProfileFieldsConfig } from './types';
import { getPCAData } from '../../../utils/pcaData';
import QuestionBankForm from '../../questionBank/list/components/QuestionBankForm.vue';
import * as questionBankApi from '../../questionBank/list/api';
import TreeList from './treeList.vue';
import { GetDocumentTree, GetCategoryList, GetTagList,DeleteDocumentCategory } from '../../questionBank/positionList/api';
import { Session } from '/@/utils/storage';

// 添加 CompetencyTag 接口定义
interface CompetencyTag {
  id: number;
  name: string;
  selected?: boolean;
  weight?: number;
}

// 添加 InterviewerAvatar 接口定义
interface InterviewerAvatar {
  id: number;
  name: string;
  image?: string;
  avatar_url?: string;
}

// 添加选项接口定义
interface QuestionOption {
  id?: number;
  text: string;
  is_correct: boolean;
  sort?: number;
}

// 添加 ChatQuestion 接口定义
interface ChatQuestion {
  id?: number;
  title: string;
  ability: string;
  content: string;
  target: string;
  weight: number;
  maxAnswers: number;
  source: 'ai_generated' | 'custom_selected'; // 添加题目来源标识
  question_form?: number;
  question_form_name?: string;
  scoring_reference?: string;
  competency_tags?: CompetencyTag[];
  enable_follow_up?: boolean;
  options?: QuestionOption[];
}

// 添加 Paper 接口定义
interface Paper {
  id: number;
  title: string;
  questionCount: number;
  duration: number;
  difficulty: string;
}

interface AIVideoStep {
  name: string;
  id: string | number;
  aiConfig?: {
    abilities: string[];
  };
}

const router = useRouter();
const route = useRoute();
const positionId = ref(route.query.id as string);
const positionStatus = ref(false);
const drag = ref(false); // 添加拖拽状态变量

// 职位数据
const positionData = reactive({
  title: '',
  job_category: '',
  job_type_display: '',
  city: '',
  location: [] as string[] | string, // 修改类型定义
  location_str: '',
  address_detail: '',
  benefits: [],
  requirements: '',
  job_type: 0,
  salary_range: '',
  department: '',
  end_date: '',
  description: '',
  work_experience_required: '',
  education_required: '',
  competency_tags: [],
  options: [],
  status: 0
});

// 招聘流程数据 - 修改为普通数组而非 ref 对象，添加type字段用于重复检查
const recruitmentProcess = reactive([
  { id: 6, name: '简历收集', description: '简历收集', active: true, type: 'resume_collection',visible:true },
  { id: 5, name: '资料收集', description: '资料收集', active: true, type: 'data_collection',visible:true },
  { id: 2, name: 'AI考察', description: 'AI考察', active: true, type: 'ai_video',visible:true },
  { id: 8, name: '综合素质考察', description: '综合素质考察', active: true, type: 'common_sense',visible:true },
  { id: 9, name: '心理问题', description: '心理问题', active: true, type: 'psychological_problem',visible:true },
  { id: 7, name: '候选人提问', description: '时长5分钟，最多3个问题', active: true, type: 'candidate_questions', visible:true,
    config: {
      title: '候选人提问',
      duration: 5,
      maxQuestions: 3,
      description: '候选人可以向面试官提问关于公司、职位或团队的问题',
      isRequired: true,
      allowSkip: false,
      guidelines: [
        '请提出与职位、公司文化或团队相关的问题',
        '避免询问已在职位描述中明确说明的信息',
        '可以询问职业发展机会和团队工作方式'
      ]
    }
  },

 
 /*  { id: 1, name: '待核验', description: '待核验', active: true, type: 'pending_verification' }, */
  { id: 3, name: '已通过', description: '已通过', active: true, type: 'passed',visible:true },
  { id: 4, name: '已淘汰', description: '已淘汰', active: false, type: 'rejected',visible:true },
  
]);

// 是否显示流程编辑对话框
const showProcessDialog = ref(false);

// 定义可选的流程步骤类型
const processStepOptions = [
  { label: 'AI考察', value: 'ai_video' },
  { label: '视频宣讲', value: 'video_presentation' }, 
  { label: '肢体检测', value: 'body_detection' },  // 新增肢体检测选项
  /* { label: 'AI实时对话', value: 'ai_chat' },*/
  { label: '资料收集', value: 'data_collection' },
  { label: '简历收集', value: 'resume_collection' },
  { label: '候选人提问', value: 'candidate_questions' },
  { label: '心理问题', value: 'psychological_problem' },
  { label: '综合素质考察', value: 'common_sense' },
  /* { label: '代码测试', value: 'code_test' },
  { label: '打字测试', value: 'typing_test' } */
];
/* 选择问题 */
const QuestionSelectDialog = ref(false);
const handleQSizeChange = (size: number) => {
  questionList.pageSize = size;
  GetQuestionList({page:questionList.page,limit:questionList.pageSize,question_form:questionListQuery.question_form}).then((res:any)=>{
    if(res.data){
      questionList.value = res.data.items;
      questionListpage.page=res.data.page;
        questionListpage.pageSize=res.data.limit;
        totalQuestions2.value=res.data.total;
    }
  })
};
const handleQPageChange = (page: number) => {
  questionList.page = page;
  GetQuestionList({page:questionList.page,limit:questionList.pageSize,question_form:questionListQuery.question_form}).then((res:any)=>{
    if(res.data){
      questionList.value = res.data.items;
      questionListpage.page=res.data.page;
        questionListpage.pageSize=res.data.limit;
        totalQuestions2.value=res.data.total;
    }
  })
};

const confirmSelect = async () => {
  const selectedQuestionIds =selectedQuestions.value.map((item:any) => item.id);
  console.log('selectedQuestionIds', selectedQuestionIds);
  if (selectedQuestionIds.length === 0) {
    ElMessage.warning('请至少选择一个问题');
    return;
  }

  try {
    await AddDocument({
      position_id: route.query.id,
      question_id: selectedQuestionIds,
      duration: 60, // 默认时长，您可以根据需求调整
      tenant_id: Session.get('tenant_id')
    });
    
    // 更新已选择的问题列表
    const newSelectedQuestions = questionList.value.filter((item: any) => item.selected);
    selectedQuestions.value.push(...newSelectedQuestions);
    
    ElMessage.success('问题添加成功');
    QuestionSelectDialog.value = false;
  } catch (error: any) {
    console.error('添加问题失败:', error);
    if (error.code === 4000) {
      ElMessage.warning('该题目已绑定，请选择其他题目');
    } else {
      ElMessage.error('添加问题失败，请重试');
    }
  }
}

const handleAddCompetency = () => {
  competencyLoading.value = true;
  GenerateCompetency({
    position_id:route.query.id,
  }).then((res:any) => {
    res.data.forEach((item:any) => {
          item.selected = false;
        });
    competencyTags.value = res.data;
    console.log('res', res);
    competencyLoading.value = false;
  }).catch((err:any) => {
    console.log('err', err);
    competencyLoading.value = false;
  })
};

/* 工作地点 */
// 工作地点选项
const locationOptions = getPCAData();

// 修改处理地点选择变化的函数
const handleLocationChange = (value: any) => {
  console.log('地址选择变化:', value);
  if (value && Array.isArray(value) && value.length > 0) {
    const [provinceCode, cityCode, districtCode] = value;
    const province = locationOptions.find(p => p.code === provinceCode);
    let city, district;

    if (province && province.children) {
      city = province.children.find(c => c.code === cityCode);
      if (city && city.children) {
        district = city.children.find(d => d.code === districtCode);
      }
    }

   /*  // 保存名称
    formData.location_names = [
      province?.name || '',
      city?.name || '',
      district?.name || ''
    ].filter(Boolean);

    // 更新各个字段
    formData.province = province?.name || '';
    formData.city = city?.name || '';
    formData.district = district?.name || '';
    formData.location_str = formData.location_names.join('/'); */
  } else {
  /*   formData.location_names = [];
    formData.province = '';
    formData.city = '';
    formData.district = '';
    formData.location_str = ''; */
  }
};

const handleIsRequiredCorrectChange = (id: number, value: boolean) => {
    // UpdateObj({
    //     id: id,
    //     is_required_correct: value
    // }).then((res:any) => {
    //     console.log('res', res);
    // })
};

// 当前选择的添加位置
const currentAddIndex = ref(-1);
// 是否显示选项菜单
const showOptionsMenu = ref(false);
// 选项菜单的位置
const menuPosition = reactive({ top: '0px', left: '0px' });

// AI考察对话框显示状态
const showAIVideoDialog = ref(false);

// AI考察配置选项
const aiVideoOptions = reactive({
  qualityControl: false,
  teamwork: false,
  problemSolving: false,
  dataAnalysis: false,
  positionMatch: false,
  proactiveness: false,
  basicAbility: false,
  communication: false,
  serviceAwareness: false,
  xxxx: false
});

// 当前步骤
const currentStep = ref(1);

// 选中的能力列表
const selectedAbilities = ref([
  {
    label: '沟通能力',
    value: 'communication',
    level: 'CC',
    description: '能够清晰、准确地表达想法，善于倾听和理解他人的观点，具备良好的书面和口头表达能力。',
    expanded: false,
    isNew: true
  },
  {
    label: '团队协作',
    value: 'teamwork',
    level: 'CC',
    description: '能够与团队成员有效合作，共同完成目标，具备良好的团队精神和协作意识。',
    expanded: false,
    isNew: false
  }
]);

const toggleAbilityExpand = (ability:any) => {
  ability.expanded = !ability.expanded;
};

// 获取能力标签
const getAbilityLabel = (key: string) => {
  const abilityMap: Record<string, string> = {
    qualityControl: '质量控制',
    teamwork: '团队协作',
    problemSolving: '问题解决',
    dataAnalysis: '问题分析',
    taskManagement: '分析问题',
    productivity: '生产效率',
    manufacturingSkills: '制造制作技能',
    customerService: '客户服务技能',
    resistanceToPressure: '抗压能力-客户服务',
    workDefinition: '工作稳定-宣誓',
    selfIntroduction: '自我介绍-宣誓',
    detailOrientation: '细节关注',
    logicalThinking: '清晰逻辑思维',
    safetyAwareness: '安全意识',
    customerServiceAwareness: '客户服务意识',
    timeManagement: '时间管理',
    teamCooperation: '团队合作',
    timeManagementSkills: '时间管理能力',
    productEvaluation: '品鉴评估能力',
    basicQualifications: '基本素质',
    networkDeployment: '网位布署',
    remoteCooperation: '泡通协作',
    executionAbility: '执行能力',
    selfDiscipline: '自驱力',
    managementAbility: '管理能力',
    customerOrientation: '客户导向',
    stability: '稳定性',
    salesSkills: '销售技巧',
    responseAbility: '应变能力'
  };
  return abilityMap[key] || key;
};

// 排名设置
const rankSettings = reactive({
  min: 0,
  max: 100,
  minScore: 0.00,
  maxScore: 0.00
});

/* 回答不充分追问 */
const handleFollowUpChange = (value: boolean) => {
  console.log(value);
};

// AI模型版本
const aiModelVersion = ref('standard');

// 是否启用有效期
const validityEnabled = ref(false);

// 在 script setup 部分添加以下响应式变量
const showVideoLectureDialog = ref(false); // 控制视频宣讲弹窗显示
const videoLectureForm = reactive({
  title: '', // 步骤名称
  videoFile: null, // 视频文件
  description: '', // 视频简介
  broadcastType: 'required', // 播放设置：必须看完/看过即可
});

// 在 script setup 部分添加新的响应式变量
const showAIChatDialog = ref(false); // 控制AI实时对话抽屉显示

// 添加 AI 实时对话配置相关的响应式变量
const chatDuration = ref(15); // 默认15分钟
const maxQuestions = ref(5); // 默认5个问题

// 在 script setup 部分添加以下响应式变量
const showQuestionDialog = ref(false); // 控制添加问题弹框显示
const questionForm = reactive({
  id: '',
  content: '', // 题目内容
  competency_tags: [], // 胜任力标签
  weight: 100, // 权重占比，默认100%
  level: 1, // 胜任力级别，默认1级
  type: 'open', // 题目形式：开放问题/单选题/多选题/填空题/自言语
  question_form: 0, // 题目类型：0-开放问题，1-单选题，2-多选题
  options: [], // 选项列表
  position: [], // 适用职位
  category: '', // 分类
  tags: [], // 标签
  suggestedDuration: 60, // 建议时长，默认60秒
  scoring_reference: '' // 评分标准
});

// 定义胜任力标签类型
interface CompetencyTagItem {
  id: string;
  name: string;
  weight: number;
}

const getcompetency_tags = (value:any)=>{
  return value.map((item:any)=>{
    return item.id
  })
}
// 胜任力标签选项
const competencyTagOptions = ref<CompetencyTag[]>([]);

// 职位类型选项
const positionOptions = ref([
  { label: '后端开发', value: 'backend' },
  { label: '前端开发', value: 'frontend' },
  { label: '产品经理', value: 'product_manager' },
  { label: '项目经理', value: 'project_manager' },
  { label: '测试工程师', value: 'test_engineer' }
]);

// 题目分类选项
const categoryOptions = ref([
  { label: '技术能力', value: 'tech' },
  { label: '管理能力', value: 'management' },
  { label: '沟通能力', value: 'communication' },
  { label: '专业知识', value: 'professional' },
  { label: '个人素质', value: 'personal' }
]);

// 标签选项
const tagOptions = ref([
  { label: '时间管理', value: 'time_management' },
  { label: '压力处理', value: 'pressure_handling' },
  { label: '团队合作', value: 'team_cooperation' },
  { label: '问题分析', value: 'problem_analysis' },
  { label: '创新思维', value: 'innovative_thinking' }
]);

// 重置问题表单
const resetQuestionForm = () => {
  Object.assign(questionForm, {
    id: '',
    content: '',
    competency_tags: [],
    weight: 100,
    level: 1,
    type: 'open',
    question_form: 0,
    options: [],
    position: [],
    category: '',
    tags: [],
    suggestedDuration: 60,
    scoring_reference: ''
  });
};

// 取消添加问题
const cancelAddQuestion = () => {
  showQuestionDialog.value = false;
  resetQuestionForm();
};

// 确认修改问题
const confirmAddQuestion = async () => {
  // 表单验证
  if (!questionForm.content) {
    ElMessage.error('请输入题目内容');
    return;
  }

  // 验证胜任力配置
  if (!validateCompetencyConfig()) {
    return;
  }

  try {
    // 创建新的问题对象
    const newQuestion = {
      id: questionForm.id,
      content: questionForm.content,
      competency_tags: questionForm.competency_tags,
      options: questionForm.options,
      weight: questionForm.weight,
      level: questionForm.level,
      question_form: questionForm.question_form,
      position: questionForm.position,
      category: questionForm.category,
      suggestedDuration: questionForm.suggestedDuration,
      scoring_reference: questionForm.scoring_reference,
    };
    console.log(newQuestion);

    // TODO: 调用API保存问题
 /*     const response = await UpdateQuestion(newQuestion);
     console.log(response);
    if(response.code === 200){
      ElMessage.success('问题修改成功');
    }else{
      ElMessage.error('问题修改失败');
    } */
    // 关闭弹窗
    showQuestionDialog.value = false;
    
    // 重置表单
    resetQuestionForm();
    
    // 提示成功
   /*  ElMessage.success('问题修改成功'); */
    
    // 刷新问题列表
    // await loadQuestions();
  } catch (error) {
    console.error('添加问题失败:', error);
    ElMessage.error('添加问题失败，请重试');
  }
};

// 在 script setup 中添加以下响应式变量
const showDataCollectionDialog = ref(false); // 控制资料收集对话框显示
const dataCollectionForm = reactive({
  isRequired: false, // 开启评分开关
  questions: [] // 问题列表
});

// 修改问题类型定义
interface QuestionType {
  label: string;
  value: string;
  isVisible?: boolean;
  enableScoring?: boolean;
  isRequired?: boolean;
}

// 定义问题列表
const questionTypes = ref<QuestionType[]>([
  { 
    label: 'Q1', 
    value: 'q1',
    isVisible: true,
    enableScoring: false,
    isRequired: false
  },
  { 
    label: '请问你的毕业院校是哪里？', 
    value: 'school',
    isVisible: true,
    enableScoring: false,
    isRequired: true
  }
]);

// 添加简历收集相关的状态和方法
const showResumeCollectionDialog = ref(false);
const resumeCollectionForm = reactive({
  title: '简历收集',
  isRequired: true,
  steps: 4, // 默认步骤数
});

// 显示简历收集弹窗
const showResumeCollectionConfig = () => {
  showResumeCollectionDialog.value = true;
};

// 取消简历收集配置
const cancelResumeCollection = () => {
  showResumeCollectionDialog.value = false;
  // 重置表单
  Object.assign(resumeCollectionForm, {
    title: '简历收集',
    isRequired: true,
    steps: 4
  });
};

// 确认添加简历收集
const confirmResumeCollection = () => {
  // 创建新的简历收集步骤
  const newStep = {
    id: Date.now(),
    name: resumeCollectionForm.title,
    description: '简历收集',
    active: true,
    type: 'resume_collection',
    config: {
      ...resumeCollectionForm
    }
  };
  
  // 添加到流程中
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  
  // 关闭弹窗
  showResumeCollectionDialog.value = false;
  
  // 提示成功
  ElMessage.success('简历收集步骤已添加');
  
  // 重置表单
  cancelResumeCollection();
};

// AI自动组题loading状态
const autoGenerateLoading = ref(false);

// 题目设置选项
const questionSettings = reactive({
  enableScoreQuestions: false, // 得分题开关
  enableColorBlindQuestions: false, // 色盲题开关
  enableOpenQuestions: false // 开放问题开关
});

// 获取职位详情
const getPositionDetail = async () => {
  try {
    const id = route.query.id;
    if (!id) {
      ElMessage.error('职位ID不存在');
      return;
    }
    
    // 修复类型错误，创建符合InfoReq类型的对象
    const idValue = Array.isArray(id) ? id[0] : id;
    // 创建一个符合API要求的请求对象
    const infoReq = id
    const response = await api.GetObj(id); // 使用 infoReq 而不是 id
    if (response && response.data) {
      Object.assign(positionData, response.data);
      competencyTagOptions.value=response.data.competency_tags
      const config = await GetConfig(id);
      if (config && config.data) {
        getConfigId.value=config.data.id;
        
        // 根据配置状态初始化得分题和色盲题开关
        if (config.data.enable_psychological_test !== undefined) {
          questionSettings.enableScoreQuestions = config.data.enable_psychological_test;
        }
        if (config.data.enable_color_blind_test !== undefined) {
          questionSettings.enableColorBlindQuestions = config.data.enable_color_blind_test;
        }
      }
      // 设置职位状态
      positionStatus.value = positionData.status === 1;
    }
  } catch (error) {
    console.error('获取职位详情失败:', error);
    ElMessage.error('获取职位详情失败');
  }
};

// 返回列表页
const goBack = () => {
  router.push('/position/list');
};

// 编辑职位
const handleEdit = () => {
  router.push(`/position/list`);
};

// 分享职位
const handleShare = () => {
  ElMessage.success('分享链接已复制到剪贴板');
};

// 修改职位状态
const handleStatusChange = async (value: boolean) => {
  const id = route.query.id;
  try {
    const newStatus = value ? 1 : 0;

    // 如果是要开启职位，需要先检查视频状态
    if (value) {
      // 检查视频状态
      const videoStatusResponse = await api.CheckQuestionVideosStatus({
        position_id: id,
        tenant_id:Session.get('tenant_id')
      });

      if (videoStatusResponse.code === 2000) {
        const { is_all_completed, total_questions } = videoStatusResponse.data;
        
        // 检查视频是否全部完成且存在题目
        if (!is_all_completed || total_questions <= 0) {
          ElMessage.warning(`无法开启职位，原因：${total_questions <= 0 ? '当前职位没有设置面试题目' : '面试题目视频未全部生成完成'}`);
          // 恢复原状态
          positionStatus.value = !value;
          return;
        }
      } else {
        ElMessage.error('检查视频状态失败，请稍后重试');
        // 恢复原状态
        positionStatus.value = !value;
        return;
      }
    }

    await api.UpdateObj({
      id: id,
      status: newStatus
    });
    positionData.status = newStatus;
    ElMessage.success(`职位已${value ? '开启' : '关闭'}`);
  } catch (error) {
    console.error('修改状态失败:', error);
    ElMessage.error('修改状态失败');
    // 恢复原状态
    positionStatus.value = !value;
  }
};



// 编辑招聘流程
const handleEditProcess = () => {
  showProcessDialog.value = true;
};

// 保存招聘流程
const saveProcess = () => {
  showProcessDialog.value = false;
  ElMessage.success('招聘流程已更新');
};

// 取消编辑
const cancelEditProcess = () => {
  showProcessDialog.value = false;
};

// 删除流程步骤 - 删除后允许重新添加相同类型的步骤
const deleteProcessStep = (step: any,index: number) => {
  if(step.type=='ai_video'){
    showAIVideoDialog.value = false;
  }
  if(step.type=='ai_chat'){
    showAIChatDialog.value = false;
  }
  if(step.type=='ai_video'){
      UpdateConfig({
        id: getConfigId.value,
        enable_open_questions: false // 如果删除后还有AI考察，则保持为true，否则设为false
      }).then((res:any) => {
        if(res.code == 2000) {
          ElMessage.success('删除成功');
        } else {
          ElMessage.error('删除失败');
        }
      })
  }
  if(step.type=='psychological_problem'){ // 处理综合素质考察删除
    UpdateConfig({
      id: getConfigId.value,
      enable_scoring_questions: false // 删除综合素质考察时，将enable_scoring_questions设置为false
    }).then((res:any) => {
      if(res.code == 2000) {
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
    })
  }
  if(step.type=='common_sense'){ // 处理综合素质考察删除
    UpdateConfig({
      id: getConfigId.value,
      enable_single_choice: false, // 删除综合素质考察时，将enable_scoring_questions设置为false
      enable_multiple_choice: false,
      enable_image_choice: false,
      enable_fill_blank:false,
    }).then((res:any) => {
      if(res.code == 2000) {
        ElMessage.success('删除成功');
      } else {
        ElMessage.error('删除失败');
      }
    })
  }
  recruitmentProcess.splice(index, 1);
};

// 在特定位置添加流程步骤
const addProcessStepAt = (index: number) => {
 /*  if (recruitmentProcess.length >= 6) {
    ElMessage.warning('最多只能添加6个流程步骤');
    return;
  } */
  
  const newStep = {
    id: Date.now(),
    name: '新步骤',
    description: '新步骤',
    active: true,
    type: 'custom' // 自定义步骤类型
  };
  
  recruitmentProcess.splice(index, 0, newStep);
};

// 修改原有的添加方法，调用新方法
const addProcessStep = () => {
  addProcessStepAt(recruitmentProcess.length);
};

// 获取状态文本
const getStatusText = (status: number) => {
  const statusMap: Record<number, string> = {
    0: '未发布',
    1: '已发布',
    2: '已结束'
  };
  return statusMap[status] || '未知状态';
};

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'danger'
  };
  return typeMap[status] || 'info';
};

// 获取职位性质文本
const getJobTypeText = (type: number) => {
  const typeMap: Record<number, string> = {
    0: '全职',
    1: '兼职',
    2: '实习',
    3: '其他'
  };
  return typeMap[type] || '未知';
};

// 显示选项菜单 - 用于在指定位置添加招聘流程步骤
const showStepOptions = (index: number, event: MouseEvent) => {
  currentAddIndex.value = index;
  showOptionsMenu.value = true;
  
  // 计算菜单位置 - 获取按钮元素
  const button = event.currentTarget as HTMLElement;
  // 获取对话框元素，作为相对定位的参考
  const dialogContent = button.closest('.process-dialog-content');
  
  if (dialogContent) {
    // 获取按钮和对话框的位置信息
    const buttonRect = button.getBoundingClientRect();
    const dialogRect = dialogContent.getBoundingClientRect();
    
    // 计算相对于对话框的位置
    const top = buttonRect.bottom - dialogRect.top + 5; // 按钮下方5px
    const left = buttonRect.left - dialogRect.left;
    
    // 设置菜单位置
    menuPosition.top = `${top}px`;
    menuPosition.left = `${left}px`;
  }
  
  // 阻止事件冒泡
  event.stopPropagation();
  
};
// 修改添加选定类型的步骤方法
const addSelectedStepType = async (type: string, label: string) => {
  // 检查是否已存在相同类型的步骤，防止重复添加
   if (type === 'ai_video') {
    UpdateConfig({
      id: getConfigId.value,
      enable_open_questions: true
  }).then((res:any) => {
    if(res.code == 2000) {
      recruitmentProcess[2].visible = true;
      showOptionsMenu.value = false;
      /* initializeConfigState();  */// 添加初始化调用
    } else {
      ElMessage.error('更新配置失败');
    }
  })
  }

  // 添加综合素质考察类型的处理
  if (type === 'common_sense') {
    UpdateConfig({
      id: getConfigId.value,
      enable_single_choice: true,
      enable_multiple_choice: true,
      enable_image_choice: true,
      enable_fill_blank:true,
    }).then((res:any) => {
      if(res.code == 2000) {
        recruitmentProcess[3].visible = true;
        console.log('recruitmentProcess',recruitmentProcess);
        showOptionsMenu.value = false;
       /*  initializeConfigState();  */// 添加初始化调用
      } else {
        ElMessage.error('更新配置失败');
      }
    })
   
 
  }

  // 添加心理问题类型的处理
  if (type === 'psychological_problem') {
    UpdateConfig({
      id: getConfigId.value,
      enable_scoring_questions: true
    }).then((res:any) => {
      if(res.code == 2000) {
        recruitmentProcess[4].visible = true;
        showOptionsMenu.value = false;
      /*   initializeConfigState(); */
      } else {
        ElMessage.error('更新配置失败');
      }
    })

  }

  // 添加后渲染提问类型的处理
  if (type === 'post_render_questions') {
    showPostRenderDialog.value = true;
    showOptionsMenu.value = false;
    return;
  }

  const existingStep = recruitmentProcess.find(step => {
    if (step.type && step.type === type) {
      return true;
    }
    if (step.name === label) {
      return true;
    }
    return false;
  });
  
  if (existingStep) {
    ElMessage.warning(`"${label}"步骤已存在，不能重复添加`);
    showOptionsMenu.value = false;
    return;
  }
  
  // 添加 AI 实时对话类型的处理
  if (type === 'ai_chat') {
    showAIChatDialog.value = true;
    showOptionsMenu.value = false;
    return;
  }
  
  // 添加视频宣讲类型的处理
  if (type === 'video_presentation') {
    showVideoLectureConfig();
    showOptionsMenu.value = false;
    return;
  }
  
  // 添加资料收集类型的处理
  if (type === 'data_collection') {
    const response = await GetConfig(route.query.id);
    if (response && response.data) {
      getConfigId.value=response.data.id;
      updateFieldConfig(fieldConfig, response.data.profile_fields_config as ProfileFieldsConfig);
      showDataCollectionDialog.value = true;
      showOptionsMenu.value = false;
    }else{
      showDataCollectionDialog.value = true;
      showOptionsMenu.value = false;
    }
    return;
  }
  
  // 添加简历收集类型的处理
  if (type === 'resume_collection') {
    showResumeCollectionConfig();
    showOptionsMenu.value = false;
    return;
  }
  
  // 添加代码测试类型的处理
  if (type === 'code_test') {
    showCodeTestConfig();
    showOptionsMenu.value = false;
    return;
  }
  
  // 添加打字测试类型的处理
  if (type === 'typing_test') {
    showTypingTestDialog.value = true;
    showOptionsMenu.value = false;
    return;
  }
  
  // 添加候选人提问环节的处理
  if (type === 'candidate_questions') {
    showCandidateQuestionsDialog.value = true;
    showOptionsMenu.value = false;
    return;
  }
  
  // 创建新的招聘流程步骤，包含type字段用于重复检查
  const newStep = {
    id: Date.now(),
    name: label,
    description: label,
    active: true,
    type: type,
    visible:true
  };
  console.log('newStep',newStep);
  // 在指定位置插入新步骤
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  showOptionsMenu.value = false;
};

// 下一步
const nextStep = async () => {
  if (currentStep.value < 3) {
    // 如果从第一步进入第二步,更新已选维度到 selectedAbilities
    if (currentStep.value === 1) {
      // 校验是否选择了胜任力标签
      const selectedTags = competencyTags.value.filter(tag => tag.selected);
      if (selectedTags.length === 0) {
        ElMessage.warning('请至少选择一个胜任力考核维度');
        return; // 阻止进入下一步
      }

      try {
        // 直接使用选中的标签数据构建selectedAbilities数组
        selectedAbilities.value = selectedTags.map((tag) => ({
          label: tag.name,
          value: tag.name.toLowerCase().replace(/\s+/g, '_'),
          id: tag.id, // 使用标签原有的ID
          description: tag.description || '', // 如果没有描述则使用空字符串
          level: 'CC', // 默认等级
          expanded: false,
          isNew: true
        }));

      } catch (error) {
        console.error('处理胜任力标签失败:', error);
        ElMessage.error('处理胜任力标签失败');
        return; // 如果处理失败，不进入下一步
      }
    }
    // 如果从第二步进入第三步，分别处理AI生成和自定义选择的题目
    if (currentStep.value === 2) {
      // 校验是否选择了面试题目
      if (chatQuestions.value.length === 0) {
        ElMessage.warning('请至少添加一个面试题目');
        return; // 阻止进入下一步
      }
      
      try{
        // 分别处理AI生成的题目和自定义选择的题目
        await handleQuestionsSeparately();
      } catch (error) {
        console.error('保存题目失败:', error);
        ElMessage.error('保存题目失败');
        return; // 如果保存失败，不进入下一步
      }
    }
    // 如果从第三步完成配置，验证面试设置
    if (currentStep.value === 3) {
      const validation = validateInterviewSettings();
      if (!validation.isValid) {
        validation.messages.forEach(message => {
          ElMessage.warning(message);
        });
        return;
      }
      
      // 打印完整的配置信息
      const completeConfig = getCompleteInterviewConfig();
      console.log('完整的面试配置:', completeConfig);
    }
     currentStep.value++; 
  } else {
    finishConfig();
  }

};

// 上一步
const prevStep = () => {
  if (currentStep.value > 1) {
    currentStep.value--;
  }
};

// 完成配置
const finishConfig = async () => {
  // 验证是否选择了面试官
  if (!selectedInterviewer.value || !selectedInterviewer.value.id) {
    ElMessage.warning('请选择面试官形象');
    return; // 阻止继续执行保存操作
  }

  // 获取选中的面试官信息
  const selectedInterviewerInfo = {
    id: selectedInterviewer.value.id,
    name: selectedInterviewer.value.name,
    avatar_url: selectedInterviewer.value.avatar_url || selectedInterviewer.value.image
  };
  
  // 获取面试设置选项
  const interviewSettings = getInterviewSettings();
  
  // 获取题目设置选项
  const currentQuestionSettings = {
    enableScoreQuestions: questionSettings.enableScoreQuestions,
    enableColorBlindQuestions: questionSettings.enableColorBlindQuestions
  };

  try {
    // 更新职位状态为未发布
    await api.UpdateObj({
        id: route.query.id,
        status: 0
      });

    // 更新本地状态
    positionData.status = 0;
    positionStatus.value=false;

    if(getConfigId.value==0){
      const response = await CreateConfig({
        position_id:route.query.id,
        digital_human_id:selectedInterviewer.value.id,
      })  
      if(response.code==2000){
        ElMessage.success('配置保存成功');
        
        // 调用获取开场白和视频接口 - 顺序执行，间隔3-5秒
        try {
          const params = { config_id: response.data?.id || response.data };
          
          // 检查是否有开场白配置
          const hasOpeningSpeech = interviewSettings.beforeStartText && 
                                   interviewSettings.beforeStartText.trim() !== '';
          
          if (hasOpeningSpeech) {
            // 有开场白配置，先请求获取开场白接口
            await GetOpeningSpeech(params);
            console.log('开场白生成成功');
            showAIVideoDialog.value = false;
            currentStep.value = 1;
            // 等待3-5秒（这里设置为4秒）
            await new Promise(resolve => setTimeout(resolve, 4000));
          } else {
            console.log('无开场白配置，跳过开场白生成');
          }
          
          // 请求获取视频接口
          await GetVideo(params);
          ElMessage.success('视频开始生成');
        } catch (error) {
          console.error('获取开场白和视频失败:', error);
          ElMessage.warning('视频生成中，请稍后');
        }
      }else{
        ElMessage.error('配置保存失败');
      }
    }else{
      const response = await UpdateConfig({
        id:getConfigId.value,
        digital_human_id:selectedInterviewer.value.id,
      })
      if(response.code==2000){
        ElMessage.success('配置保存成功');
        
        // 调用获取开场白和视频接口 - 顺序执行，间隔3-5秒
        try {
          const params = { config_id: getConfigId.value };
          
          // 第一步：请求获取开场白接口
          console.log('开始生成开场白...');
          await GetOpeningSpeech(params);
          console.log('开场白生成成功');
          showAIVideoDialog.value = false;
           currentStep.value = 1;
          // 第二步：等待3-5秒（这里设置为4秒）
          console.log('等待4秒后开始生成视频...');
          await delay(4000);
          
          // 第三步：请求获取视频接口
          console.log('开始生成视频...');
          await GetVideo(params);
          console.log('视频生成请求已发送');
          ElMessage.success('视频开始生成');
        } catch (error) {
          console.error('获取开场白和视频失败:', error);
          ElMessage.warning('视频生成中，请稍后');
        }
      }else{
        ElMessage.error('配置保存失败');
      }
    }
  } catch (error) {
    console.error('更新职位状态失败:', error);
    ElMessage.error('更新职位状态失败');
    return;
  }

  console.log('保存时选中的面试官:', selectedInterviewerInfo);
  console.log('保存时的面试设置:', interviewSettings);
  console.log('保存时的题目设置:', currentQuestionSettings);
  
  // 创建新的AI考察步骤
  const newStep = {
    id: Date.now(),
    name: 'AI考察',
    description: `已选择${selectedAbilities.value.length}项能力测评`,
    active: true,
    type: 'ai_video',
    abilities: selectedAbilities.value.map(a => a.value),
    // 添加面试官信息
    interviewer: selectedInterviewerInfo,
    // 添加面试设置信息
    settings: interviewSettings
  };

  // 添加到流程中
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  
  // 关闭对话框
  showAIVideoDialog.value = false;
  
  // 重置当前步骤
  currentStep.value = 1;
  
  // 提示成功
  ElMessage.success('AI考察步骤已添加');
};

// 取消AI考察配置
const cancelAIVideoConfig = () => {
  showAIVideoDialog.value = false;
  currentStep.value = 1; // 重置步骤
};

// 跳转到指定步骤
const jumpToStep = (step: number) => {
  // 确保步骤在有效范围内
/*   if (step >= 1 && step <= 3) {
    currentStep.value = step;
  } */
};

// 显示视频宣讲配置弹窗
const showVideoLectureConfig = () => {
  showVideoLectureDialog.value = true;
};

// 取消视频宣讲配置
const cancelVideoLecture = () => {
  showVideoLectureDialog.value = false;
  // 重置表单
  Object.assign(videoLectureForm, {
    title: '',
    videoFile: null,
    description: '',
    broadcastType: 'required'
  });
};

// 确认添加视频宣讲
const confirmVideoLecture = () => {
  // 创建新的视频宣讲步骤
  const newStep = {
    id: Date.now(),
    name: videoLectureForm.title || '视频宣讲',
    description: videoLectureForm.description || '视频宣讲',
    active: true,
    type: 'video_presentation',
    config: {
      ...videoLectureForm
    }
  };
  
  // 添加到流程中
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  
  // 关闭弹窗
  showVideoLectureDialog.value = false;
  
  // 提示成功
  ElMessage.success('视频宣讲步骤已添加');
  
  // 重置表单
  cancelVideoLecture();
};

// 添加 AI 实时对话相关方法
const handleAIChatConfig = () => {
  // 这里添加确认配置的逻辑
  const newStep = {
    id: Date.now(),
    name: 'AI实时对话',
    description: 'AI实时对话',
    active: true,
    type: 'ai_chat'
  };
  
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  showAIChatDialog.value = false;
  ElMessage.success('AI实时对话步骤已添加');
};

const cancelAIChatConfig = () => {
  showAIChatDialog.value = false;
};

// 候选人提问环节相关方法 - 用于配置候选人提问环节
const confirmCandidateQuestions = () => {
  // 验证表单数据
  if (!candidateQuestionsForm.title.trim()) {
    ElMessage.warning('请输入环节名称');
    return;
  }
  
  if (candidateQuestionsForm.duration <= 0) {
    ElMessage.warning('提问时长必须大于0分钟');
    return;
  }
  
  if (candidateQuestionsForm.maxQuestions <= 0) {
    ElMessage.warning('最多提问数量必须大于0');
    return;
  }
  
  // 判断是编辑模式还是新增模式
  if (editingCandidateQuestionsIndex.value >= 0) {
    // 编辑模式：更新现有步骤
    const existingStep = recruitmentProcess[editingCandidateQuestionsIndex.value];
    existingStep.name = candidateQuestionsForm.title;
    existingStep.description = `时长${candidateQuestionsForm.duration}分钟，最多${candidateQuestionsForm.maxQuestions}个问题`;
    existingStep.config = { ...candidateQuestionsForm };
    
    ElMessage.success('候选人提问环节已更新');
  } else {
    // 新增模式：创建新的候选人提问步骤
    const newStep = {
      id: Date.now(),
      name: candidateQuestionsForm.title,
      description: `时长${candidateQuestionsForm.duration}分钟，最多${candidateQuestionsForm.maxQuestions}个问题`,
      active: true,
      type: 'candidate_questions',
      config: {
        ...candidateQuestionsForm
      }
    };
    
    // 添加到流程中
    recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
    
    ElMessage.success('候选人提问环节已添加');
  }
  
  // 关闭弹窗
  showCandidateQuestionsDialog.value = false;
  
  // 重置表单为默认值
  resetCandidateQuestionsForm();
};

const cancelCandidateQuestions = () => {
  showCandidateQuestionsDialog.value = false;
  resetCandidateQuestionsForm();
};

// 重置候选人提问表单为默认值
const resetCandidateQuestionsForm = () => {
  editingCandidateQuestionsIndex.value = -1; // 重置编辑索引
  Object.assign(candidateQuestionsForm, {
    title: '候选人提问',
    duration: 5,
    maxQuestions: 3,
    description: '候选人可以向面试官提问关于公司、职位或团队的问题',
    isRequired: true,
    allowSkip: false,
    guidelines: [
      '请提出与职位、公司文化或团队相关的问题',
      '避免询问已在职位描述中明确说明的信息',
      '可以询问职业发展机会和团队工作方式'
    ]
  });
};

// 添加问题列表数据
const chatQuestions = ref<ChatQuestion[]>([]);

// 计算面试总时长
const totalInterviewDuration = computed(() => {
  return chatQuestions.value.reduce((total, question) => {
    // 根据问题类型分配时长
    switch (question.question_form) {
      case 0: // 开放题
        return total + 60;
      case 1: // 单选题
        return total + 30;
      case 2: // 多选题
        return total + 30;
      default: // 其他类型默认30秒
        return total + 30;
    }
  }, 0);
});

// 格式化时长显示（将秒数转换为分钟和秒的格式）
const formatDuration = computed(() => {
  const seconds = totalInterviewDuration.value;
  if (seconds < 60) {
    return `${seconds}秒`;
  }
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = seconds % 60;
  return remainingSeconds > 0 ? `${minutes}分${remainingSeconds}秒` : `${minutes}分钟`;
});

// 添加问题处理方法
const handleAddQuestion = () => {
  showQuestionDialog.value = true;
};

/* // 取消添加问题
const cancelAddQuestion = () => {
  showQuestionDialog.value = false;
  // 重置表单
  Object.assign(questionForm, {
    title: '',
    ability: '',
    content: '',
    target: '',
    weight: 100,
    maxAnswers: 1
  });
}; */

/* // 确认添加问题
const confirmAddQuestion = () => {
  if (!questionForm.title || !questionForm.content) {
    ElMessage.warning('请填写必填项');
    return;
  }

  // 创建新问题对象
  const newQuestion = {
    id: Date.now(), // 添加唯一ID
    title: questionForm.title,
    ability: questionForm.ability,
    content: questionForm.content,
    target: questionForm.target,
    weight: questionForm.weight,
    maxAnswers: questionForm.maxAnswers,
    source: 'custom_selected' as const // 标识为自定义题目
  };

  // 添加到问题列表
  chatQuestions.value.push(newQuestion);
  
  // 关闭弹框
  showQuestionDialog.value = false;
  
  // 重置表单
  cancelAddQuestion();
  
  // 提示成功
  ElMessage.success('问题添加成功');
}; */

// 导入问题处理方法 - 修改为打开QuestionBankForm
const handleImportQuestion = () => {
  // 重置表单数据
  questionBankFormData.value = {
    question: '',
    question_form: null,
    competency_tags: [],
    position_types: [],
    category_id: null,
    tags: [],
    recommended_duration: 60,
    status: 1,
    is_required_correct: false,
    is_system: false,
    sort: 1,
    options: [],
    scoring_reference: '',
    blank_answer_template: []
  };
  isEditingQuestion.value = false;
  showQuestionBankFormDialog.value = true;
};

// QuestionBankForm 提交处理
const handleQuestionBankFormSubmit = async (formData: any) => {
  try {
    // 调用题库API创建题目
    const response = await questionBankApi.AddObj({
      ...formData,
      tenant_id: Session.get('tenant_id')
    });
    
    if (response && response.code === 2000) {
      ElMessage.success('题目创建成功');
      console.log(response);
      // 将创建的题目添加到当前职位的题目列表中
      if (response.data) {
        const newQuestion = {
          id: response.data.id || response.data,
          title: formData.question,
          question_form: formData.question_form,
          question_form_name: getQuestionFormName(formData.question_form),
          scoring_reference: formData.scoring_reference || '',
          competency_tags: formData.competency_tags || [],
          options: formData.options || [],
          enable_follow_up: false,
          maxAnswers: 1,
          weight: 100,
          source: 'custom_selected' as const
        };
        
        // 添加到题目列表
        chatQuestions.value.push(newQuestion);
        
      }
      
      // 关闭对话框
      showQuestionBankFormDialog.value = false;
    } else {
      ElMessage.error('题目创建失败，请重试');
    }
  } catch (error) {
    console.error('创建题目失败:', error);
    ElMessage.error('题目创建失败，请重试');
  }
};

// QuestionBankForm 取消处理
const handleQuestionBankFormCancel = () => {
  showQuestionBankFormDialog.value = false;
  questionBankFormData.value = {};
};

// 获取题目形式名称的辅助函数
const getQuestionFormName = (questionForm: number) => {
  const formMap: { [key: number]: string } = {
    0: '开放问题',
    1: '单选题', 
    2: '多选题',
    3: '色盲题',
    4: '得分题',
    5: '判断题',
    6: '填空题'
  };
  return formMap[questionForm] || '未知类型';
};

// 在 script setup 中添加
const editQuestion = (index: number) => {
  // 编辑问题的逻辑
  const question = chatQuestions.value[index];
  console.log(question);
  Object.assign(questionForm, question);
  showQuestionDialog.value = true;
  distributeWeightsEvenly()
};

const deleteQuestion = (index: number) => {
  ElMessageBox.confirm('确认删除该问题？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    chatQuestions.value.splice(index, 1);
    ElMessage.success('删除成功');
  });
};

// 取消资料收集配置
const cancelDataCollection = () => {
  showDataCollectionDialog.value = false;
  // 重置表单
  Object.assign(dataCollectionForm, {
    isRequired: false,
    questions: []
  });
};

// 确认添加资料收集
const confirmDataCollection = () => {
  /* if (dataCollectionForm.questions.length === 0) {
    ElMessage.warning('请至少选择一个问题');
    return;
  } */

  // 创建新的资料收集步骤
  const newStep = {
    id: Date.now(),
    name: '资料收集',
    description: `已选择${dataCollectionForm.questions.length}个问题`,
    active: true,
    type: 'data_collection',
    config: {
      ...dataCollectionForm,
      questions: dataCollectionForm.questions.map(q => {
        // 修复 find 方法的使用
        const question = questionTypes.value.find(type => type.value === q);
        return {
          type: q,
          title: question?.label || '',
          required: dataCollectionForm.isRequired
        };
      })
    }
  };

  // 添加到流程中
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);

  // 关闭弹窗
  showDataCollectionDialog.value = false;

  // 提示成功
  ElMessage.success('资料收集步骤已添加');

  // 重置表单
  cancelDataCollection();
};

// 使用 onMounted 和 onUnmounted 钩子
onMounted(() => {
  getPositionDetail();
  getCompetencyList();
  getDigitalList();
  // 初始化配置状态
  initializeConfigState();
});

// 组件销毁时清理轮询
onUnmounted(() => {
  // 取消正在进行的轮询
  cancelPolling();
});

// 初始化配置状态
const initializeConfigState = async () => {
  try {
    const id = route.query.id;
    if (id) {
      const config = await GetConfig(id);
      if (config && config.data) {
        // 同步得分题开关状态
        if (config.data.enable_psychological_test !== undefined) {
          questionSettings.enableScoreQuestions = config.data.enable_psychological_test;
        }
        // 同步色盲题开关状态
        if (config.data.enable_color_blind_test !== undefined) {
          questionSettings.enableColorBlindQuestions = config.data.enable_color_blind_test;
        }
        // 同步AI考察（开放问题）开关状态
          recruitmentProcess[2].visible = config.data.question_form_switches.enable_open_questions;
          recruitmentProcess[3].visible = config.data.question_form_switches.enable_single_choice ||
          config.data.question_form_switches.enable_multiple_choice ||
          config.data.question_form_switches.enable_image_choice ||
          config.data.question_form_switches.enable_fill_blank;
          recruitmentProcess[4].visible = config.data.question_form_switches.enable_scoring_questions;
        
        
        // 可以在这里添加其他配置状态的同步
      }
    }
  } catch (error) {
    console.error('初始化配置状态失败:', error);
  }
};

// 添加代码测试相关的状态和方法
const showCodeTestDialog = ref(false);
const codeTestForm = reactive({
  title: '代码笔试',
  autoJudge: true,
  selectedPaper: null as Paper | null,
});

// 显示代码测试弹窗
const showCodeTestConfig = () => {
  showCodeTestDialog.value = true;
};

// 取消代码测试配置
const cancelCodeTest = () => {
  showCodeTestDialog.value = false;
  // 重置表单
  Object.assign(codeTestForm, {
    title: '代码笔试',
    autoJudge: true,
    selectedPaper: null
  });
};

// 确认添加代码测试
const confirmCodeTest = () => {
  if (!codeTestForm.selectedPaper) {
    ElMessage.warning('请添加考试试卷');
    return;
  }
  
  // 创建新的代码测试步骤
  const newStep = {
    id: Date.now(),
    name: codeTestForm.title,
    description: `${codeTestForm.selectedPaper.title}`,
    active: true,
    type: 'code_test',
    config: {
      ...codeTestForm
    }
  };
  
  // 添加到流程中
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  
  // 关闭弹窗
  showCodeTestDialog.value = false;
  
  // 提示成功
  ElMessage.success('代码笔试步骤已添加');
  
  // 重置表单
  cancelCodeTest();
};

// 选择试卷
const handleSelectPaper = () => {
  // 模拟选择试卷
  codeTestForm.selectedPaper = {
    id: 1,
    title: '前端开发工程师笔试',
    questionCount: 4,
    duration: 60,
    difficulty: '中等难度'
  } as Paper;
};

// 查看试卷
const handleViewPaper = () => {
  ElMessage.info('查看试卷功能开发中');
};

// 更换试卷
const handleChangePaper = () => {
  ElMessage.info('更换试卷功能开发中');
};

// 删除试卷
const handleRemovePaper = () => {
  codeTestForm.selectedPaper = null;
};

// 添加打字测试对话框
const showTypingTestDialog = ref(false);
const typingTestForm = reactive({
  title: '', // 步骤名称
  duration: 5, // 测试时间，默认5分钟
  content: '', // 测试页面标题
  notes: '', // 注意事项内容
  videoMonitoring: false, // 是否启用视频监控
  passCriteria: {
    speed: false, // 是否通过速度标准
    accuracy: true, // 是否通过正确率标准，默认选中
  },
  selectionMode: 'random', // 文章选择方式：random-随机抽取，self-候选人自主选择
  pageTitle: '', // 测试页面标题
  previewImage: null, // 登录界面预览图
  articles: [] // 文章列表
});

// 取消打字测试配置
const cancelTypingTest = () => {
  showTypingTestDialog.value = false;
  // 重置表单
  Object.assign(typingTestForm, {
    title: '',
    duration: 5,
    content: '',
    notes: '',
    videoMonitoring: false,
    passCriteria: {
      speed: false,
      accuracy: true,
    },
    selectionMode: 'random',
    pageTitle: '',
    previewImage: null,
    articles: []
  });
};

// 确认添加打字测试
const confirmTypingTest = () => {
  // 创建新的打字测试步骤
  const newStep = {
    id: Date.now(),
    name: typingTestForm.title,
    description: `打字测试 ${typingTestForm.duration}分钟`,
    active: true,
    type: 'typing_test',
    config: {
      ...typingTestForm
    }
  };
  
  // 添加到流程中
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  
  // 关闭弹窗
  showTypingTestDialog.value = false;
  
  // 提示成功
  ElMessage.success('打字测试步骤已添加');
  
  // 重置表单
  cancelTypingTest();
};

// 添加职位名称编辑功能
const isEditingTitle = ref(false);
const editingTitle = ref('');

// 开始编辑职位名称
const startEditTitle = () => {
  editingTitle.value = positionData.title;
  isEditingTitle.value = true;
};

// 取消编辑职位名称
const cancelEditTitle = () => {
  isEditingTitle.value = false;
};

// 保存编辑后的职位名称
const saveTitle = async () => {
  if (!editingTitle.value.trim()) {
    ElMessage.warning('职位名称不能为空');
    return;
  }
  
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      title: editingTitle.value.trim()
    });
    
    // 更新本地数据
    positionData.title = editingTitle.value.trim();
    isEditingTitle.value = false;
    ElMessage.success('职位名称已更新');
  } catch (error) {
    console.error('更新职位名称失败:', error);
    ElMessage.error('更新职位名称失败');
  }
};

// 工作地点编辑
const isEditingLocation = ref(false);
const editingLocation = ref('');

// 开始编辑工作地点
const startEditLocation = () => {
  if (!positionData.location) {
    editingLocation.value = '';
  } else if (Array.isArray(positionData.location)) {
    editingLocation.value = positionData.location;
  } else if (typeof positionData.location === 'string') {
    try {
      // 移除方括号和单引号，并分割成数组
      const cleanStr = positionData.location.replace(/[\[\]']/g, '');
      const locationArray = cleanStr.split(',').map(item => item.trim());
      // 根据地址数据查找对应的code
      const province = locationOptions.find(p => p.name === locationArray[0]);
      let city, district;
      
      if (province && province.children) {
        city = province.children.find(c => c.name === locationArray[1]);
        if (city && city.children) {
          district = city.children.find(d => d.name === locationArray[2]);
        }
      }

      editingLocation.value = [
        province?.code,
        city?.code,
        district?.code
      ].filter(Boolean);
    } catch (e) {
      console.error('解析地址失败:', e);
      editingLocation.value = '';
    }
  }
  isEditingLocation.value = true;
};

// 取消编辑工作地点
const cancelEditLocation = () => {
  isEditingLocation.value = false;
};

// 保存工作地点
const saveLocation = async () => {
  try {
    const id = route.query.id;
    // 获取选中地址的名称
    const locationNames = [];
    if (editingLocation.value && Array.isArray(editingLocation.value)) {
      const [provinceCode, cityCode, districtCode] = editingLocation.value;
      const province = locationOptions.find(p => p.code === provinceCode);
      let city, district;

      if (province) {
        locationNames.push(province.name);
        if (province.children) {
          city = province.children.find(c => c.code === cityCode);
          if (city) {
            locationNames.push(city.name);
            if (city.children) {
              district = city.children.find(d => d.code === districtCode);
              if (district) {
                locationNames.push(district.name);
              }
            }
          }
        }
      }
    }

    await api.UpdateObj({
      id: id,
      location: locationNames
    });
    
    // 更新本地数据
    positionData.location = locationNames;
    isEditingLocation.value = false;
    ElMessage.success('工作地点已更新');
  } catch (error) {
    console.error('更新工作地点失败:', error);
    ElMessage.error('更新工作地点失败');
  }
};

// 职位薪资编辑
const isEditingSalary = ref(false);
const editingSalary = ref('');

// 开始编辑职位薪资
const startEditSalary = () => {
  editingSalary.value = positionData.salary_range || '';
  isEditingSalary.value = true;
};

// 取消编辑职位薪资
const cancelEditSalary = () => {
  isEditingSalary.value = false;
};

// 保存职位薪资
const saveSalary = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      salary_range: editingSalary.value.trim()
    });
    
    // 更新本地数据
    positionData.salary_range = editingSalary.value.trim();
    isEditingSalary.value = false;
    ElMessage.success('职位薪资已更新');
  } catch (error) {
    console.error('更新职位薪资失败:', error);
    ElMessage.error('更新职位薪资失败');
  }
};

// 工作经验编辑
const isEditingExperience = ref(false);
const editingExperience = ref('');

// 开始编辑工作经验
const startEditExperience = () => {
  editingExperience.value = positionData.work_experience_required || '';
  isEditingExperience.value = true;
};

// 取消编辑工作经验
const cancelEditExperience = () => {
  isEditingExperience.value = false;
};

// 保存工作经验
const saveExperience = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      work_experience_required: editingExperience.value
    });
    
    // 更新本地数据
    positionData.work_experience_required = editingExperience.value;
    isEditingExperience.value = false;
    ElMessage.success('工作经验已更新');
  } catch (error) {
    console.error('更新工作经验失败:', error);
    ElMessage.error('更新工作经验失败');
  }
};

// 学历要求编辑
const isEditingEducation = ref(false);
const editingEducation = ref('');

// 开始编辑学历要求
const startEditEducation = () => {
  editingEducation.value = positionData.education_required || '';
  isEditingEducation.value = true;
};

// 取消编辑学历要求
const cancelEditEducation = () => {
  isEditingEducation.value = false;
};

// 保存学历要求
const saveEducation = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      education_required: editingEducation.value
    });
    
    // 更新本地数据
    positionData.education_required = editingEducation.value;
    isEditingEducation.value = false;
    ElMessage.success('学历要求已更新');
  } catch (error) {
    console.error('更新学历要求失败:', error);
    ElMessage.error('更新学历要求失败');
  }
};

// 所属部门编辑
const isEditingDepartment = ref(false);
const editingDepartment = ref('');

// 开始编辑所属部门
const startEditDepartment = () => {
  editingDepartment.value = positionData.department || '';
  isEditingDepartment.value = true;
};

// 取消编辑所属部门
const cancelEditDepartment = () => {
  isEditingDepartment.value = false;
};

// 保存所属部门
const saveDepartment = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      department: editingDepartment.value.trim()
    });
    
    // 更新本地数据
    positionData.department = editingDepartment.value.trim();
    isEditingDepartment.value = false;
    ElMessage.success('所属部门已更新');
  } catch (error) {
    console.error('更新所属部门失败:', error);
    ElMessage.error('更新所属部门失败');
  }
};

// 截止日期编辑
const isEditingEndDate = ref(false);
const editingEndDate = ref('');

// 开始编辑截止日期
const startEditEndDate = () => {
  editingEndDate.value = positionData.end_date || '';
  isEditingEndDate.value = true;
};

// 取消编辑截止日期
const cancelEditEndDate = () => {
  isEditingEndDate.value = false;
};

// 保存截止日期
const saveEndDate = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      end_date: editingEndDate.value
    });
    
    // 更新本地数据
    positionData.end_date = editingEndDate.value;
    isEditingEndDate.value = false;
    ElMessage.success('截止日期已更新');
  } catch (error) {
    console.error('更新截止日期失败:', error);
    ElMessage.error('更新截止日期失败');
  }
};

// 职位要求编辑
const isEditingRequirements = ref(false);
const editingRequirements = ref('');

// 开始编辑职位要求
const startEditRequirements = () => {
  editingRequirements.value = positionData.requirements || '';
  isEditingRequirements.value = true;
};

// 取消编辑职位要求
const cancelEditRequirements = () => {
  isEditingRequirements.value = false;
};

// 保存职位要求
const saveRequirements = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      requirements: editingRequirements.value
    });
    
    // 更新本地数据
    positionData.requirements = editingRequirements.value;
    isEditingRequirements.value = false;
    ElMessage.success('职位要求已更新');
  } catch (error) {
    console.error('更新职位要求失败:', error);
    ElMessage.error('更新职位要求失败');
  }
};

// 职位描述编辑
const isEditingDescription = ref(false);
const editingDescription = ref('');

// 开始编辑职位描述
const startEditDescription = () => {
  editingDescription.value = positionData.description || '';
  isEditingDescription.value = true;
};

// 取消编辑职位描述
const cancelEditDescription = () => {
  isEditingDescription.value = false;
};

// 保存职位描述
const saveDescription = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      description: editingDescription.value
    });
    
    // 更新本地数据
    positionData.description = editingDescription.value;
    isEditingDescription.value = false;
    ElMessage.success('职位描述已更新');
  } catch (error) {
    console.error('更新职位描述失败:', error);
    ElMessage.error('更新职位描述失败');
  }
};

// 职位性质编辑
const isEditingJobType = ref(false);
const editingJobType = ref(0);

// 开始编辑职位性质
const startEditJobType = () => {
  editingJobType.value = positionData.job_type || 0;
  isEditingJobType.value = true;
};

// 取消编辑职位性质
const cancelEditJobType = () => {
  isEditingJobType.value = false;
};

// 保存职位性质
const saveEditJobType = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      job_type: editingJobType.value
    });
    
    // 更新本地数据
    positionData.job_type = editingJobType.value;
    isEditingJobType.value = false;
    ElMessage.success('职位性质已更新');
  } catch (error) {
    console.error('更新职位性质失败:', error);
    ElMessage.error('更新职位性质失败');
  }
};

// 添加能力标签相关的响应式变量
const competencyTags = ref<CompetencyTag[]>([]);
const isEditingCompetency = ref(false);
const selectedCompetencies = ref([]);

// 获取能力标签列表
const getCompetencyList = async () => {
  try {
    const response = await GetCompetencyList({page:1,pageSize:1000});
    if (response && response.data) {
    /*   competencyTagOptions.value = response.data.items.map((item: any) => ({
        id: item.id,
        name: item.name,
        selected: false
      })); */
    }
  } catch (error) {
    console.error('获取能力标签列表失败:', error);
    ElMessage.error('获取能力标签列表失败');
  }
};

// 开始编辑能力标签
const startEditCompetency = async () => {
  // 先获取所有可用的胜任力标签
  await getCompetencyList();
  
  // 设置已选中的标签
  selectedCompetencies.value = positionData.competency_tags?.map((tag: any) => tag.id) || [];
  
  // 标记已选中的标签
  competencyTagOptions.value.forEach(tag => {
    tag.selected = selectedCompetencies.value.includes(tag.id);
  });
  
  isEditingCompetency.value = true;
};

// 取消编辑能力标签
const cancelEditCompetency = () => {
  isEditingCompetency.value = false;
};

// 保存能力标签
const saveCompetency = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      competency_tags: selectedCompetencies.value
    });
    
    // 更新本地数据
    positionData.competency_tags = competencyTagOptions.value
      .filter(tag => selectedCompetencies.value.includes(tag.id))
      .map(tag => ({
        id: tag.id,
        name: tag.name
      }));
      
    isEditingCompetency.value = false;
    ElMessage.success('能力标签已更新');
  } catch (error) {
    console.error('更新能力标签失败:', error);
    ElMessage.error('更新能力标签失败');
  }
};

// 在setup中添加
const currentEditingStep = ref<AIVideoStep | null>(null);
/* 获取已配置ID */
const getConfigId =ref(0)
// 编辑AI考察
const editAIVideo = async (step: AIVideoStep) => {
   // 添加资料收集类型的处理
   if (step.name === '资料收集') {
    const response = await GetConfig(route.query.id);
    if (response && response.data) {
      getConfigId.value=response.data.id;
      updateFieldConfig(fieldConfig, response.data.profile_fields_config as ProfileFieldsConfig);
      showDataCollectionDialog.value = true;
      showOptionsMenu.value = false;
    }else{
      showDataCollectionDialog.value = true;
      showOptionsMenu.value = false;
    }
    return;
  }

  if (step.name === 'AI考察') {
    // 如果是删除操作，先删除相关的AI考察问题
    if (step.action === 'delete') {
      await handleDeleteAIQuestions();
      return;
    }

    const response = await GetConfig(route.query.id);
    competencyLoading.value = true;
    currentEditingStep.value = step;
    showAIVideoDialog.value = true;
    currentStep.value = 1;
    
    try {
      // 获取当前职位下已生成的问题
      const questionResponse = await GetDraftList({
        position_id: route.query.id,
        page: 1,
        limit: 20
      });
      
      if (questionResponse && questionResponse.data && questionResponse.data.dataList) {
        chatQuestions.value = questionResponse.data.dataList.map((item:any)=>{
          item.content=item.question;
          item.title=item.question;
          item.competency_tags=item.competency_tag_info
          item.source='ai_generated';
          return item;
        });
      }

      // 首先尝试获取已有的职位标签
      const existingTags = await GetPositionTags({position_id:route.query.id,page:1,limit:50});
      console.log('existingTags', existingTags);
      if (existingTags && existingTags.data && existingTags.data.items.length > 0) {
        // 如果存在已有标签，直接使用
        existingTags.data.items.forEach((item: any) => {
          // 设置默认值
          item.importance = 1;
          item.selected = false;

          // 如果存在competency快照数据，则更新选中状态
          if (positionData.latest_competency_snapshot && Array.isArray(positionData.latest_competency_snapshot)) {
            // 使用some方法替代内部循环，提高代码可读性
            item.selected = positionData.latest_competency_snapshot.some(
              (snapshot: any) => snapshot.id === item.id
            );
          }
        });
        competencyTags.value = existingTags.data.items;
      } else {
        // 如果没有已有标签，则生成新的标签
        const response2 = await GenerateCompetency({position_id: route.query.id});
        if (response2 && response2.data) {
          response2.data.forEach((item: any) => {
            item.selected = false;
          });
          competencyTags.value = response2.data;
          
          // 保存生成的胜任力标签
          try {
            await SaveCompetency({
              position_id: route.query.id,
              tags: competencyTags.value
            });
            ElMessage.success('胜任力标签保存成功');
          } catch (error) {
            console.error('保存胜任力标签失败:', error);
            ElMessage.error('胜任力标签保存失败');
          }
        }
      }

      if (response && response.data) {
        getConfigId.value = response.data.id;
      }
    } catch (error) {
      console.error('获取或生成能力标签失败:', error);
      ElMessage.error('获取或生成能力标签失败');
    } finally {
      competencyLoading.value = false;
    }
    
    // 重置选项
    (Object.keys(aiVideoOptions) as Array<keyof typeof aiVideoOptions>).forEach(key => {
      aiVideoOptions[key] = false;
    });
  }
  if(step.name === '综合素质考察'){
    GetQuestionList({page:1,limit:20}).then((res:any)=>{
      if(res.data){
        questionList.value = res.data.items;
        questionListpage.page=res.data.page;
        questionListpage.pageSize=res.data.limit;
        totalQuestions2.value=res.data.total;
        getTreeData();
        QuestionSelectDialog.value = true;
        
      }
    })
    
  }
  if(step.name === '心理问题'){
    GetQuestionList({page:1,limit:30,question_form:4}).then((res:any)=>{
      if(res.data){
        questionListQuery.question_form=4
        questionList.value = res.data.items;
        questionListpage.page=res.data.page;
        questionListpage.pageSize=res.data.limit;
        totalQuestions2.value=res.data.total;
        getDFTreeData();
        showQuestionSelectDialog.value = true;
      }
    })
    
  }
};

// 保存AI考察配置
const saveAIVideoConfig = async () => {
  try {
    // 获取选中的能力标签
    const selectedAbilities = Object.entries(aiVideoOptions)
      .filter(([_, value]) => value)
      .map(([key]) => key);

    // 更新当前编辑的步骤
    if (currentEditingStep.value) {
      currentEditingStep.value.aiConfig = {
        abilities: selectedAbilities,
        // 可以根据需要添加其他配置
      };
    }

    // 关闭对话框
    showAIVideoDialog.value = false;
    ElMessage.success('AI考察配置已保存');
  } catch (error) {
    console.error('保存AI考察配置失败:', error);
    ElMessage.error('保存失败，请重试');
  }
};

// 在 script setup 部分添加以下响应式变量
const customDimension = ref('');
const customDescription = ref('');
const continueAdd = ref(false);

// 添加新的维度
const addDimension = async () => {
  // 验证输入
  if (!customDimension.value.trim()) {
    ElMessage.warning('请输入维度名称');
    return;
  }
  
  // 检查维度名称是否已存在
  const existingDimension = competencyTags.value.find(tag => tag.name === customDimension.value.trim());
  if (existingDimension) {
    ElMessage.warning('该维度名称已存在，请重新输入');
    return;
  }
  
  try {
    // 1. 首先调用创建标签接口
    const createResponse = await CreateCompetency({
      name: customDimension.value.trim(),
      description: customDescription.value.trim(),
      importance: 1,
      weight: 0
    });

    if (!createResponse.data) {
      throw new Error('创建标签失败');
    }

    const newTagId = createResponse.data.id;

    // 2. 调用绑定接口，将新创建的标签绑定到当前职位
    await BatchUpdateTags({
      tag_ids: [newTagId],
      position_ids: [positionId.value]
    });

    // 创建新的维度对象
    const newDimension = {
      id: newTagId, // 使用API返回的真实ID
      name: customDimension.value.trim(),
      description: customDescription.value.trim(),
      selected: false,
      importance: 1,
      weight: 0,
      isCustom: true // 标记为自定义维度
    };
    
    // 将新维度添加到competencyTags数组中（添加到备选维度区域）
    competencyTags.value.push(newDimension);
    
   /*  ElMessage.success(`自定义维度"${newDimension.name}"已添加并绑定到当前职位`); */
    
    // 如果不是继续新增，则重置表单
    if (!continueAdd.value) {
      customDimension.value = '';
      customDescription.value = '';
    } else {
      // 继续新增时只清空输入框，保持焦点便于继续输入
      customDimension.value = '';
      customDescription.value = '';
    }
    
    console.log('添加新维度成功:', newDimension);
    console.log('当前备选维度列表:', competencyTags.value);
    
  } catch (error) {
    console.error('添加自定义维度失败:', error);
    ElMessage.error('添加自定义维度失败，请重试');
  }
}

// 删除自定义维度
const deleteCustomDimension = (dimension: any) => {
  ElMessageBox.confirm(
    `确认删除自定义维度"${dimension.name}"吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 从competencyTags数组中移除
    const index = competencyTags.value.findIndex(tag => tag.id === dimension.id && tag.isCustom);
    if (index > -1) {
      competencyTags.value.splice(index, 1);
      
      // 如果该维度已被选中，也要从已选维度列表中移除
      const selectedIndex = selectedDimensions.value.findIndex(item => item.name === dimension.name);
      if (selectedIndex > -1) {
        selectedDimensions.value.splice(selectedIndex, 1);
      }
      
      ElMessage.success(`自定义维度"${dimension.name}"已删除`);
      console.log('删除自定义维度成功:', dimension);
    } else {
      ElMessage.error('删除失败，未找到该维度');
    }
  }).catch(() => {
    // 用户取消删除
    console.log('用户取消删除自定义维度');
  });
};

const settings = reactive({
  
  keepVideo: false,
  interruptionMode: '',
  smartFollowUp: false,
  followUpStyle: ''
});

interface InterviewerAvatar {
  id: number;
  name: string;
  image: string;
}

const interviewerAvatars = ref<InterviewerAvatar[]>([
  {
    id: 1,
    name: 'Jessica',
    image: '/avatars/jessica.png'
  },
  {
    id: 2,
    name: 'Mike',
    image: '/avatars/mike.png'
  },
  {
    id: 3,
    name: 'Sarah',
    image: '/avatars/sarah.png'
  }
]);

const selectedInterviewer = ref(interviewerAvatars.value[0]);
const interviewerAvatar = ref('');
// 添加面试官选择处理函数
const handleInterviewerSelect = (avatar: any) => {
  // 更新选中的面试官
  selectedInterviewer.value = avatar;
  
  // 打印选中的面试官信息（调试用）
  console.log('选中的面试官信息:', {
    id: avatar.id,
    name: avatar.name,
    avatar_url: avatar.avatar_url || avatar.image
  });
  interviewerAvatar.value = avatar.avatar_url;
  // 可以在这里添加其他处理逻辑
  // 比如：保存到后端、触发其他事件等
  
  // 提示用户
  ElMessage.success(`已选择面试官：${avatar.name}`);
};

// 分别处理AI生成的题目和自定义选择的题目
const handleQuestionsSeparately = async () => {
  // 分离AI生成的题目和自定义选择的题目
  const aiGeneratedQuestions = chatQuestions.value.filter(q => q.source === 'ai_generated');
  const customSelectedQuestions = chatQuestions.value.filter(q => q.source === 'custom_selected');
  
  console.log('AI生成的题目:', aiGeneratedQuestions);
  console.log('自定义选择的题目:', customSelectedQuestions);
  
  // 处理AI生成的题目 - 调用SaveDraft接口
  if (aiGeneratedQuestions.length > 0) {
    await SaveDraft({
      draft_ids: aiGeneratedQuestions.map((draft: any) => draft.id)
    });
    console.log('AI生成的题目已保存到草稿');
  }
  
  // 处理自定义选择的题目 - 调用其他接口（这里需要根据实际需求调整）
  if (customSelectedQuestions.length > 0) {
    // 构建API请求数据 - 修改为符合API期望的格式
    const requestData = {
      position_id: route.query.id,
      question_id: { 
        question_id: customSelectedQuestions
      },
      duration:60,
      tenant_id:Session.get('tenant_id')
    };
    // 这里可以调用专门处理自定义题目的接口
    // 例如：await SaveCustomQuestions({ question_ids: customSelectedQuestions.map(q => q.id) });
    console.log('自定义选择的题目需要调用专门的接口处理');
    
    // 临时处理：也使用SaveDraft接口，但可以在后端根据source字段区分处理
    const response = await AddDocument(requestData);
    if (response && response.code === 2000) {
      ElMessage.success('自定义选择的题目已保存');
    }else{
      ElMessage.error('自定义选择的题目保存失败');
    }
  }
};

// 获取面试设置选项的函数
const getInterviewSettings = () => {
  const interviewSettings = {
    // 回答视频保留设置
    keepVideo: settings.keepVideo,
    // 中断后作答限制模式
    interruptionMode: settings.interruptionMode,
    // 追问风格设置
    followUpStyle: settings.followUpStyle,
    // 智慧追问设置
    smartFollowUp: settings.smartFollowUp
  };
  
  console.log('当前面试设置:', interviewSettings);
  return interviewSettings;
};

// 处理面试设置变化的函数
const handleSettingChange = (settingType: string, value: any) => {
  console.log(`面试设置 ${settingType} 已更改为:`, value);
  
  // 根据不同的设置类型进行处理
  switch (settingType) {
    case 'keepVideo':
      console.log('回答视频保留设置:', value ? '开启' : '关闭');
      break;
    case 'interruptionMode':
      console.log('中断后作答限制模式:', value === 'previous' ? '从上一问重新作答' : '从当前问题作答');
      break;
    case 'followUpStyle':
      console.log('追问风格:', value);
      break;
    case 'smartFollowUp':
      console.log('智慧追问设置:', value ? '开启' : '关闭');
      break;
  }
  
  // 可以在这里添加其他处理逻辑
  // 比如：实时保存到后端、触发相关事件等
};

// 验证面试设置配置完整性
const validateInterviewSettings = () => {
  const currentSettings = getInterviewSettings();
  
  // 检查必要设置是否已配置
  const validation = {
    isValid: true,
    messages: [] as string[]
  };
  
  // 这里可以添加具体的验证逻辑
  if (currentSettings.interruptionMode === '') {
    validation.isValid = false;
    validation.messages.push('请选择中断后作答限制模式');
  }
  
  return validation;
};

// 拖拽开始处理
const handleDragStart = (evt: any) => {
  drag.value = true;
  console.log('开始拖拽题目:', evt);
};

// 拖拽结束处理
const handleDragEnd = (evt: any) => {
  drag.value = false;
  console.log('拖拽结束:', evt);
  console.log('当前题目顺序:', chatQuestions.value);
  
  // 这里可以调用API保存新的题目顺序
  // await saveQuestionOrder(chatQuestions.value);
  
  ElMessage.success('题目顺序已更新');
};

// 获取完整的面试配置信息
const getCompleteInterviewConfig = () => {
  return {
    // 面试官信息
    interviewer: {
      id: selectedInterviewer.value.id,
      name: selectedInterviewer.value.name,
      avatar_url: selectedInterviewer.value.avatar_url || selectedInterviewer.value.image
    },
    // 面试设置
    settings: getInterviewSettings(),
    // 题目设置
    questionSettings: {
      enableScoreQuestions: questionSettings.enableScoreQuestions,
      enableColorBlindQuestions: questionSettings.enableColorBlindQuestions
    },
    // 选中的能力标签
    abilities: selectedAbilities.value,
    // 题目列表
    questions: chatQuestions.value,
    // 当前步骤
    currentStep: currentStep.value
  };
};

/* 获取数字人列表 */
const getDigitalList = async () => {
  const response = await GetDigitalList({page:1,pageSize:1000});
  if (response && response.data) {
    interviewerAvatars.value = response.data;
  }
};

const handleCompetencyChange = (item: any, val: boolean) => {
  if (val) {
    // 当选中时,添加到已选维度列表
    selectedDimensions.value.push({
      name: item.name,
      description: item.description || '暂无描述' // 如果没有描述则显示默认值
    });
  } else {
    // 当取消选中时,从已选维度列表中移除
    selectedDimensions.value = selectedDimensions.value.filter(
      dimension => dimension.name !== item.name
    );
  }
};

// 删除选中的胜任力标签
const removeSelectedAbility = (index: number) => {
  ElMessageBox.confirm('确认删除这个胜任力标签吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 获取被删除的能力标签
    const removedAbility = selectedAbilities.value[index];
    
    // 从 selectedAbilities 数组中移除
    selectedAbilities.value.splice(index, 1);
    
    // 同时从 selectedDimensions 数组中移除对应项
    selectedDimensions.value = selectedDimensions.value.filter(
      dimension => dimension.name !== removedAbility.label
    );
    
    // 更新对应的checkbox状态 - 将对应的competencyTags项的selected设为false
    const competencyTag = competencyTags.value.find((tag: any) => tag.name === removedAbility.label);
    if (competencyTag) {
      competencyTag.selected = false;
    }
    
    ElMessage.success('胜任力标签已删除');
  }).catch(() => {
    // 用户取消删除
  });
};

// 在 script setup 部分添加以下代码
const selectedDimensions = ref<Array<{name: string, description: string}>>([]);

// 创建延迟函数
const delay = (ms: number): Promise<void> => {
  return new Promise(resolve => setTimeout(resolve, ms));
};

// 轮询控制器，用于取消轮询
let pollingController: { cancelled: boolean } | null = null;

// 轮询获取草稿列表的函数
const pollForDraftList = async (params: { tenant_id: number; page: number; limit: number; position_id: string }, maxAttempts: number = 300, interval: number = 2000): Promise<any> => {
  let attempts = 0;
  
  // 创建轮询控制器
  pollingController = { cancelled: false };
  const currentController = pollingController;
  
  return new Promise((resolve, reject) => {
    const poll = async () => {
      try {
        // 检查是否已取消轮询
        if (currentController.cancelled) {
          console.log('轮询已被取消');
          resolve(null);
          return;
        }
        
        attempts++;
        console.log(`第${attempts}次轮询获取草稿列表...`);
        
        const response = await GetDraftList(params);
        
        // 再次检查是否已取消轮询（防止在异步请求期间被取消）
        if (currentController.cancelled) {
          console.log('轮询已被取消');
          resolve(null);
          return;
        }
        
        // 检查是否有数据
        if (response && response.data && response.data.dataList && response.data.dataList.length > 0) {
          console.log('轮询成功，获取到草稿列表数据');
          pollingController = null; // 清理控制器
          resolve(response);
          return;
        }
        
        // 如果超过最大尝试次数，停止轮询
        if (attempts >= maxAttempts) {
          console.log('轮询达到最大次数，停止轮询');
          pollingController = null; // 清理控制器
          resolve(response); // 返回最后一次的响应，即使没有数据
          return;
        }
        
        // 继续轮询
        setTimeout(poll, interval);
        
      } catch (error) {
        console.error(`第${attempts}次轮询失败:`, error);
        
        // 检查是否已取消轮询
        if (currentController.cancelled) {
          console.log('轮询已被取消');
          resolve(null);
          return;
        }
        
        // 如果是网络错误且还没超过最大尝试次数，继续尝试
        if (attempts < maxAttempts) {
          setTimeout(poll, interval);
        } else {
          pollingController = null; // 清理控制器
          reject(error);
        }
      }
    };
    
    // 开始第一次轮询
    poll();
  });
};

// 取消轮询的函数
const cancelPolling = () => {
  if (pollingController) {
    pollingController.cancelled = true;
    pollingController = null;
    console.log('轮询已被手动取消');
  }
};

// 处理取消生成题目
const handleCancelGenerate = () => {
  cancelPolling();
  autoGenerateLoading.value = false;
  ElMessage.info('已取消AI自动组题');
};

// 处理得分题开关变化
const handleScoreQuestionsChange = async (value: boolean) => {
  console.log('得分题开关状态:', value ? '开启' : '关闭');
  
  if (value) {
    const response = await GetQuestionList({page:1,limit:1000,question_form:4,tenant_id:Session.get('tenant_id')});
    console.log(response);
    if (response && response.data) {
      BatchBind({
        position_id: route.query.id,
        question_id: {question_id:response.data.items.map((item: any) => item.id)},
        tenant_id: Session.get('tenant_id')
      }).then(async (res:any)=>{
        if(res.code===2000){
          // 绑定成功后更新配置中的enable_psychological_test字段
          try {
            if (getConfigId.value > 0) {
              await UpdateConfig({
                id: getConfigId.value,
                enable_psychological_test: true
              });
              console.log('配置中的enable_psychological_test字段已更新为true');
                         }else{
               const createResponse = await CreateConfig({
                 position_id: route.query.id,
                 enable_psychological_test: true,
                 tenant_id:Session.get('tenant_id')
               });
               if (createResponse && createResponse.code === 2000) {
                 getConfigId.value = createResponse.data?.id || createResponse.data;
                 console.log('配置创建成功，enable_psychological_test字段已设置为true');
               }
             }
          } catch (error) {
            console.error('更新enable_psychological_test字段失败:', error);
            // 不显示错误消息给用户，避免影响主要功能的用户体验
          }
          
          ElMessage.success('得分题功能已开启');
        }else{
          ElMessage.error('得分题功能开启失败');
        }
      })
      
    } else {
      ElMessage.error('获取题目列表失败');
    }
    // 可以在这里添加开启得分题时的特殊逻辑
    // 比如：自动添加得分相关的题目类型、更新界面显示等
  } else {
    try {
      const response = await GetQuestionList({page:1,limit:1000,question_form:4,tenant_id:1});
      if (response && response.data) {
      await BatchUnbind({
        position_id: route.query.id,
        question_id:response.data.items.map((item: any) => item.id),
        tenant_id: Session.get('tenant_id')
      });
      
      // 解绑成功后更新配置中的enable_psychological_test字段
      if (getConfigId.value > 0) {
        await UpdateConfig({
          id: getConfigId.value,
          enable_psychological_test: false
        });
        console.log('配置中的enable_psychological_test字段已更新为false');
      } else {
        // 如果没有配置ID，创建新配置并设置为false
        const createResponse = await CreateConfig({
          position_id: route.query.id,
          enable_psychological_test: false,
          tenant_id: Session.get('tenant_id')
        });
        if (createResponse && createResponse.code === 2000) {
          getConfigId.value = createResponse.data?.id || createResponse.data;
          console.log('配置创建成功，enable_psychological_test字段已设置为false');
        }
      }
      
      ElMessage.info('得分题功能已关闭');
      }
    } catch (error) {
      console.error('关闭得分题功能失败:', error);
      ElMessage.error('关闭得分题功能失败');
    }
    // 可以在这里添加关闭得分题时的清理逻辑
  }
  
  // 可以在这里调用API保存设置状态
  // await saveQuestionSettings(questionSettings);
};

// 处理色盲题开关变化
const handleColorBlindQuestionsChange = async (value: boolean) => {
  console.log('色盲题开关状态:', value ? '开启' : '关闭');
  
  if (value) {
    // 开启色盲题
    const response = await GetQuestionList({page:1,limit:1000,question_form:3,tenant_id:1}); // 假设色盲题的question_form为5
    console.log(response);
    if (response && response.data) {
      BatchBind({
        position_id: route.query.id,
        question_id: {question_id:response.data.items.map((item: any) => item.id)},
        tenant_id: Session.get('tenant_id')
      }).then(async (res:any)=>{
        if(res.code===2000){
          // 绑定成功后更新配置中的enable_color_blind_test字段
          try {
            if (getConfigId.value > 0) {
              await UpdateConfig({
                id: getConfigId.value,
                enable_color_blind_test: true
              });
              console.log('配置中的enable_color_blind_test字段已更新为true');
            }else{
              const createResponse = await CreateConfig({
                position_id: route.query.id,
                enable_color_blind_test: true,
                tenant_id:Session.get('tenant_id')
              });
              if (createResponse && createResponse.code === 2000) {
                getConfigId.value = createResponse.data?.id || createResponse.data;
                console.log('配置创建成功，enable_color_blind_test字段已设置为true');
              }
            }
          } catch (error) {
            console.error('更新enable_color_blind_test字段失败:', error);
            // 不显示错误消息给用户，避免影响主要功能的用户体验
          }
          
          ElMessage.success('色盲题功能已开启');
        }else{
          ElMessage.error('色盲题功能开启失败');
        }
      })
      
    } else {
      ElMessage.error('获取色盲题目列表失败');
    }
    // 可以在这里添加开启色盲题时的特殊逻辑
    // 比如：自动添加色盲测试相关题目、设置特殊的评分标准等
  } else {
    // 关闭色盲题
    try {
      const response = await GetQuestionList({page:1,limit:1000,question_form:3,tenant_id:1}); // 假设色盲题的question_form为5
      if (response && response.data) {
        await BatchUnbind({
          position_id: route.query.id,
          question_id:response.data.items.map((item: any) => item.id),
          tenant_id: Session.get('tenant_id')
        });
        
        // 解绑成功后更新配置中的enable_color_blind_test字段
        if (getConfigId.value > 0) {
          await UpdateConfig({
            id: getConfigId.value,
            enable_color_blind_test: false
          });
          console.log('配置中的enable_color_blind_test字段已更新为false');
        } else {
          // 如果没有配置ID，创建新配置并设置为false
          const createResponse = await CreateConfig({
            position_id: route.query.id,
            enable_color_blind_test: false,
            tenant_id:Session.get('tenant_id')
          });
          if (createResponse && createResponse.code === 2000) {
            getConfigId.value = createResponse.data?.id || createResponse.data;
            console.log('配置创建成功，enable_color_blind_test字段已设置为false');
          }
        }
        
        ElMessage.info('色盲题功能已关闭');
      }
    } catch (error) {
      console.error('关闭色盲题功能失败:', error);
      ElMessage.error('关闭色盲题功能失败');
    }
    // 可以在这里添加关闭色盲题时的清理逻辑
  }
};

// 在 script setup 中添加以下内容
// 题目选择相关的响应式变量
const showQuestionSelectDialog = ref(false);
const questionSearchKeyword = ref('');
const questionList = ref([]);
const selectedQuestions = ref([]);

// QuestionBankForm 相关的状态管理
const showQuestionBankFormDialog = ref(false);
const questionBankFormData = ref({});
const isEditingQuestion = ref(false);
const totalQuestions = ref(0);
const totalQuestions2 = ref(0);
const questionListQuery = reactive({
  page: 1,
  pageSize: 10,
  keyword: '',
  question_form: null as number | null
});
const questionListpage = reactive({
  page: 1,
  limit: 20,
  keyword: '',
  question_form: null as number | null
});

// 获取题目列表
const fetchQuestionList = async () => {
  try {
    const params = {
      ...questionListQuery,
      keyword: questionSearchKeyword.value,
      // 只有当选择了题目类型时才传递该参数
      ...(questionListQuery.question_form !== null && { question_form: questionListQuery.question_form })
    };
    const response = await GetQuestionList(params);
    if (response && response.data) {
      questionList.value = response.data.items;
      totalQuestions.value = response.data.total;
    }
  } catch (error) {
    console.error('获取题目列表失败:', error);
    ElMessage.error('获取题目列表失败');
  }
};

// 处理题目搜索
const handleQuestionSearch = () => {
  questionListQuery.page = 1;
  fetchQuestionList();
};

// 处理分页大小变化
const handleQuestionSizeChange = (val: number) => {
  questionListQuery.pageSize = val;
  fetchQuestionList();
};

// 处理页码变化
const handleQuestionPageChange = (val: number) => {
  questionListQuery.page = val;
  fetchQuestionList();
};

// 处理题目选择变化
const handleQuestionSelectionChange = (selection: any[]) => {
  selectedQuestions.value = selection;
};

// 取消选择题目
const cancelQuestionSelect = () => {
  showQuestionSelectDialog.value = false;
  selectedQuestions.value = [];
  questionSearchKeyword.value = '';
};

const confirmQuestionSelect = async () => {
  // 1. 验证是否选择了题目
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请至少选择一个题目');
    return;
  }

  try {
    // 2. 获取选中题目的ID列表
    const selectedQuestionIds = selectedQuestions.value.map(item => item.id);

    // 3. 调用AddDocument接口进行绑定
    await AddDocument({
      position_id: route.query.id,
      question_id: selectedQuestionIds,
      duration: 60, // 默认时长
      tenant_id:Session.get('tenant_id')
    });

    // 4. 将选中的题目添加到本地列表中
    const formattedQuestions = selectedQuestions.value.map((question: any) => ({
      id: question.id,
      title: question.question || question.title,
      ability: question.ability || '未设置',
      content: question.content || question.question,
      target: question.target || '未设置',
      competency_tags: question.competency_tags || [],
      question_form_name: question.question_form_name,
      scoring_reference: question.scoring_reference,
      question_form: question.question_form,
      is_required_correct: question.is_required_correct,
      weight: 100,
      maxAnswers: 1,
      enable_follow_up: true,
      options: question.options || [],
      source: 'custom_selected' as const
    }));
    
    chatQuestions.value.push(...formattedQuestions);
    
    // 5. 关闭对话框并重置状态
    showQuestionSelectDialog.value = false;
    selectedQuestions.value = [];
    questionSearchKeyword.value = '';
    
    // 6. 显示成功提示
    ElMessage.success('题目添加成功');

  } catch (error: any) {
    console.error('添加题目失败:', error);
    showQuestionSelectDialog.value = false;
    if (error.code === 4000) {
      ElMessage.warning('该题目已绑定，请选择其他题目');
    } else {
      ElMessage.error('添加题目失败，请重试');
    }
  }
};

// 字段配置数据
const fieldConfig = reactive({
  // 基本信息
  name: { visible: true, label: '姓名', required: true },
  gender: { visible: true, label: '性别', required: true },
  three_period: { visible: true, label: '是否为三期', required: true },
  phone: { visible: true, label: '手机号', required: true },
  id_card: { visible: true, label: '身份证号', required: true },
  ethnicity: { visible: true, label: '民族', required: true },
  height: { visible: true, label: '身高(cm)', required: false },
  weight: { visible: true, label: '体重(kg)', required: false },
  current_address: { visible: true, label: '现居住地址', required: true },
  household_location: { visible: true, label: '户口所在地', required: false },
  marital_status: { visible: true, label: '婚育状况', required: false },
  expected_salary: { visible: true, label: '期望薪资(元/月)', required: false },

  // 家庭成员信息
  family_member: {
    visible: true,
    label: '家庭成员',
    fields: {
      relation: { visible: true, label: '称谓', required: true },
      name: { visible: true, label: '姓名', required: true },
      workplace_address: { visible: true, label: '工作单位/家庭地址', required: false },
      position: { visible: true, label: '职务', required: false },
      phone: { visible: true, label: '联系电话', required: true },
      is_emergency_contact: { visible: true, label: '是否为紧急联系人', required: false }
    }
  },

  // 教育经历
  education: {
    visible: true,
    label: '教育经历',
    fields: {
      start_time: { visible: true, label: '开始时间', required: true },
      end_time: { visible: true, label: '结束时间', required: true },
      school_name: { visible: true, label: '学校名称', required: true },
      major: { visible: true, label: '专业', required: true },
      degree: { visible: true, label: '学历', required: true }
    }
  },

  // 专业技能
  require_professional_skills: { visible: true, label: '专业技能', required: true },
  training_fields_config: { visible: true, label: '受过的培训', required: true },

  // 工作经历
  work_experience: {
    visible: true,
    label: '工作经历',
    fields: {
      start_time: { visible: true, label: '开始时间', required: true },
      end_time: { visible: true, label: '结束时间', required: true },
      company_name: { visible: true, label: '单位名称', required: true },
      employee_count: { visible: true, label: '单位人数', required: true },
      department: { visible: true, label: '任职部门', required: true },
      position: { visible: true, label: '担任职务', required: true },
      monthly_salary: { visible: true, label: '月总收入', required: true },
      supervisor: { visible: true, label: '直接领导', required: true },
      supervisor_phone: { visible: true, label: '领导电话', required: true }
    }
  },
  question_form_switches:{
        enable_open_questions: true,      // 0: 开放问题
        enable_single_choice: true,       // 1: 单选题
        enable_multiple_choice: true,     // 2: 多选题
        enable_image_choice: true,        // 3: 看图选答案
        enable_scoring_questions: true,   // 4: 得分题
        enable_follow_up_questions: true, // 5: 追加型开放问题
        enable_fill_blank: true           // 6: 填空题
  }
});

// 保存字段配置
const saveFieldConfig = async () => {
  try {
    // 构建配置数据
    const configData = {
      position_id: route.query.id, // 职位ID
      /* config_name: "咖啡师配置", // 配置名称
      digital_human_id: 4, // 数字人ID */
      
      // 简历上传配置
      require_resume_upload: true, // 是否要求上传简历
      resume_file_types: ["pdf", "docx", "doc"], // 允许的文件类型
      max_resume_size_mb: 10, // 最大文件大小(MB)
      digital_human_opening_speech:'你好，我是本次面试的面试官，欢迎参加本公司的线上面试!面试预计需要15分钟，请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试以免影响本次面试的结果。如果你在面试过程中遇到问题，请与我们的招聘人员联系。',
      // 个人信息配置
      require_basic_info: true, // 是否要求填写基本信息
      profile_fields_config: {
        name: { required: fieldConfig.name.required, visible: fieldConfig.name.visible },
        phone: { required: fieldConfig.phone.required, visible: fieldConfig.phone.visible },
        id_card: { required: fieldConfig.id_card.required, visible: fieldConfig.id_card.visible },
        gender: { required: fieldConfig.gender.required, visible: fieldConfig.gender.visible },
        birth_date: { required: false, visible: true },
        political_status: { required: false, visible: true },
        ethnicity: { required: fieldConfig.ethnicity.required, visible: fieldConfig.ethnicity.visible },
        height: { required: fieldConfig.height.required, visible: fieldConfig.height.visible },
        weight: { required: fieldConfig.weight.required, visible: fieldConfig.weight.visible },
        marital_status: { required: fieldConfig.marital_status.required, visible: fieldConfig.marital_status.visible }
      },
      
      // 教育信息配置
      require_education_info: fieldConfig.education.visible, // 是否要求填写教育信息
      education_fields_config: {
        school_name: { required: fieldConfig.education.fields.school_name.required, visible: fieldConfig.education.fields.school_name.visible },
        major: { required: fieldConfig.education.fields.major.required, visible: fieldConfig.education.fields.major.visible },
        degree: { required: fieldConfig.education.fields.degree.required, visible: fieldConfig.education.fields.degree.visible },
        start_date: { required: fieldConfig.education.fields.start_time.required, visible: fieldConfig.education.fields.start_time.visible },
        end_date: { required: fieldConfig.education.fields.end_time.required, visible: fieldConfig.education.fields.end_time.visible }
      },
      
      // 工作经验配置
      require_work_experience: fieldConfig.work_experience.visible, // 是否要求填写工作经验
      work_experience_fields_config: {
        company_name: { required: fieldConfig.work_experience.fields.company_name.required, visible: fieldConfig.work_experience.fields.company_name.visible },
        position: { required: fieldConfig.work_experience.fields.position.required, visible: fieldConfig.work_experience.fields.position.visible },
        department: { required: fieldConfig.work_experience.fields.department.required, visible: fieldConfig.work_experience.fields.department.visible },
        start_date: { required: fieldConfig.work_experience.fields.start_time.required, visible: fieldConfig.work_experience.fields.start_time.visible },
        end_date: { required: fieldConfig.work_experience.fields.end_time.required, visible: fieldConfig.work_experience.fields.end_time.visible },
        job_description: { required: true, visible: true },
        achievements: { required: false, visible: true },
        resignation_reason: { required: false, visible: true }
      },
      
      // 家庭信息配置
      require_family_info: fieldConfig.family_member.visible, // 是否要求填写家庭信息
      family_fields_config: {
        relation: { required: fieldConfig.family_member.fields.relation.required, visible: fieldConfig.family_member.fields.relation.visible },
        name: { required: fieldConfig.family_member.fields.name.required, visible: fieldConfig.family_member.fields.name.visible },
        workplace: { required: fieldConfig.family_member.fields.workplace_address.required, visible: fieldConfig.family_member.fields.workplace_address.visible },
        position: { required: fieldConfig.family_member.fields.position.required, visible: fieldConfig.family_member.fields.position.visible },
        phone: { required: fieldConfig.family_member.fields.phone.required, visible: fieldConfig.family_member.fields.phone.visible }
      },
      
      // 培训经历配置
      require_training_info: fieldConfig.training_fields_config.visible,
      require_professional_skills: fieldConfig.require_professional_skills.visible,

   /*    training_fields_config: {
        training_name: { required: true, visible: true },
        institution: { required: true, visible: true },
        start_date: { required: true, visible: true },
        end_date: { required: false, visible: true },
        certificate: { required: false, visible: true }
      },
       */
      // 姿态配置
      enable_posture_check: true,
      posture_check_config: {
        required_photos: ["front", "side", "back"],
        instructions: "请按照提示上传您的全身照片，确保光线充足，背景简洁"
      },
      
      // 面试配置
      interview_duration_minutes: 45,
      enable_video_recording: true,
      enable_face_recognition: true,
      
      // 评分配置
      scoring_method: "hybrid",
      auto_analysis_enabled: true,
      
      // 其他配置
      custom_welcome_message: "欢迎参加咖啡师岗位的面试，请放松心情，准备好开始面试吧！",
      custom_instructions: "本次面试共有10个问题，每个问题有60秒的回答时间，请简洁明了地表达您的观点。",
      
      notification_config: {
        send_email: true,
        send_sms: false,
        notify_hr: true,
        completion_message: "感谢您完成面试，我们将在3个工作日内给您回复。"
      },
      
      is_active: true,
      is_template: false
    };
    if(getConfigId.value==0){
    }else{
      configData.id=getConfigId.value;
    }
    
    // 调用后端 API
    if(getConfigId.value==0){
      const response = await CreateConfig(configData);
       if(response.code==2000){
      ElMessage.success('配置保存成功');
      showDataCollectionDialog.value = false;
      showOptionsMenu.value = false;  
    }else{
      ElMessage.error('配置保存失败');
    }
    }else{
      //configData.digital_human_opening_speech='你好，我是本次面试的面试官，欢迎参加本公司的线上面试!面试预计需要15分钟，请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试以免影响本次面试的结果。如果你在面试过程中遇到问题，请与我们的招聘人员联系。'
      const response = await UpdateConfig(configData);
      if(response.code==2000){
        ElMessage.success('配置保存成功');
        showDataCollectionDialog.value = false;
        showOptionsMenu.value = false;  
      }else{
        ElMessage.error('配置保存失败');
      }
    }
   
  } catch (error) {
    console.error('保存配置失败:', error);
    ElMessage.error('配置保存失败');
  }
};

// 获取基本信息字段
const getBasicFields = () => {
  const basicFields = {
    name: fieldConfig.name,
    gender: fieldConfig.gender,
    three_period: fieldConfig.three_period,
    phone: fieldConfig.phone,
    id_card: fieldConfig.id_card,
    ethnicity: fieldConfig.ethnicity,
    height: fieldConfig.height,
    weight: fieldConfig.weight,
    current_address: fieldConfig.current_address,
    household_location: fieldConfig.household_location,
    marital_status: fieldConfig.marital_status,
    expected_salary: fieldConfig.expected_salary
  };
  return basicFields;
};

// 获取专业技能字段
const getSkillFields = () => {
  const skillFields = {
    skills: fieldConfig.require_professional_skills,
    training: fieldConfig.training_fields_config
  };
  return skillFields;
};

// 面试设置弹窗
const showInterviewSettingsDialog = ref(false);
const interviewSettings = reactive({
  faceConsistency: true,
  preventScreenshot: true,
  screenSwitchAlert: true,
  positionDetection: true,
  eyeMovementDetection: true,
  reviewInterview: false,
  beforeStart: true,
  beforeStartText: '你好，我是本次面试的面试官，欢迎参加本公司的线上面试!面试预计需要15分钟，请你提前安排在网络良好、光线亮度合适、且相对安静的环境参加这次面试以免影响本次面试的结果。如果你在面试过程中遇到问题，请与我们的招聘人员联系。',
  afterStartReminder: false,
  afterStartText: '本次面试如有15分钟，高效调前后流程，安静好心理',
  disclaimer: false,
  disclaimerText: '本次面试已全部结束，感谢您的参与，请等待后续通知。'
});

// 编辑状态变量
const isEditingBeforeStart = ref(false);
const isEditingAfterStart = ref(false);
const isEditingDisclaimer = ref(false);

// 编辑中的文本内容
const editingBeforeStartText = ref('');
const editingAfterStartText = ref('');
const editingDisclaimerText = ref('');

// 取消面试设置
const cancelInterviewSettings = () => {
  showInterviewSettingsDialog.value = false;
  // 重置编辑状态
  isEditingBeforeStart.value = false;
  isEditingAfterStart.value = false;
  isEditingDisclaimer.value = false;
  // 重置表单
  Object.assign(interviewSettings, {
    faceConsistency: true,
    preventScreenshot: true,
    screenSwitchAlert: true,
    positionDetection: true,
    eyeMovementDetection: true,
    reviewInterview: false,
    beforeStart: true,
    beforeStartText: '你好，我想咨询其间的面试，欢迎来到大面试',
    afterStartReminder: false,
    afterStartText: '本次面试如有15分钟，高效调前后流程，安静好心理',
    disclaimer: false,
    disclaimerText: '本次面试已全部流程拍摄，面试者同意可为今后资讯调研'
  });
};

// 确认面试设置
const confirmInterviewSettings = () => {
  // 这里可以添加保存面试设置的API调用
  console.log('保存面试设置:', interviewSettings);
  ElMessage.success('面试设置已保存');
  showInterviewSettingsDialog.value = false;
};

// 编辑面试设置
const handleEditInterview = () => {
  GetConfig(route.query.id).then((res:any)=>{
    showInterviewSettingsDialog.value = true;
    getConfigId.value=res.data.id;
    interviewSettings.beforeStartText = res.data.digital_human_opening_speech;
  })
  
};

// 开始前文本编辑方法
const startEditBeforeStart = () => {
  editingBeforeStartText.value = interviewSettings.beforeStartText;
  isEditingBeforeStart.value = true;
};

const cancelEditBeforeStart = () => {
  isEditingBeforeStart.value = false;
  editingBeforeStartText.value = '';
};

const saveBeforeStart = async () => {
  if (!editingBeforeStartText.value.trim()) {
    ElMessage.warning('开始前提示内容不能为空');
    return;
  }
  
  interviewSettings.beforeStartText = editingBeforeStartText.value.trim();
  
  try {
    let response;
      console.log(getConfigId.value);
    // 根据getConfigId的值决定调用哪个接口
    if (getConfigId.value == 0) {
      // getConfigId不等于0时，调用CreateConfig接口
      response = await CreateConfig({
        position_id: route.query.id,
        digital_human_opening_speech: editingBeforeStartText.value.trim()
      });
      
      if (response.code === 2000) {
        // 创建成功后更新getConfigId
        getConfigId.value = response.data?.id || response.data;
        ElMessage.success('开始前提示内容已创建');
        isEditingBeforeStart.value = false;
      } else {
        ElMessage.error('开始前提示内容创建失败');
      }
    } else {
      // getConfigId等于0时，调用UpdateConfig接口
      response = await UpdateConfig({
        id: getConfigId.value,
        digital_human_opening_speech: editingBeforeStartText.value.trim()
      });
      
      if (response.code === 2000) {
        ElMessage.success('开始前提示内容已更新');
        isEditingBeforeStart.value = false;
        
        // 调用GetOpeningSpeech接口
        try {
          const params = { config_id: getConfigId.value };
          await GetOpeningSpeech(params);
          console.log('开场白生成成功');
        } catch (error) {
          console.error('获取开场白失败:', error);
          ElMessage.warning('开场白生成中，请稍后');
        }
      } else {
        ElMessage.error('开始前提示内容更新失败');
      }
    }
  } catch (error) {
    console.error('保存开始前提示内容失败:', error);
    ElMessage.error('保存失败，请重试');
  }
};

// 开始后提醒编辑方法
const startEditAfterStart = () => {
  editingAfterStartText.value = interviewSettings.afterStartText;
  isEditingAfterStart.value = true;
};

const cancelEditAfterStart = () => {
  isEditingAfterStart.value = false;
  editingAfterStartText.value = '';
};

const saveAfterStart = () => {
  if (!editingAfterStartText.value.trim()) {
    ElMessage.warning('开始后提醒内容不能为空');
    return;
  }
  
  interviewSettings.afterStartText = editingAfterStartText.value.trim();
  isEditingAfterStart.value = false;
  ElMessage.success('开始后提醒内容已更新');
};

// 免责声明编辑方法
const startEditDisclaimer = () => {
  editingDisclaimerText.value = interviewSettings.disclaimerText;
  isEditingDisclaimer.value = true;
};

const cancelEditDisclaimer = () => {
  isEditingDisclaimer.value = false;
  editingDisclaimerText.value = '';
};

const saveDisclaimer = () => {
  if (!editingDisclaimerText.value.trim()) {
    ElMessage.warning('免责声明内容不能为空');
    return;
  }
  
  interviewSettings.disclaimerText = editingDisclaimerText.value.trim();
  isEditingDisclaimer.value = false;
  ElMessage.success('免责声明内容已更新');
};

// 题目数量设置
const questionCountSettings = reactive({
  openQuestionsCount: 5,
  choiceQuestionsCount: 10
});

// 处理题目数量变化
const handleQuestionCountChange = () => {
  // 这里可以添加其他逻辑，比如保存到本地存储等
  console.log('题目数量已更新:', questionCountSettings);
};

// 修改自动生成题目的方法
const handleAutoGenerate = async () => {
  try {
    autoGenerateLoading.value = true;
    
    // 获取选中的能力标签ID
    const competencyTagIds = selectedAbilities.value.map(ability => {
      return ability.id;
    });/* selectedDimensions.value.map(dimension => {
      const tag = competencyTags.value.find(tag => tag.name === dimension.name);
      return tag ? tag.id : null;
    }).filter(id => id !== null); */
    
    if (competencyTagIds.length === 0) {
      ElMessage.warning('请先选择能力标签');
      return;
    }

    const params = {
      position_id: route.query.id,
      competency_tag_ids: competencyTagIds,
      open_questions_count: questionCountSettings.openQuestionsCount, // 使用设置的开放题数量
      choice_questions_count: questionCountSettings.choiceQuestionsCount, // 使用设置的选择题数量
      auto_save: true,
      tenant_id: Session.get('tenant_id')
    };

    // 调用生成题目的接口
    const response = await GenerateQuestions(params);
    
    if (response && response.data) {
      // 生成成功后，使用轮询获取最新生成的题目
      const draftResponse = await pollForDraftList({
        tenant_id:Session.get('tenant_id'),
        page: 1,
        limit: 30,
        position_id: route.query.id as string
      });
  console.log(draftResponse);
      
      // 检查轮询是否被取消
      if (draftResponse === null) {
        console.log('轮询被取消，停止处理');
        return;
      }
      
      if (draftResponse && draftResponse.data && draftResponse.data.dataList) {
        // 将获取到的题目格式化并添加到 chatQuestions 列表中
        const formattedQuestions = draftResponse.data.dataList.map((question: any) => ({
          id: question.id || Date.now(),
          title: question.question || question.title,
          ability: question.ability || '未设置',
          content: question.content || question.question,
          target: question.target || '未设置',
          competency_tags: question.competency_tag_info || [],
          question_form_name: question.question_form_name,
          scoring_reference: question.scoring_reference,
          question_form: question.question_form,
          is_required_correct: question.is_required_correct,
          weight: 100,
          maxAnswers: 1,
          enable_follow_up:true,
          options: question.options || [],
          source: 'ai_generated' as const // 标识为AI生成的题目
        }));
        
        // 清空现有题目并添加新生成的题目
        chatQuestions.value = formattedQuestions;
        ElMessage.success(`已成功生成${formattedQuestions.length}个面试题目`);
      } else {
        ElMessage.warning('AI生成题目中，请稍后再试');
      }
    }
  } catch (error) {
    console.error('AI自动组题失败:', error);
    ElMessage.error('AI自动组题失败，请重试');
  } finally {
    // 无论成功或失败都要关闭loading状态
    autoGenerateLoading.value = false;
  }
};

// 处理胜任力标签变化
const handleCompetencyTagsChange = (value: string[]) => {
  // 更新选中的标签ID
  questionForm.competency_tags = [];
  
  if (value.length > 0) {
    // 计算每个标签的均分权重
    const averageWeight = Math.floor(100 / value.length);
    const remainder = 100 % value.length;
    
    // 根据选中的标签ID，从competencyTagOptions中获取完整的标签信息
    questionForm.competency_tags = value.map((tagId, index) => {
      const tagOption = competencyTagOptions.value.find(option => option.id === tagId);
      return {
        id: tagId,
        name: tagOption ? tagOption.name : `标签${tagId}`,
        // 均分权重，余数分配给前几个标签
        weight: averageWeight + (index < remainder ? 1 : 0)
      };
    });
  }
};

// 验证胜任力配置
const validateCompetencyConfig = () => {
  if (questionForm.competency_tags.length === 0) {
    ElMessage.warning('请至少选择一个胜任力标签');
    return false;
  }
  
  if (questionForm.weight <= 0 || questionForm.weight > 100) {
    ElMessage.warning('权重必须在1-100之间');
    return false;
  }
  
  
  return true;
};

// 处理题目形式变化
const handleQuestionTypeChange = (value: string) => {
  questionForm.type = value;
  // 根据题目形式设置默认建议时长
  switch (value) {
    case 'open':
      questionForm.suggestedDuration = 120; // 开放题默认2分钟
      break;
    case 'single':
    case 'multiple':
      questionForm.suggestedDuration = 60; // 选择题默认1分钟
      break;
    case 'fill':
      questionForm.suggestedDuration = 30; // 填空题默认30秒
      break;
    case 'self':
      questionForm.suggestedDuration = 180; // 自言语默认3分钟
      break;
    default:
      questionForm.suggestedDuration = 60;
  }
};

// 添加状态变量
const competencyLoading = ref(false);

// 候选人提问环节相关变量 - 用于候选人向面试官提问的环节配置
const showCandidateQuestionsDialog = ref(false); // 控制候选人提问弹窗显示
const editingCandidateQuestionsIndex = ref(-1); // 编辑候选人提问环节的索引
const candidateQuestionsForm = reactive({
  title: '候选人提问', // 环节名称
  duration: 5, // 提问时长（分钟）
  maxQuestions: 3, // 最多提问数量
  description: '候选人可以向面试官提问关于公司、职位或团队的问题', // 环节描述
  isRequired: true, // 是否必须环节
  allowSkip: false, // 是否允许跳过
  guidelines: [ // 提问指引
    '请提出与职位、公司文化或团队相关的问题',
    '避免询问已在职位描述中明确说明的信息',
    '可以询问职业发展机会和团队工作方式'
  ]
});

const removeGuideline = (index: number) => {
  candidateQuestionsForm.guidelines.splice(index, 1);
};

const addGuideline = () => {
  candidateQuestionsForm.guidelines.push('');
};

// 编辑候选人提问环节
const editCandidateQuestions = (step: any, index: number) => {
  editingCandidateQuestionsIndex.value = index;
  
  // 如果步骤有配置信息，加载到表单中
  if (step.config) {
    Object.assign(candidateQuestionsForm, step.config);
  } else {
    // 如果没有配置信息，从步骤的基本信息推断
    candidateQuestionsForm.title = step.name;
    candidateQuestionsForm.description = step.description || '候选人可以向面试官提问关于公司、职位或团队的问题';
    candidateQuestionsForm.duration = 5;
    candidateQuestionsForm.maxQuestions = 3;
    candidateQuestionsForm.isRequired = step.active;
    candidateQuestionsForm.allowSkip = false;
    candidateQuestionsForm.guidelines = [
      '请提出与职位、公司文化或团队相关的问题',
      '避免询问已在职位描述中明确说明的信息',
      '可以询问职业发展机会和团队工作方式'
    ];
  }
  
  showCandidateQuestionsDialog.value = true;
};

// 统一的编辑流程步骤方法
const editProcessStep = (step: any, index: number) => {
  switch (step.type) {
    case 'ai_video':
      editAIVideo(step);
      break;
    case 'candidate_questions':
      editCandidateQuestions(step, index);
      break;
    case 'data_collection':
      // TODO: 添加资料收集编辑功能
      editAIVideo(step);
      /* ElMessage.info('资料收集编辑功能开发中'); */
      break;
    case 'resume_collection':
      // TODO: 添加简历收集编辑功能
      editAIVideo(step);
      break;
    default:
    editAIVideo(step);
      break;
  }
};

// 权重变化处理函数
const handleWeightChange = (index: number, value: number | null) => {
  if (value === null || value < 0) value = 0;
  if (value > 100) value = 100;
  
  const tags = questionForm.competency_tags as CompetencyTagItem[];
  const oldWeight = tags[index].weight;
  const newWeight = Math.round(value);
  
  // 更新当前标签权重
  tags[index].weight = newWeight;
  
  // 如果只有一个标签，直接设置为100
  if (tags.length === 1) {
    tags[0].weight = 100;
    return;
  }
  
  // 计算权重差值
  const weightDiff = newWeight - oldWeight;
  const otherTags = tags.filter((_, i) => i !== index);
  const totalOtherWeight = otherTags.reduce((sum, tag) => sum + tag.weight, 0);
  
  // 如果其他标签总权重为0，则平均分配剩余权重
  if (totalOtherWeight === 0) {
    const remainingWeight = 100 - newWeight;
    const averageWeight = Math.floor(remainingWeight / otherTags.length);
    const remainder = remainingWeight % otherTags.length;
    
    otherTags.forEach((tag, i) => {
      const tagIndex = tags.findIndex(t => t.id === tag.id);
      tags[tagIndex].weight = averageWeight + (i < remainder ? 1 : 0);
    });
  } else {
    // 按比例调整其他标签权重
    const targetTotalOther = 100 - newWeight;
    
    if (targetTotalOther > 0) {
      otherTags.forEach(tag => {
        const tagIndex = tags.findIndex(t => t.id === tag.id);
        const proportion = tag.weight / totalOtherWeight;
        tags[tagIndex].weight = Math.round(targetTotalOther * proportion);
      });
      
      // 处理舍入误差
      const currentTotal = getTotalWeight();
      if (currentTotal !== 100) {
        const diff = 100 - currentTotal;
        // 找到最大权重的其他标签进行调整
        const maxOtherTag = otherTags.reduce((max, tag) => 
          tag.weight > max.weight ? tag : max
        );
        const maxTagIndex = tags.findIndex(t => t.id === maxOtherTag.id);
        tags[maxTagIndex].weight += diff;
      }
    } else {
      // 如果当前权重已经是100%，其他标签设为0
      otherTags.forEach(tag => {
        const tagIndex = tags.findIndex(t => t.id === tag.id);
        tags[tagIndex].weight = 0;
      });
    }
  }
};

// 获取总权重
const getTotalWeight = (): number => {
  const tags = questionForm.competency_tags as CompetencyTagItem[];
  return tags.reduce((total, tag) => total + (tag.weight || 0), 0);
};

// 平均分配权重
const distributeWeightsEvenly = () => {
  const tags = questionForm.competency_tags as CompetencyTagItem[];
  if (tags.length === 0) return;
  
  const averageWeight = Math.floor(100 / tags.length);
  const remainder = 100 % tags.length;
  
  tags.forEach((tag, index) => {
    tag.weight = averageWeight + (index < remainder ? 1 : 0);
  });
};

const competencyTagsValue = computed({
  get: () => getcompetency_tags(questionForm.competency_tags),
  set: (value) => {
    questionForm.competency_tags = value;
    handleCompetencyTagsChange(value);
  }
});

// 删除AI考察相关问题
const handleDeleteAIQuestions = async () => {
  try {
    // 获取当前职位下的所有AI生成的问题
    const response = await GetPositionQuestions({
      position_id: route.query.id,
      tenant_id: Session.get('tenant_id'),
      is_ai_generated: true // 只获取AI生成的问题
    });

    if (response && response.data && response.data.length > 0) {
      // 批量解绑AI生成的问题
      await BatchUnbind({
        position_id: route.query.id,
        question_id: response.data.map((item: any) => item.id),
        tenant_id:Session.get('tenant_id')
      });

      // 更新配置
      if (getConfigId.value > 0) {
        await UpdateConfig({
          id: getConfigId.value,
          enable_ai_questions: false
        });
      }

      ElMessage.success('AI考察问题已删除');
    }
  } catch (error) {
    console.error('删除AI考察问题失败:', error);
    ElMessage.error('删除AI考察问题失败');
  }
};

// 在setup部分添加以下代码
// ... existing code ...
// 监听enable_open_questions的变化
watch(
  () => fieldConfig.question_form_switches.enable_open_questions,
  (newVal) => {
    if (!newVal) {
      // 如果禁用了AI考察，隐藏相关内容
      recruitmentProcess.forEach((process) => {
        if (process.type === 'ai_interview') {
          process.visible = false;
        }
      });
    } else {
      // 如果启用了AI考察，显示相关内容
      recruitmentProcess.forEach((process) => {
        if (process.type === 'ai_interview') {
          process.visible = true;
        }
      });
    }
  },
  { immediate: true }
);

// 修改添加AI考察的方法
const addAIInterview = () => {
  // 添加AI考察时，自动启用enable_open_questions
  UpdateConfig({
    id: route.query.id,
    question_form_switches: {
      ...fieldConfig.question_form_switches,
      enable_open_questions: true
    }
  }).then((res:any) => {
    if(res.code == 2000) {
      // 添加AI考察的其他逻辑...
    }
  });
};
// ... existing code ...

// 新增对话框控制变量
const showCommonSenseDialog = ref(false);
const showPsychologicalDialog = ref(false);
const showPostRenderDialog = ref(false);

// 在setup中添加相关变量和方法
const bodyDetectionConfigVisible = ref(false)
const bodyDetectionConfig = ref({
  duration: 5,
  detectionItems: ['face', 'pose'],
  promptText: '请按照提示完成相应的动作，系统将自动进行检测。'
})

// 打开肢体检测配置
const openBodyDetectionConfig = () => {
  bodyDetectionConfigVisible.value = true
}

// 取消肢体检测配置
const cancelBodyDetectionConfig = () => {
  bodyDetectionConfigVisible.value = false
}

// 保存肢体检测配置
const saveBodyDetectionConfig = async () => {
  try {
    // TODO: 调用API保存配置
    await saveProcessConfig({
      position_id: route.params.id,
      process_type: 'body_detection',
      config: bodyDetectionConfig.value
    })
    ElMessage.success('配置保存成功')
    bodyDetectionConfigVisible.value = false
  } catch (error) {
    console.error('保存肢体检测配置失败:', error)
    ElMessage.error('配置保存失败')
  }
}

// 在handleProcessConfig方法中添加肢体检测的处理
const handleProcessConfig = (type: string) => {
  switch (type) {
    // ... existing code ...
    case 'body_detection':
      openBodyDetectionConfig()
      break
    // ... existing code ...
  }
}
/* 树状 */
const documentTreeData = ref([]);
const treeListRef = ref();

const handleTreeClick = (data: any) => {
  console.log(data)
  // 获取点击的节点信息
  const { firstLevel, secondLevel, currentNode } = data;
  
  // 如果点击的是二级节点(标签)
  if (secondLevel) {
    // 根据标签ID搜索题目
    GetQuestionList({
      page: 1,
      limit: 20,
      question_tags: secondLevel.id.replace('tag_', ''), // 移除前缀获取真实ID
      question_form: questionListQuery.question_form
    }).then((res: any) => {
      if (res.data) {
        questionList.value = res.data.items;
        questionListpage.page = res.data.page;
        questionListpage.pageSize = res.data.limit;
        totalQuestions2.value = res.data.total;
      }
    });
  }
  // 如果点击的是一级节点(分类)
  else if (firstLevel) {
    // 根据分类ID搜索题目
    GetQuestionList({
      page: 1,
      limit: 20,
      question_category: firstLevel.id.replace('category_', ''), // 移除前缀获取真实ID
      question_form: questionListQuery.question_form
    }).then((res: any) => {
      if (res.data) {
        questionList.value = res.data.items;
        questionListpage.page = res.data.page;
        questionListpage.pageSize = res.data.limit;
        totalQuestions2.value = res.data.total;
      }
    });
  }
}

const handleUpdateDocument = (data: any) => {
  console.log(data)
}
const handleDeleteDocument = (data: any) => {
  console.log(data)
}

// 获取文档树数据
const getTreeData = () => {
	GetDocumentTree({}).then((ret: any) => {
		console.log('ret', ret);
		const responseData = ret.data;
		GetCategoryList({}).then((res: any) => {
			console.log('res', res);
			const categoryList = res.data.items.filter((item: any) => 
				!['技术能力', '服务意识', '职业素质','基本常识','色盲检测','内容铺垫'].includes(item.name)
			);
			GetTagList({}).then((res: any) => {
				console.log('res', res);
				const tagList = res.data.items;
			
				// 创建根节点
				const rootNode = [ 
					/* {
						id: 'root',
						title: '职位开放题',
						children: responseData.map((item: any) => ({
							...item,
							id: `open_${item.id}`,
							title: item.name || item.title,
							question_type: 'open',
							chinese_explanation: item.chinese_explanation || ''
						}))
					},
					{
						id: 'professional_questions',
						title: '专业考察题库',
						children: responseData.map((item: any) => ({
							...item,
							id: `prof_${item.id}`,
							title: item.name || item.title,
							question_type: 'professional',
							chinese_explanation: item.chinese_explanation || ''
						}))
					}, */
					...categoryList.map((item: any) => ({
						id: `category_${item.id}`,  
						title: item.name,
						children: tagList.filter((tag: any) => tag.category_id === item.id).map((tag: any) => ({
							id: `tag_${tag.id}`,
							title: tag.name,
							chinese_explanation: tag.chinese_explanation || ''
						})) 
					}))
				];
				documentTreeData.value = rootNode;
			});
		});
	});
};

/* 得分题 */
const treeData = ref([]);
const defaultProps = {
  children: 'children',
  label: 'title'
}
const handleNodeClick = async (data: any) => {
  try {
    // 如果点击的是分类节点（没有 tag_ 前缀的 id）
    if (data.id.startsWith('category_')) {
      const categoryId = data.id.replace('category_', '');
      const response = await GetQuestionList({
        page: 1,
        limit: 1000, // 设置较大的限制以获取所有题目
        question_category: categoryId,
        question_form: questionListQuery.question_form
      });

      if (response && response.data) {
        // 更新题目列表显示
        questionList.value = response.data.items;
        questionListpage.page = response.data.page;
        questionListpage.pageSize = response.data.limit;
        totalQuestions2.value = response.data.total;

        // 自动选中所有题目
        const table = document.querySelector('.el-table__header-wrapper');
        if (table) {
          const checkAll = table.querySelector('.el-checkbox');
          if (checkAll) {
            (checkAll as any).__vueParentComponent.emit('change', true);
          }
        }
        
        // 更新选中的题目列表
        selectedQuestions.value = response.data.items;
      }
    } 
    // 如果点击的是标签节点
    else if (data.id.startsWith('tag_')) {
      const tagId = data.id.replace('tag_', '');
      const response = await GetQuestionList({
        page: 1,
        limit: 1000,
        question_tags: tagId,
        question_form: questionListQuery.question_form
      });

      if (response && response.data) {
        // 更新题目列表显示
        questionList.value = response.data.items;
        questionListpage.page = response.data.page;
        questionListpage.pageSize = response.data.limit;
        totalQuestions2.value = response.data.total;

        // 自动选中所有题目
        const table = document.querySelector('.el-table__header-wrapper');
        if (table) {
          const checkAll = table.querySelector('.el-checkbox');
          if (checkAll) {
            (checkAll as any).__vueParentComponent.emit('change', true);
          }
        }
        
        // 更新选中的题目列表
        selectedQuestions.value = response.data.items;
      }
    }
  } catch (error) {
    console.error('获取题目列表失败:', error);
    ElMessage.error('获取题目列表失败');
  }
}

const getDFTreeData = () => {
  GetDocumentTree({}).then((ret: any) => {
		console.log('ret', ret);
		const responseData = ret.data;
		GetCategoryList({}).then((res: any) => {
			console.log('res', res);
			const categoryList = res.data.items.filter((item: any) => 
				!['技术能力', '服务意识', '职业素质','基本常识','色盲检测','内容铺垫','红线题','健康情况','综合素质题'].includes(item.name)
			);
			GetTagList({}).then((res: any) => {
				console.log('res', res);
				const tagList = res.data.items;
			
				// 创建根节点
				const rootNode = [ 
					...categoryList.map((item: any) => ({
						id: `category_${item.id}`,  
						title: item.name,
						children: tagList.filter((tag: any) => tag.category_id === item.id).map((tag: any) => ({
							id: `tag_${tag.id}`,
							title: tag.name,
							chinese_explanation: tag.chinese_explanation || ''
						})) 
					}))
				];
				treeData.value = rootNode;
			});
		});
	});
}
</script>

<style scoped>
@import './index.css';

</style>
<style lang="scss" scoped>
/* 修改 checkbox 选中颜色 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #0419a3 !important; /* 选中背景色 */
  border-color: #0419a3 !important; /* 选中边框色 */
}

/* 修改 checkbox 选中时的勾选标记颜色 */
:deep(.el-checkbox__input.is-checked .el-checkbox__inner::after) {
  border-color: #ffffff !important; /* 勾选标记颜色，通常为白色 */
}

/* 修改 checkbox hover 状态颜色 */
:deep(.el-checkbox__inner:hover) {
  border-color: #0419a3 !important;
}

/* 修改 checkbox focus 状态颜色 */
:deep(.el-checkbox__input.is-focus .el-checkbox__inner) {
  border-color: #0419a3 !important;
}

/* 如果需要修改半选中状态的颜色 */
:deep(.el-checkbox__input.is-indeterminate .el-checkbox__inner) {
  background-color: #0419a3 !important;
  border-color: #0419a3 !important;
}

/* 为特定的 checkbox 组件自定义样式 */
:deep(.custom-checkbox .el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: #548235 !important;
  border-color: #548235 !important;
}

:deep(.custom-checkbox .el-checkbox__inner:hover) {
  border-color: #0419a3 !important;
}

/* 自定义维度标签样式 */
.custom-tag {
  display: inline-block;
  background-color: #409eff;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
  margin-left: 8px;
  font-weight: 500;
  transform: scale(0.8);
  transform-origin: left center;
}

/* 自定义维度项容器样式 */
.custom-dimension-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  padding: 4px 8px;
  border-radius: 4px;
  margin: 2px 0;
  transition: background-color 0.2s;
  
  &:hover {
    background-color: #f5f7fa;
    
    .delete-custom-btn {
      opacity: 1;
    }
  }
  
  .delete-custom-btn {
    opacity: 0;
    transition: opacity 0.2s;
    color: #f56c6c;
    margin-left: 8px;
    padding: 4px;
    
    &:hover {
      background-color: #fef0f0;
      color: #f56c6c;
    }
  }
}
/* 添加题目选择对话框样式 */
.question-select-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.question-select-content {
  .search-bar {
    margin-bottom: 20px;
    
    .search-inputs {
      display: flex;
      align-items: center;
      gap: 10px;
    }
  }

  .question-list {
    margin-top: 20px;
  }

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

/* 添加拖拽相关样式 */
.question-card {
  position: relative;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  margin-bottom: 12px;
  background: #fff;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
}

/* 拖拽状态样式 */
.sortable-ghost {
  opacity: 0.5;
  background: #f5f7fa;
  border: 2px dashed #c0c4cc;
}

// .sortable-chosen {
//   cursor: grabbing;
//   transform: rotate(5deg);
// }

.sortable-drag {
  cursor: grabbing;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  transform: rotate(5deg);
}

  .question-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 12px;

    .question-title {
      display: flex;
      align-items: flex-start;
      gap: 12px;
      flex: 1;


      .title-content {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 20px;

        .question-content {
          flex: 1;
          display: flex;
          align-items: flex-start;
          gap: 10px;
          flex-direction: column;

          .question-number {
            color: #909399;
            font-size: 12px;
          }
        }

        .question-tags {
          margin-top: 20px;
          flex-shrink: 0;
          display: flex;
          flex-wrap: nowrap;
          gap: 8px;
          align-items: center;
          max-width: 300px;
          
          .competency-tag {
            margin: 0;
            border-color: #ed7d31;
            color: #fff;
            background-color: #ed7d31;
            font-size: 12px;
            white-space: nowrap;
            
            &:hover {
              background-color: #ed7d31;
              border-color: #ed7d31;
              color: #fff;
            }
          }
          
          .more-tags-indicator {
            font-size: 12px;
            color: #909399;
            background-color: #f0f2f5;
            padding: 2px 6px;
            border-radius: 3px;
            white-space: nowrap;
            flex-shrink: 0;
            
            &:hover {
              color: #409eff;
              background-color: #ecf5ff;
            }
          }
        }
      }
    }

    .question-actions {
      display: flex;
      gap: 4px;
    }
  }

.question-info {
  .info-item {
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-label {
      color: #909399;
      margin-right: 8px;
    }
  }
}


.field-config-panel {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .panel-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    h3 {
      margin: 0;
      font-size: 18px;
      color: #303133;
      font-weight: 600;
    }
  }

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #303133;
    margin: 24px 0 16px;
    padding-left: 10px;
    border-left: 4px solid #0419a3;
  }

  .field-config-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 12px;
    padding: 12px 16px;
    background: #f5f7fa;
    border-radius: 6px;
    transition: all 0.3s ease;
    
    &:hover {
      background: #eef1f6;
    }
    
    &.sub-field {
      background: #fff;
      border: 1px solid #e4e7ed;
      margin-left: 12px;
      
      &:hover {
        border-color: #0419a3;
      }
    }
    
    .field-label {
      flex: 1;
      font-size: 14px;
      color: #606266;
      display: flex;
      align-items: center;
      gap: 8px;
    }
    
    .required-tag {
      font-size: 12px;
      padding: 0 6px;
      height: 20px;
      line-height: 18px;
    }
    
    :deep(.el-switch.is-checked .el-switch__core) {
      border-color: #0419a3;
      background-color: #0419a3;
    }
  }
}
:deep(.el-switch.is-checked .el-switch__core) {
      border-color: #0419a3;
      background-color: #0419a3;
    }
.el-row {
  margin-bottom: 12px;
}

/* 题目开关样式 */
.question-switches {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-left: auto;
  padding-left: 20px;
  border-left: 1px solid #e4e7ed;
  
  .switch-item {
    display: flex;
    align-items: center;
    gap: 8px;
    
    .switch-label {
      font-size: 14px;
      color: #606266;
      white-space: nowrap;
    }
    
    .el-input-number {
      width: 100px;
    }
  }
}

/* 确保interview-actions布局正确 */
.interview-actions {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
  
  .import-btn, .custom-btn {
    flex-shrink: 0;
  }
  .import-btn,.custom-btn:hover{
    color: #0419a3;
    border-color: #0419a3;
  }
}

/* 面试设置弹窗样式 */
.interview-settings-dialog {
  :deep(.el-dialog__body) {
    padding: 20px;
  }
}

.interview-settings-content {
  .settings-section {
    margin-bottom: 24px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .section-header {
      margin-bottom: 16px;
      
      .section-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        padding-left: 10px;
        border-left: 4px solid #0419a3;
      }
    }
    
    .setting-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
     padding: 0 30px;
     border-radius: 20px;
      border: 1px solid #f0f0f0;
      .setting-label{
        min-width: 150px;
        text-align: justify;
        text-align-last: justify;
        text-justify: inter-character;
      }
      
      &:last-child {
        border-bottom: none;
      }
      
      .setting-info {
        display: flex;
        align-items: center;
        flex: 1;
        // margin-right: 16px;
        
        .setting-name {
          width: 150px;
          font-size: 14px;
          font-weight: 500;
          margin-right: 100px;
          color: #808080;
          display: block;
          margin-bottom: 4px;
          text-align: justify;
          text-align-last: justify;
          text-justify: inter-character;
        }
        
        .setting-desc {
          width: 390px;
          font-size: 12px;
          color: #909399;
          margin: 0;
          line-height: 1.4;
          text-align: justify;
          text-align-last: justify;
          text-justify: inter-character;
        }
      }
      

      
      :deep(.el-switch.is-checked .el-switch__core) {
        border-color: #0419a3;
        background-color: #0419a3;
      }
      
      .switch-desc {
        font-size: 12px;
        color: #909399;
        margin-left: 8px;
      }
      
      .setting-desc-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        gap: 8px;
       /*  flex: 1; */
       width: 80%;
        
        .setting-desc {
          width:390px;
          margin: 0;
        }
        
        .edit-desc-btn {
          padding: 4px;
          min-height: auto;
          
          &:hover {
            color: #0419a3;
          }
        }
      }
      
      .desc-edit-container {
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex: 1;
        
        .desc-edit-actions {
          display: flex;
          gap: 8px;
          margin-left: 15px;
          margin-top: 8px;
          justify-content: flex-end;
        }
      }
    }
  }
}

.avatar-name {
  margin-top: 8px;
  font-size: 14px;
  color: #333;
  width: 100%;
  text-align: center;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.avatar-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 80px; // 设置一个固定宽度
}

.question-form {
  .form-item {
    margin-bottom: 20px;

    .form-label {
      font-size: 14px;
      color: #333;
      margin-bottom: 8px;
      font-weight: 500;

      .required {
        color: #f56c6c;
        margin-left: 4px;
      }
    }

    .form-tip {
      font-size: 12px;
      color: #999;
      margin-top: 4px;
    }

    .competency-config {
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      padding: 12px;

      .config-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;

        &:last-child {
          margin-bottom: 0;
        }

        .config-label {
          flex: 1;
          font-size: 14px;
          color: #666;
          text-align: center;
        }

        .tag-name {
          flex: 1;
          font-size: 14px;
          color: #333;
          text-align: center;
        }

        .el-input-number {
          flex: 1;
          margin: 0 10px;
        }
      }
    }

    .full-width {
      width: 100%;
    }
  }
}

/* 标题和按钮左右布局样式 */
.header-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  h3 {
    margin: 0;
    flex: 1;
  }
  
  .right_btn {
    flex-shrink: 0;
  }
}

/* QuestionBankForm 对话框样式 */
:deep(.question-bank-form-dialog) {
  .el-dialog__header {
    padding: 20px 20px 10px 20px;
    border-bottom: 1px solid #ebeef5;
    
    .el-dialog__title {
      font-size: 18px;
      font-weight: 600;
      color: #303133;
    }
  }
  
  .el-dialog__body {
    padding: 0;
    max-height: 70vh;
    overflow-y: auto;
  }
  
  .el-dialog__footer {
    padding: 10px 20px 20px 20px;
    border-top: 1px solid #ebeef5;
  }
}

/* 权重配置增强样式 */
.competency-config {
  .config-row {
    &:first-child {
      background-color: #f8f9fa;
      border-radius: 4px 4px 0 0;
      font-weight: 600;
      color: #409eff;
    }
    
    /* 平均分配按钮样式 */
    .el-button--text {
      padding: 4px 8px;
      margin-left: auto;
      font-size: 12px;
      
      &:hover {
        background-color: #ecf5ff;
        color: #409eff;
      }
    }
  }
  
  .tag-name {
    font-weight: 500;
    color: #303133;
  }
}

.weight-sum {
  font-weight: bold;
  color: #67c23a;
  margin-left: 8px;
  font-size: 13px;
  
  &.weight-error {
    color: #f56c6c;
    animation: shake 0.5s ease-in-out;
  }
}

/* 输入框优化样式 */
:deep(.el-input-number) {
  .el-input__inner {
    text-align: center;
    font-weight: 500;
  }
  
  &.is-focus .el-input__inner {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

/* 权重错误提示动画 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}

/* 权重配置增强样式 */
.competency-config {
  .config-row {
    &:first-child {
      background-color: #f8f9fa;
      border-radius: 4px 4px 0 0;
      font-weight: 600;
      color: #409eff;
    }
    
    /* 平均分配按钮样式 */
    .el-button--text {
      padding: 4px 8px;
      margin-left: auto;
      font-size: 12px;
      
      &:hover {
        background-color: #ecf5ff;
        color: #409eff;
      }
    }
  }
  
  .tag-name {
    font-weight: 500;
    color: #303133;
  }
}

.weight-sum {
  font-weight: bold;
  color: #67c23a;
  margin-left: 8px;
  font-size: 13px;
  
  &.weight-error {
    color: #f56c6c;
    animation: shake 0.5s ease-in-out;
  }
}

/* 输入框优化样式 */
:deep(.el-input-number) {
  .el-input__inner {
    text-align: center;
    font-weight: 500;
  }
  
  &.is-focus .el-input__inner {
    border-color: #409eff;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}

/* 权重错误提示动画 */
@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-2px); }
  75% { transform: translateX(2px); }
}
</style>
