<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">
            {{ 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
            />
            <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.job_type)">
              {{ getStatusText(positionData.job_type) }}
            </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 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 competencyTags"
                :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="handleEditUsage">编辑</el-button>
          </div>
          <div class="usage-content">
            <div class="usage-label">职位用途</div>
            <div class="usage-value">正式招聘</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 }"
            >
              <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>
      </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">
          <!-- 添加在每个步骤上方的加号按钮 -->
          <div class="add-process-btn-top" v-if="index === 0 || true">
           <!--  <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="editAIVideo(step)"
              >
                修改
              </el-button>
            <el-button 
              type="danger" 
              size="small" 
              plain 
             style="margin-top: 10px;margin-left: 0px;"
              @click="deleteProcessStep(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 
          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">考察能力</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">面试题目</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">系统设置</div>
        </div>
      </div>

      <!-- 步骤1：考察能力 -->
      <div v-if="currentStep === 1" class="ai-video-content">
        <div class="ai-video-options">
          <p class="option-tip">下面是奇才智能算法推荐的胜任力考核维度，请结合您的需求增删，确认后点击「下一步」出题</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" 
                :key="item.id" 
                v-model="item.selected"
                @change="(val) => handleCompetencyChange(item, val)"
              >
                <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">
            <h3>备选考核维度</h3>
            <div class="dimension-grid">
              <el-checkbox v-model="aiVideoOptions.xxxx" label="XXXX">
                <div class="ability-label">
                  <span>XXXX</span>
                <!--   <el-tooltip content="考察候选人的XXXX能力" placement="top">
                    <el-icon><QuestionFilled /></el-icon>
                  </el-tooltip> -->
                </div>
              </el-checkbox>
              <!-- 可以添加更多备选维度 -->
            </div>
          </div>

          <!-- 自定义维度 -->
          <div class="custom-dimensions">
            <h3>自定义维度</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" label="继续新增" />
               <!--  <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 type="primary" plain class="import-btn" >
                <el-icon><Document /></el-icon>
                导入题目
              </el-button>
              <el-button type="success" plain class="custom-btn" @click="handleImportQuestion"><!-- @click="handleAddQuestion" -->
                <el-icon><Plus /></el-icon>
                自定义题目
              </el-button>
            </div>
            <div class="interview-duration">
              <span>预计面试时长: </span>
              <span class="duration-value">0秒</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">
            <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" @click="handleAutoGenerate">AI自动组题</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="drag = true"
                @end="drag = false"
              >
                <template #item="{ element }">
                  <div class="question-card">
                    <div class="question-header">
                      <div class="question-title">
                        <span class="question-number">题目{{ chatQuestions.indexOf(element) + 1 }}</span>
                        <span><span style="color: #0017ab;">{{ '「'+element.question_form_name +'」'}}</span>{{ element.title }}</span>
                      </div>
                      <div>
                      <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">
                          <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>
                </template>
              </draggable>
            </div>
              </div>
              
              <div class="multi-dimension-questions">
                <div class="dimension-title">已选胜任力考核维度</div>
                <div class="dimension-list">
                  <div v-for="ability 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">
                      <div class="ability-description">{{ "-" }}</div>
                    </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;">
                
              </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" :alt="avatar.name" />
                      </div>
                      <div class="avatar-name">{{ avatar.name }}</div>
                    </div>
                  </div>
                </div>
                <div>追问风格:  <el-select v-model="settings.interruptionMode" placeholder="请选择">
                    <el-option label="从上一问重新作答" value="previous" />
                    <el-option label="从当前问题作答" value="current" />
                  </el-select></div>
              </div>
              </div>
               
           

            <!-- 面试设置选项 -->
            <div class="interview-settings">
              <div class="setting-item">
                <div class="setting-label">「回答视频保留」</div>
                <el-switch 
                  v-model="settings.keepVideo" 
                  @change="(value) => handleSettingChange('keepVideo', value)"
                />
                <div class="setting-desc">当候选人不符合中断条件时，保留其回答视频</div>
              </div>

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

              <div class="setting-item">
                <div class="setting-label">「智慧追问」</div>
                <el-switch 
                  v-model="settings.smartFollowUp" 
                  @change="(value) => handleSettingChange('smartFollowUp', value)"
                />
                <div class="setting-desc">当候选人给出特殊关键词时，系统将自动追问</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="drawer-footer">
          <el-button v-if="currentStep > 1" @click="prevStep">上一步</el-button>
          <el-button @click="cancelAIVideoConfig">取消</el-button>
          <el-button v-if="currentStep < 3" type="primary" @click="nextStep">下一步</el-button>
          <el-button v-else type="success" @click="finishConfig">新增</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.title"
            placeholder="请输入标题"
            maxlength="15"
            show-word-limit
          />
        </div>

        <div class="form-item">
          <div class="form-label">考察能力</div>
          <el-select
            v-model="questionForm.ability"
            placeholder="请选择考察能力"
            class="full-width"
          >
            <el-option label="深入考察抗压能力" value="pressure" />
            <el-option label="候选人回答中包含一个详细的案例" value="case" />
            <el-option label="获取候选人明确的毕业院校和专业" value="education" />
          </el-select>
        </div>

        <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-input
            v-model="questionForm.target"
            type="textarea"
            rows="3"
            placeholder="输入你想在对话中达成的目标，示例：
• 深入考察抗压能力
• 候选人回答中包含一个详细的案例
• 获取候选人明确的毕业院校和专业"
            maxlength="100"
            show-word-limit
          />
        </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="70%"
      :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-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="totalQuestions"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleQuestionSizeChange"
              @current-change="handleQuestionPageChange"
            />
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelQuestionSelect">取消</el-button>
          <el-button type="primary" @click="confirmQuestionSelect">确定</el-button>
        </span>
      </template>
    </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="field.required ? '必填项不可隐藏' : '切换显示/隐藏'"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      :disabled="field.required"
                      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="field.required ? '必填项不可隐藏' : '切换显示/隐藏'"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      :disabled="field.required"
                      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="field.required ? '必填项不可隐藏' : '切换显示/隐藏'"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      :disabled="field.required"
                      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="field.required ? '必填项不可隐藏' : '切换显示/隐藏'"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      :disabled="field.required"
                      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="field.required ? '必填项不可隐藏' : '切换显示/隐藏'"
                    placement="top"
                  >
                    <el-switch
                      v-model="field.visible"
                      :disabled="field.required"
                      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>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } 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 } from '@element-plus/icons-vue';
import { GetList } from '../../questionBank/classList/api';
import { GetCompetencyList,GetQuestionList,GenerateQuestions,GetDraftList,SaveDraft,GetDigitalList,CreateConfig,GetConfig,UpdateConfig } from './api';
import draggable from 'vuedraggable';
import { updateFieldConfig } from './utils';
import type { ProfileFieldsConfig } from './types';

// 添加 ChatQuestion 接口定义
interface ChatQuestion {
  title: string;
  ability: string;
  content: string;
  target: string;
  weight: number;
  maxAnswers: number;
}

// 添加 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.params.id as string);
const positionStatus = ref(false);
const drag = ref(false); // 添加拖拽状态变量

// 职位数据
const positionData = reactive({
  title: '',
  job_category: '',
  job_type_display: '',
  city: '',
  location: [],
  location_str: '',
  address_detail: '',
  benefits: [],
  requirements: '',
  job_type: 0,
  salary_range: '',
  department: '',
  end_date: '',
  description: '',
  work_experience_required: '',
  education_required: '',
  competency_tags: []
});

// 招聘流程数据 - 修改为普通数组而非 ref 对象
const recruitmentProcess = reactive([
  { id: 1, name: '待核验', description: '待核验', active: true },
  { id: 5, name: '资料收集', description: '资料收集', active: true },
  { id: 2, name: 'AI视频', description: 'AI视频', active: true },
  { id: 3, name: '已通过', description: '已通过', active: true },
  { id: 4, name: '已淘汰', description: '已淘汰', active: false },
  
]);

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

// 定义可选的流程步骤类型
const processStepOptions = [
  { label: 'AI视频', value: 'ai_video' },
  { label: '视频宣讲', value: 'video_presentation' },
  { label: 'AI实时对话', value: 'ai_chat' },
  { label: '资料收集', value: 'data_collection' },
  { label: '简历收集', value: 'resume_collection' },
  /* { label: '代码测试', value: 'code_test' },
  { label: '打字测试', value: 'typing_test' } */
];

// 当前选择的添加位置
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
});


// 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({
  title: '', // 标题
  ability: '', // 考察能力
  content: '', // 面试内容
  target: '', // 对话目标
  weight: 100, // 权重占比，默认100%
  maxAnswers: 1 // 最多回答次数，默认1次
});

// 在 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();
};

// 获取职位详情
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);
      // 设置职位状态
      positionStatus.value = positionData.job_type === 1;
    }
  } catch (error) {
    console.error('获取职位详情失败:', error);
    ElMessage.error('获取职位详情失败');
  }
};

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

// 编辑职位
const handleEdit = () => {
  router.push(`/position/edit/${positionId.value}`);
};

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

// 修改职位状态
const handleStatusChange = async (value: boolean) => {
  const id = route.query.id;
  try {
    const newStatus = value ? 1 : 0;
    await api.UpdateObj({
      id: id,
      job_type: newStatus
    });
    positionData.job_type = newStatus;
    ElMessage.success(`职位已${value ? '开启' : '关闭'}`);
  } catch (error) {
    console.error('修改状态失败:', error);
    ElMessage.error('修改状态失败');
    // 恢复原状态
    positionStatus.value = !value;
  }
};

// 编辑职位用途
const handleEditUsage = () => {
  ElMessage.info('编辑职位用途功能开发中');
};

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

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

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

// 删除流程步骤
const deleteProcessStep = (index: number) => {
  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
  };
  
  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') {
    showAIVideoDialog.value = true;
    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 (recruitmentProcess.length >= 6) {
    ElMessage.warning('最多只能添加6个流程步骤');
    return;
  }
  
  const newStep = {
    id: Date.now(),
    name: label,
    description: label,
    active: true,
    type: type
  };
  
  recruitmentProcess.splice(currentAddIndex.value, 0, newStep);
  showOptionsMenu.value = false;
};

// 下一步
const nextStep = async () => {
  if (currentStep.value < 3) {
    // 如果从第一步进入第二步,更新已选维度到 selectedAbilities
    if (currentStep.value === 1) {
      selectedAbilities.value = selectedDimensions.value.map(dimension => ({
        label: dimension.name,
        value: dimension.name.toLowerCase().replace(/\s+/g, '_'),
        description: dimension.description,
        level: 'CC', // 默认等级
        expanded: false,
        isNew: true
      }));
    }
    // 如果从第二步进入第三步，调用SaveDraft接口保存暂存题目
    if (currentStep.value === 2) {
     try{
        // 调用SaveDraft接口保存暂存题目
        await SaveDraft({
          draft_ids: chatQuestions.value.map((draft: any) => draft.id)
        });
      } 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 () => {
  // 获取选中的面试官信息
  const selectedInterviewerInfo = {
    id: selectedInterviewer.value.id,
    name: selectedInterviewer.value.name,
    avatar_url: selectedInterviewer.value.avatar_url || selectedInterviewer.value.image
  };
  
  // 获取面试设置选项
  const interviewSettings = getInterviewSettings();
  const response = await CreateConfig({
    position_id:route.query.id,
    digital_human_id:selectedInterviewer.value.id,
  })
  console.log(response);
  console.log('保存时选中的面试官:', selectedInterviewerInfo);
  console.log('保存时的面试设置:', interviewSettings);
  
      // 创建新的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 chatQuestions = ref<ChatQuestion[]>([]);

// 添加问题处理方法
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 = {
    title: questionForm.title,
    ability: questionForm.ability,
    content: questionForm.content,
    target: questionForm.target,
    weight: questionForm.weight,
    maxAnswers: questionForm.maxAnswers
  };

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

// 导入问题处理方法
const handleImportQuestion = () => {
  showQuestionSelectDialog.value = true;
  fetchQuestionList(); // 打开对话框时获取题目列表
};

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

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()
});

// 添加代码测试相关的状态和方法
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 = () => {
  editingLocation.value = positionData.location || '';
  isEditingLocation.value = true;
};

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

// 保存工作地点
const saveLocation = async () => {
  try {
    const id = route.query.id;
    await api.UpdateObj({
      id: id,
      location: editingLocation.value.trim()
    });
    
    // 更新本地数据
    positionData.location = editingLocation.value.trim();
    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 competencyTags = ref([]);
const isEditingCompetency = ref(false);
const selectedCompetencies = ref([]);

// 获取能力标签列表
const getCompetencyList = async () => {
  try {
    const response = await GetCompetencyList({page:1,pageSize:1000});
    if (response && response.data) {
      // 为每个标签添加选中状态属性
      competencyTags.value = response.data.items.map((item:any) => ({
        ...item,
        selected: false
      }));
    }
  } catch (error) {
    console.error('获取能力标签列表失败:', error);
    ElMessage.error('获取能力标签列表失败');
  }
};

// 开始编辑能力标签
const startEditCompetency = () => {
  selectedCompetencies.value = positionData.competency_tags?.map((tag:any) => 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 = competencyTags.value.filter(tag => 
      selectedCompetencies.value.includes(tag.id)
    );
    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视频') {
    currentEditingStep.value = step;
    showAIVideoDialog.value = true;
    currentStep.value = 1;
    // 重置选项
    (Object.keys(aiVideoOptions) as Array<keyof typeof aiVideoOptions>).forEach(key => {
      aiVideoOptions[key] = false;
    });
  }
};

// 保存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 = () => {
  // 在这里添加添加新维度的逻辑
  console.log('添加新维度:', customDimension.value, customDescription.value);
  // 重置表单
  customDimension.value = '';
  customDescription.value = '';
  continueAdd.value = false;
};

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

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

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

// 获取面试设置选项的函数
const getInterviewSettings = () => {
  const interviewSettings = {
    // 回答视频保留设置
    keepVideo: settings.keepVideo,
    // 中断后作答限制模式
    interruptionMode: settings.interruptionMode,
    // 智慧追问设置
    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 '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 getCompleteInterviewConfig = () => {
  return {
    // 面试官信息
    interviewer: {
      id: selectedInterviewer.value.id,
      name: selectedInterviewer.value.name,
      avatar_url: selectedInterviewer.value.avatar_url || selectedInterviewer.value.image
    },
    // 面试设置
    settings: getInterviewSettings(),
    // 选中的能力标签
    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
    );
  }
};

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

// 在 script setup 中添加以下内容
// 题目选择相关的响应式变量
const showQuestionSelectDialog = ref(false);
const questionSearchKeyword = ref('');
const questionList = ref([]);
const selectedQuestions = ref([]);
const totalQuestions = ref(0);
const questionListQuery = reactive({
  page: 1,
  pageSize: 10,
  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 = () => {
  if (selectedQuestions.value.length === 0) {
    ElMessage.warning('请至少选择一个题目');
    return;
  }
console.log(selectedQuestions.value);
  // 将选中的题目转换为正确的数据结构后添加到chatQuestions列表中
  const formattedQuestions = selectedQuestions.value.map((question:any) => ({
    id: question.id || Date.now(), // 确保有唯一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,
    weight: 100, // 默认权重
    maxAnswers: 1 // 默认最多回答次数
  }));
  
  chatQuestions.value.push(...formattedQuestions);
  
  // 关闭对话框并重置状态
  showQuestionSelectDialog.value = false;
  selectedQuestions.value = [];
  questionSearchKeyword.value = '';
  
  ElMessage.success(`已添加${selectedQuestions.value.length}个题目`);
};

/* AI自动组题 */
const handleAutoGenerate = async () => {
  console.log('AI自动组题');
  try {
    // 从已选择的能力标签中获取ID列表
    const competencyTagIds = 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: 2, // 开放题数量，默认2个
      choice_questions_count: 2, // 选择题数量，默认2个
      auto_save: true, // 自动保存到数据库
      tenant_id: 1 // 租户ID，这里写死为1，实际应该从系统配置或用户信息中获取
    };

    // 调用生成题目的接口
    const response = await GenerateQuestions(params);
    
    if (response && response.data) {
      // 生成成功后，调用 GetDraftList 获取最新生成的题目
      const draftResponse = await GetDraftList({
        tenant_id: 1,
        position_id: route.query.id as string
      });
console.log(draftResponse);
      if (draftResponse && draftResponse.data) {
        // 将获取到的题目格式化并添加到 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_tags || [],
          question_form_name: question.question_form_name,
          scoring_reference: question.scoring_reference,
          question_form: question.question_form,
          weight: 100,
          maxAnswers: 1
        }));
        
        // 清空现有题目并添加新生成的题目
        chatQuestions.value = formattedQuestions;
        ElMessage.success(`已成功生成${formattedQuestions.length}个面试题目`);
      }
    }
  } catch (error) {
    console.error('AI自动组题失败:', error);
    ElMessage.error('AI自动组题失败，请重试');
  }
};

// 字段配置数据
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 }
    }
  },

  // 专业技能
  skills: { visible: true, label: '专业技能', required: true },
  training: { 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 }
    }
  }
});

// 保存字段配置
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)
      
      // 个人信息配置
      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: false,
      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{
      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.skills,
    training: fieldConfig.training
  };
  return skillFields;
};

</script>

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

</style>
<style lang="scss" scoped>
/* 添加题目选择对话框样式 */
.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);
  }

  .drag-handle {
    position: absolute;
    left: -20px;
    top: 50%;
    transform: translateY(-50%);
    cursor: move;
    color: #909399;
    padding: 4px;
    
    &:hover {
      color: #409EFF;
    }
  }
}

.question-info {
  .info-item {
    margin-bottom: 8px;
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .info-label {
      color: #909399;
      margin-right: 8px;
    }
  }
}
.question-title {
  font-weight: 500;
  display: flex;
    align-items: flex-start;
    gap: 10px;
    flex-direction: column;
  .question-number {
    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;
    }
  }
}

.el-row {
  margin-bottom: 12px;
}
</style>
