<template>
    <div class="main_container">
        <div class="page_item top_header">
            <el-button style="margin-right: 92px;" class="button_default_background" @click="router.go(-1)">
                <el-icon class="img"><ArrowLeftBold /></el-icon>
                返回
            </el-button>
            <!-- 如该任务勾选了所有单科统一模板后，则会出现"整卷填写”和“按题填写”的页面，默认按照整卷填写 -->
            <TabSearch v-if="isUnifyTemplate" tabType="box" 
                :disabled="QuestionnaireModeDisabled"
                :defaultTabKey="defaultQuestionnaireMode" :tabList="[
                {
                    label:'整卷填写',
                    key:'full',
                },
                {
                    label:'按题填写',
                    key:'split',
                }]" 
                @tabChange="HandleQuestionnaireModeChange"
            />

            <div class="info_tip">
                <span class="process_tip">总进度：{{ questionnaireProgress }}</span>
                <span class="time_tip">
                    <img :src="redTimeIcon" alt="">
                    {{ 
                        deadlineCountDown?.abort ? '已结束' : 
                        `剩余时间：${deadlineCountDown?.day}天${deadlineCountDown?.hours}时${deadlineCountDown?.minutes}分` 
                    }}
                </span>
            </div>
        </div>

        <div class="page_jg_20"> </div>

        <div class="center_content">
            <!-- 左侧 教师问卷列表 -->
            <div class="page_item  left_teacher_nav">
                <div class="page_search">
                    <div class="search_content">
                        <div class="content_left">
                            <div class="grade_title" style="color: #000;">授课老师</div>
                        </div>
                    </div>
                </div>

                <ul class="teacher_list">
                    <li v-for="(teacher,index) in teacherList" :key="teacher.id" 
                        :class="['teacher_card',{active:currentActiveTeacherId === teacher.id,},
                                {disabled:defaultQuestionnaireMode == 'split' || !isTeacherEdit(teacher,index)}]" 
                        @click="(defaultQuestionnaireMode == 'split' || !isTeacherEdit(teacher,index)) ? '' : HandleSubjectTeacherChange(index,teacher)">
                        
                        
                        <div class="teacher_tag" :style="{backgroundColor:subjectToColor(teacher.evaluationSubjectName)?.color}">
                            {{ teacher.evaluationSubjectName }}
                        </div>
                        <div class="info_text">
                            <div class="teacher_name">{{ teacher.teacherName }}</div>
                            <div class="status" 
                                :style="{color:fillOutStatusToColor(teacher.evaluationStatus)?.color}"
                            >{{ fillOutStatusToColor(teacher.evaluationStatus)?.label }}</div>
                        </div>
                    </li>
                </ul>
            </div>

            <!-- 中间 问卷内容 -->
             <div  class="center_questionnaire">
                <!-- 问卷头部 -->
                <div class="questionnaire_head">
                    <h1 class="head_title">{{ questionaireMsg?.assessmentTitle }}</h1>
                    <p class="head_desc">{{ questionaireMsg?.assessmentIllustrate }}</p>
                </div>

                <!-- 整卷填写问卷内容 -->
                <template v-if="defaultQuestionnaireMode == 'full'">
                    <QuestionnaireQuestionList 
                        :allowEdit="!isCurrentQuestionnaireTaskFinish"
                        :questionaireData="questionaireMsg.questionData" 
                        v-model:questionListRef="questionListRef" 
                        @formListAnswerChange="HandleQuestionnaireFormChange"/>
                    <div class="operation">
                        <el-button :class="[isCurrentQuestionnaireTaskFinish ? 'is-disabled' :  'button_background']" 
                            @click="isCurrentQuestionnaireTaskFinish ? '' : HandleFinishReview()"
                        >评价完成</el-button>
                    </div>
                </template>


                <!-- 按题填写问卷内容 -->
                 <template v-if="defaultQuestionnaireMode == 'split'" >
                    <!-- 单选 0   评分单选 3-->
                    <SingleSelectQuestionBatchFill
                        v-if="currentEditQuestion?.questionType === 0 || currentEditQuestion?.questionType === 3" 
                        v-model:isFinishEdit="isFinishEdit" 
                        :titleIndex="currentSelectedQuestionIndex" 
                        :titleMsg="currentEditQuestion" 
                        @questionAnswerChange="HandleQuestionAnswerChange"
                        :allowEdit="!isCurrentQuestionnaireTaskFinish"
                        :customTableColumns="questionTableColumns"
                        :defaultTableData="questionTableData"
                    />
                    <!-- 多选 1 -->
                    <BatchSelectQuestionBatchFill 
                        v-if="currentEditQuestion?.questionType === 1"  
                        v-model:isFinishEdit="isFinishEdit" 
                        :titleIndex="currentSelectedQuestionIndex" 
                        :titleMsg="currentEditQuestion" 
                        @questionAnswerChange="HandleQuestionAnswerChange"
                        :allowEdit="!isCurrentQuestionnaireTaskFinish"
                        :customTableColumns="questionTableColumns"
                        :defaultTableData="questionTableData"
                    />

                    <!-- 评分题 5-->
                     <template v-if="currentEditQuestion?.questionType === 5" >
                        <!-- 数字评分  -->
                        <ScoreQuestionBatchFill     
                            v-if="currentEditQuestion?.questionAnswerClass === 0"
                            v-model:isFinishEdit="isFinishEdit" 
                            :titleIndex="currentSelectedQuestionIndex" 
                            :titleMsg="currentEditQuestion"
                            @questionAnswerChange="HandleQuestionAnswerChange"
                            :allowEdit="!isCurrentQuestionnaireTaskFinish"
                            :defaultTableData="questionTableData"
                        />

                        <!-- 星星评分 -->
                        <StarRationQuestionBatchFill 
                            v-if="currentEditQuestion?.questionAnswerClass === 1"
                            v-model:isFinishEdit="isFinishEdit" 
                            :titleIndex="currentSelectedQuestionIndex" 
                            :titleMsg="currentEditQuestion"
                            :allowEdit="!isCurrentQuestionnaireTaskFinish"
                            @questionAnswerChange="HandleQuestionAnswerChange"
                            :defaultTableData="questionTableData"
                        />
                     </template>

                     <!-- 问答题  2-->
                    <QuestionAndAnswerBatchFill
                        v-if="currentEditQuestion?.questionType === 2"
                        v-model:isFinishEdit="isFinishEdit" 
                        :titleIndex="currentSelectedQuestionIndex" 
                        :titleMsg="currentEditQuestion"
                        :allowEdit="!isCurrentQuestionnaireTaskFinish"
                        @questionAnswerChange="HandleQuestionAnswerChange"
                        :defaultTableData="questionTableData"
                    />
                    <div class="operation">
                        <el-button :class="[!isCurrentQuestionnaireTaskFinish && isFinishEdit ? 'button_background' : 'is-disabled']"  
                            @click="!isCurrentQuestionnaireTaskFinish && isFinishEdit ? HandleFinishCurrentQuestion() : ''">
                            {{(currentSelectedQuestionIndex + 1) < questionnaireSplitData?.length ? '下一题' : '提交'}}
                        </el-button>
                    </div>
                </template>
             </div>
           
            <!-- 右侧 问卷题目列表  -->
            <div class="page_item right_title_nav">
                <div class="page_search">
                    <div class="search_content">
                        <div class="content_left">
                            <div class="grade_title">问卷目录</div>
                        </div>
                    </div>
                </div>
                <ul v-if="questionaireMsg?.questionData?.length > 0" class="question_list_brief">
                    <li  v-for="(question,index) in questionaireMsg.questionData" :key="question.id">
                        <span @click="defaultQuestionnaireMode=='full' ? 
                                        ScrollToItem(question.id) : 
                                        (!isQuestionTitleEdit(question,index) ? '' :  HandleChangeQuestion(index,question)) " 
                            :title="question.questionTitleName" 
                            class="one_line_ellipsis" 
                            :class="[{active:defaultQuestionnaireMode=='split' && currentSelectedQuestionIndex == index,
                                    disabled:defaultQuestionnaireMode=='split' && !isQuestionTitleEdit(question,index)}]">
                            {{ index + 1 }}.{{ question.questionTitleName }}
                        </span>
                        <img v-if="IsSplitQuestionnaireFinish(question.studentAnswerStatus)" :src="finishIcon" alt="">
                    </li>
                </ul>
            </div>
        </div>
    </div>

</template>


<script setup lang="ts">
import { ref,onMounted, reactive, computed,watch, nextTick } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

import TabSearch from '@/baseComponents/TabSearch.vue';
import QuestionnaireQuestionList from '@/components/QuestionnaireQuestionList.vue';

import SingleSelectQuestionBatchFill from '@/components/singleSelectQuestionBatchFill/SingleSelectQuestionBatchFill.vue';
import ScoreQuestionBatchFill from '@/components/scoreQuestionBatchFill/ScoreQuestionBatchFill.vue';
import StarRationQuestionBatchFill from '@/components/starRationQuestionBatchFill/StarRationQuestionBatchFill.vue';
import QuestionAndAnswerBatchFill from '@/components/questionAndAnswerBatchFill/QuestionAndAnswerBatchFill.vue';
import BatchSelectQuestionBatchFill from '@/components/batchSelectQuestionBatchFill/BatchSelectQuestionBatchFill.vue';

import { subjectToColor,fillOutStatusToColor,
        IsSplitQuestionnaireFinish
    } from '@/components/commonDictConvert';
import { useTimeCountDown } from '@/utils/dateTransform';
import {getExcelColumn} from '@/utils/numberConvertExcelColumn'

import { getEvaluationQuestionDataApi, getEvaluationQuestionDataSplitApi, 
        saveEvaluationQuestionDataApi, saveEvaluationQuestionDataSplitApi 
    } from '@/api/questionnaireCommit'
import {getEvaluationProcessMsgApi} from '@/api/selfQuestionnaireProcess'

import redTimeIcon from '@/assets/icon/red_time_icon.svg'
import finishIcon from '@/assets/studentQuestionnaire/select_icon.png'


interface TeacherItm {
    id: string|number
    evaluationClassName: string     //班级
    evaluationStatus: number   //评价状态  0-待评价  1-进行中  2-已评价
    subjectType: number      // 科目类型 0-班主任  1 科目（单科）
    teacherName: string      //教师名称
    evaluationSubjectName:string  //科目名称
}

const router = useRouter()

// 是否 所有单科统一模板
const isUnifyTemplate = computed(()=>{
    // 统一模板状态，0-否(未勾选),1-是(已勾选)
    let unifyTemplateStatus = JSON.parse(localStorage.getItem('userInfo') || '{}')?.evaluationBO?.unifyTemplateStatus
    return unifyTemplateStatus ? true : false
})

// 倒计时相关参数
const { 
        DestoryInterval,
        deadlineCountDown,
        StartCounDown
    } =  useTimeCountDown()


/**
 * 1. 左侧教师相关变量
 */
// 待评价教师列表
const teacherList = ref<TeacherItm[]>([])

// evaluationStatus  0-待评价  1-进行中  2-已评价
// 问卷教师是否可以切换
const isTeacherEdit = computed(() => {
    // 除了已评价（2）状态可编辑外，
        // 如果有进行中状态，第一个进行中（1）状态可编辑
        // 没有进行中状态，第一个待评价（0）状态可编辑；
    const list = teacherList.value;
    
    // 获取第一个 进行中
    const firstActiveIndex = list.findIndex(item => item.evaluationStatus === 1);
    const hasActive = firstActiveIndex !== -1;
    
    // 如果没有进行中的，才去寻找第一个待评价的
    const firstPendingIndex = hasActive 
        ? -1 
        : list.findIndex(item => item.evaluationStatus === 0);

    // 2. 返回一个函数，供 v-for 循环调用
    return (teacher, index) => {
        // 已评价(2) 始终可编辑
        if (teacher.evaluationStatus === 2) return true;

        // 进行中(1)：判断当前索引是否等于缓存的第一个进行中索引
        if (teacher.evaluationStatus === 1) {
            return index === firstActiveIndex;
        }

        // 待评价(0)：判断当前索引是否等于缓存的第一个待评价索引
        if (teacher.evaluationStatus === 0) {
            return index === firstPendingIndex;
        }

        // 兜底：其他未知状态不可编辑
        return false;
    };
});

// 问卷标题是否可以切换
const isQuestionTitleEdit = computed(()=>{
    const list =  questionaireMsg.value?.questionData || []
    // 获取第一个 未答完的题
    const firstUnfinishIndex = list.findIndex(item => item.studentAnswerStatus === 0);

    return (question, index) => {
        // 已答题(1) 始终可编辑
        if (question.studentAnswerStatus === 1) return true;

        // 未答题(0)：判断当前索引是否等于缓存的第一个未答题索引
        if (question.studentAnswerStatus === 0) {
            return index === firstUnfinishIndex;
        }
        // 兜底：其他未知状态不可编辑
        return false;
    };
})
/**
 * 2. 问卷整体数据
 */

//  当前问卷任务是否全部完成 ———— 以及问卷是否结束
const isCurrentQuestionnaireTaskFinish = computed(()=>{
    // 判断教师列表是否全部完成
    return !(teacherList.value.find(teacher=>{
        return (teacher.evaluationStatus === 0 || teacher.evaluationStatus === 1)
    }))
}) 

// 问卷填写截止时间
const deadlineTime = ref('')


// 每个问卷的进度
const questionnaireProgress= computed(()=>{
    if(defaultQuestionnaireMode.value == 'full'){
        return questionaireMsg.value?.progress
    }else if(defaultQuestionnaireMode.value == 'split'){
        let totalQuestion = questionaireMsg.value?.questionData || []
        let finishLength = 0
        totalQuestion.map(item=>{
            if(IsSplitQuestionnaireFinish(item.studentAnswerStatus)){
                finishLength += 1
            }
        })
        if(totalQuestion?.length > 0){
            return Math.floor((finishLength / totalQuestion.length) * 100) + '%'
        }else{
            return '0%'
        }
    }
})


// 【按题填写】时候的全部数据内容
const questionnaireSplitData = ref<any[]>([])
// 按题填写时候的题目列表
const questionnaireSplitTitleList = computed(()=>{
    return questionnaireSplitData.value?.map((item:any)=>{
        return {
            id:item.questionId,
            studentAnswerStatus:item.studentAnswerStatus,
            questionTitleName:item.questionTitleName,
        }
    })
})

// 【整卷填写】 —— 全部数据内容
const teacherQuestionnaireData = ref([])

// 当前选择的教师问卷（整卷填写）  或者 题目问卷（按题填写） 全部信息
const currentSelectedQuestionnaireData = computed(()=>{
    // 整卷填写
    if(defaultQuestionnaireMode.value == 'full'){
        return teacherQuestionnaireData.value.find((item:any)=>{
            return item.evaluationCodeRelationId == currentActiveTeacherId.value
        })
    // 按题填写
    }else if(defaultQuestionnaireMode.value == 'split'){
        return questionnaireSplitData.value?.[currentSelectedQuestionIndex.value]
    }
})
// 最终渲染的整体问卷数据
const questionaireMsg = computed(()=>{
     if(defaultQuestionnaireMode.value == 'full'){
        let addedQuestionList = currentSelectedQuestionnaireData.value?.questionData?.map(item=>{
            let options = item.answerData.map(opt=>{
                return{
                    questionSortCode:String(opt.questionSortCode),  //选项的序号 
                    answerCode: opt.answerCode,
                    content: opt.answerName,
                    score: opt.answerScore,
                    id: opt.answerId
                }
            })
            let extraConfig = []
            if(Number(item.questionAnswerType) === 1){
                extraConfig.push('required')
            }
            if(Number(item.questionSortRole) === 1){
                extraConfig.push('isHorizontal')
            }

            // 初始化默认值
            let defaultAnswer = undefined
            // 单选  | 评分单选
            if(item.questionType === 0 || item.questionType === 3){
                item.answerData.map(opt=>{
                    if(opt.answerCode){
                        defaultAnswer = opt.answerCode
                    }
                })
            // 多选  
            }else if(item.questionType === 1){
                defaultAnswer = []
                item.answerData.map(opt=>{
                    if(opt.answerCode){
                        defaultAnswer.push(opt.answerCode)
                    }
                })
            //问答  
            }else if(item.questionType === 2){
                defaultAnswer = item.studentAnswer
            //评分
            } else if(item.questionType === 5){
                defaultAnswer = item.studentAnswerScore
            }

            console.log('defaultAnswer',defaultAnswer)  

            return {
                ...item,
                id:item.questionId,
                extraConfig,    // 是否必答 required, 是否横排 isHorizontal
                options,

                answer:defaultAnswer,  //获取默认answer
            }
        })

        console.log('默认初始赋值——————addedQuestionList',addedQuestionList)
        return{
            assessmentTitle:currentSelectedQuestionnaireData.value?.assessmentName,  //问卷标题
            assessmentIllustrate:currentSelectedQuestionnaireData.value?.assessmentIllustrate,  //问卷简介
            // 问卷试题列表
            questionData:addedQuestionList,
            progress:currentSelectedQuestionnaireData.value?.progress,
            deadlineTime:currentSelectedQuestionnaireData.value?.endDateTime,
        }

     }else if(defaultQuestionnaireMode.value == 'split'){
        return{
            assessmentTitle:currentSelectedQuestionnaireData.value?.assessmentName,  //问卷标题
            assessmentIllustrate:currentSelectedQuestionnaireData.value?.assessmentIllustrate,  //问卷简介
            // 问卷试题列表
            questionData:questionnaireSplitTitleList.value,
            // progress:currentSelectedQuestionnaireData.value?.progress,
            deadlineTime:currentSelectedQuestionnaireData.value?.endDateTime,
        }
     }
})


//  历史选择的问卷填写方式  
// //无 '' ,  full 整卷填写 , split  按题填写
const HistoryQuestionnaireFillMode = ref('')

// 默认的问卷填写模式
const defaultQuestionnaireMode = ref('full')  //  split  full
// 问卷填写模式是否允许修改
const QuestionnaireModeDisabled = ref(false)

// 问卷填写模式变更
const HandleQuestionnaireModeChange = async (val)=>{
    console.log('当前选中的值',val)
    defaultQuestionnaireMode.value = val
    if(val == 'split'){
        await GetSplitQuestionnaireData()
    }else if(val == 'full'){
        await GetFullQuestionnaireData()
    }
}

// 监听从接口获取到的 历史问卷填写方式，变更当前页面的模式和模式的禁选状态
watch(()=>HistoryQuestionnaireFillMode.value,(newVal)=>{
    if(newVal){
        defaultQuestionnaireMode.value = newVal
        QuestionnaireModeDisabled.value = true
    }
})

//  获取整卷填写问卷数据
const GetFullQuestionnaireData = async ()=>{
    let teacherIds = teacherList.value.map(item=>{
        return item.id
    })
    let res = await getEvaluationQuestionDataApi(teacherIds)
    if(res?.code == 200){
        teacherQuestionnaireData.value = res?.data
    }

    // 如果当前没有选中的教师问卷，则默认选中第一个教师问卷
    if(currentActiveTeacherId.value){
        return
    }
    currentActiveTeacherId.value = teacherList.value?.[0]?.id || ''
}

// 获取按题填写问卷数据
const GetSplitQuestionnaireData = async ()=>{
    let teacherIds = teacherList.value.map(item=>{
        return item.id
    })
    let res = await getEvaluationQuestionDataSplitApi(teacherIds)
    if(res?.code == 200){
        questionnaireSplitData.value = res.data
    }
}


/**
 * 3. 整卷填写相关变量 和操作
 */
// 问卷试题 dom
const questionListRef = ref()
// 当前选中的待评价科目教师 
const currentActiveTeacherId = ref<number|string>('') 

// 整卷填写 教师问卷的答案
const fullQuestionnaireAnswer = ref({})

// 切换 评价的科目教师
const HandleSubjectTeacherChange = (index,teacher)=>{
    currentActiveTeacherId.value = teacher.id

    currentSelectedQuestionIndex.value = 0
}

// 问卷试题定位—— 滚动定位到试题中的某一题
const ScrollToItem = (id)=>{
    const targetElement = questionListRef.value.querySelector(`[id="${id}"]`);
    if (targetElement) {
        // 平滑滚动到目标元素，并使其居中显示
        targetElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
    }
}
// 接收问卷表单填写信息的变更
const HandleQuestionnaireFormChange = (val)=>{
    fullQuestionnaireAnswer.value = val
}
// 问卷整卷提交
const HandleFinishReview = async ()=>{
    console.log('整卷提交的问卷答案--',fullQuestionnaireAnswer.value)

    let params = {
        evaluationCodeRelationId: currentSelectedQuestionnaireData.value.evaluationCodeRelationId,
        assessmentId: currentSelectedQuestionnaireData.value.assessmentId,
        answerData: Object.values(fullQuestionnaireAnswer.value)
    }

    let res = await saveEvaluationQuestionDataApi(params)

    if(res?.code == 200){
        ElMessage.success('问卷评价提交成功')
        // true  表示当前问卷全部填写完成，跳到下一个问卷（ false 没有完成的留在当前问卷页）
        if(res.data){
            fullQuestionnaireAnswer.value = {}
            // 重新查询教师状态和问卷状态
            await ReloadPageData()
            // 重查和索引切换顺序不能颠倒
            // 找到当前选中的教师
            let currentIndex = teacherList.value.findIndex(item=>{
                return item.id == currentActiveTeacherId.value
            })
            // 如果不是最后一卷，跳转到下一卷
            if((currentIndex + 1) >= teacherList.value.length ){
                return
            }
            // 跳转到下一个教师的问卷
            currentActiveTeacherId.value = teacherList.value?.[currentIndex + 1]?.id || ''
        }else{
            // 重新查询教师状态和问卷状态
            await ReloadPageData()
        }
    }
}


/**
 *  4. 按题填写相关变量 和操作
 */
const isFinishEdit = ref(false)  // 当前试题是否已经编辑完成
const currentSelectedQuestionIndex = ref(0)  // 当前选中的题目索引

// 当前问卷题目的 教师评价答案列表
const singleQuestionAnswer = ref([])

// 当前编辑的试题
const currentEditQuestion = computed(()=>{
    let currentQuestion = questionnaireSplitData.value?.[currentSelectedQuestionIndex.value]
    let extraConfig = []
    if(Number(currentQuestion?.questionAnswerType) === 1){
        extraConfig.push('required')
    }
    if(Number(currentQuestion?.questionSortRole) === 1){
        extraConfig.push('isHorizontal')
    }
    return {...currentQuestion,extraConfig}
})


// 按题填写的表格数据渲染 _ 不同题目类型渲染不同的内容
const questionTableColumns = ref<any[]>([])  //按题填写的表列数据
const questionTableData = ref<any[]>([])   //按题填写的表行数据


// 监听【按题填写】时候的 表格数据渲染 
watch(()=>currentEditQuestion.value?.questionType,(newVal)=>{
    console.log('teacherList',teacherList.value)
    console.log('questionaireMsg',questionaireMsg.value)
    switch(newVal){
        case 0:
        case 3:
        {    //单选
            let initRowKeys = {}  //初始化的行数据

            let singleScoreObj = {}
            // 表列（头）获取
            questionTableColumns.value =  currentEditQuestion.value?.answerData?.map((item,index)=>{
                initRowKeys['sort_'+item.questionSortCode] = false
                singleScoreObj[item.questionSortCode] = item.answerScore
                return {
                    name:'sort_'+item.questionSortCode,
                    label:`${getExcelColumn(item.questionSortCode - 1)}. `+item.answerName,
                    width:'200',
                    fixed:'',
                    align:'left',
                    minWdth:'',
                    custom:true,
                }
            }) || []
            // 表行数据获取
            questionTableData.value =   currentEditQuestion.value?.studentAnswerData?.map((stuAnswer)=>{
                let rowKeys = {
                    ...initRowKeys,
                    evaluationCodeRelationId: stuAnswer.evaluationCodeRelationId,
                    "answerCode": "",
                    "studentAnswer": "",
                    studentQuestionScore: currentEditQuestion.value?.questionScore,
                    "studentAnswerScore": '',
                    // 评分单选时候，每个选项对应的分值 obj
                    "answerScoreObj": singleScoreObj
                }

                let answers = []
                if(stuAnswer.answerCode){
                    answers = stuAnswer.answerCode?.split('|') || []
                }
                // 回显已经填写完的信息
                answers.map((ans)=>{
                    rowKeys['sort_'+ans] = true
                })

                return {
                    teacher:stuAnswer.teacherName,
                    ...rowKeys
                }
            })
            break
        }    
        case 1:{    //多选
            let initRowKeys = {}  //初始化的行数据
            questionTableColumns.value =  currentEditQuestion.value?.answerData?.map((item,index)=>{
                initRowKeys['sort_'+item.questionSortCode] = false
                return {
                    name:'sort_'+item.questionSortCode,
                    label:`${getExcelColumn(item.questionSortCode - 1)}. `+item.answerName,
                    width:'200',
                    fixed:'',
                    align:'left',
                    minWdth:'',
                    custom:true,
                }
            }) || []
            // 表行数据获取
            questionTableData.value =   currentEditQuestion.value?.studentAnswerData?.map((stuAnswer)=>{
                let rowKeys = {
                    ...initRowKeys,
                    evaluationCodeRelationId: stuAnswer.evaluationCodeRelationId,
                    "answerCode": "",
                    "studentAnswer": "",
                    studentQuestionScore: '',
                    "studentAnswerScore": '',
                    "answerScore": ''
                }

                let answers = []
                if(stuAnswer.answerCode){
                    answers = stuAnswer.answerCode?.split('|') || []
                }
                // 回显已经填写完的信息
                answers.map((ans)=>{
                    rowKeys['sort_'+ans] = true
                })
                return {
                    teacher:stuAnswer.teacherName,
                    ...rowKeys
                }
            })
            break
        }    
        case 5:{
            //评分题
            questionTableData.value =   currentEditQuestion.value?.studentAnswerData?.map((stuAnswer)=>{
                let answers = stuAnswer.studentAnswerScore
                // 回显已经填写完的信息
                return {
                    teacher:stuAnswer.teacherName,
                    score:answers,
                    fullScore:currentEditQuestion.value?.questionScore,

                    evaluationCodeRelationId: stuAnswer.evaluationCodeRelationId,
                }
            })
            break
        }    
        case 2:{   //问答题 
            // 表行数据获取
            questionTableData.value =   currentEditQuestion.value?.studentAnswerData?.map((stuAnswer)=>{
                let answers = stuAnswer.studentAnswer
                // 回显已经填写完的信息
                return {
                    teacher:stuAnswer.teacherName,
                    content:answers,

                    evaluationCodeRelationId: stuAnswer.evaluationCodeRelationId,
                }
            })
            break
        }   
    }
},{immediate:true})


// 切换当前选中的试题索引
const HandleChangeQuestion = (index,question)=>{
    console.log('当前索引--',index)
    isFinishEdit.value = false
    currentSelectedQuestionIndex.value = index

}
// 接收问卷试题答案的变更
const HandleQuestionAnswerChange = (val)=>{
    singleQuestionAnswer.value = val
}
// 当前题目 有关所有教师的评价数据提交
const HandleFinishCurrentQuestion = async ()=>{
    console.log('当前题目的教师评价数据--',singleQuestionAnswer.value )
    let finalAnswerData:any[] = []
    
    switch(currentEditQuestion.value?.questionType){
        // 单选
        case 0:
        // 多选
        case 1:{
            finalAnswerData = singleQuestionAnswer.value.map(item=>{
                let keys = Object.keys(item).filter(key=>{
                    return key.includes('sort_') && item[key] === true
                })
                let answerCode =  keys.map(ans=>{
                    return ans.split('_')[1]
                }).join('|')
                return {
                    evaluationCodeRelationId: item.evaluationCodeRelationId,
                    answerCode: answerCode,
                    studentAnswer: '',
                    studentQuestionScore: '',
                    studentAnswerScore: '',
                    answerScore: ''
                }
            })
            break
        }   
        case 3:{    //评分单选
            finalAnswerData = singleQuestionAnswer.value.map(item=>{
                let keys = Object.keys(item).find(key=>{
                    return key.includes('sort_') && item[key] === true
                })
                let answerCode =  keys?.split('_')[1]
                return {
                    evaluationCodeRelationId: item.evaluationCodeRelationId,
                    answerCode: answerCode,
                    studentAnswer: '',
                    studentQuestionScore: '',
                    studentAnswerScore: '',
                    answerScore: item.answerScoreObj?.[answerCode]
                }
            })
            break
        }    
        case 5:{   //评分题
            finalAnswerData = singleQuestionAnswer.value.map(item=>{
                return {
                    evaluationCodeRelationId: item.evaluationCodeRelationId,
                    answerCode: '',
                    studentAnswer: '',
                    studentQuestionScore: item.fullScore,
                    studentAnswerScore: item.score,
                    answerScore: ''
                }
            })
            break
        }    
        case 2:{   //问答题 
            finalAnswerData = singleQuestionAnswer.value.map(item=>{
                return {
                    evaluationCodeRelationId: item.evaluationCodeRelationId,
                    answerCode: '',
                    studentAnswer: item.content,
                    studentQuestionScore: '',
                    studentAnswerScore: '',
                    answerScore: ''
                }
            })
            break
        }   
    }

    let params = {
        questionId: currentSelectedQuestionnaireData.value.questionId,
        lastQuestion: currentSelectedQuestionIndex.value + 1 >= questionnaireSplitData.value?.length ? true : false,
        answerData:finalAnswerData
    }

    let res =  await saveEvaluationQuestionDataSplitApi(params)
    if(res?.code == 200){
        ElMessage.success('问卷评价提交成功')
        // 不是最后一卷 ，要跳转到下一卷
        if((currentSelectedQuestionIndex.value + 1) < questionaireMsg.value.questionData?.length){
            singleQuestionAnswer.value = []
            isFinishEdit.value = false
            questionTableData.value = []
            questionTableColumns.value = []
            // 重新查询 问卷内容和页面内容
            await ReloadPageData()
            currentSelectedQuestionIndex.value += 1
        }else{
            // 重新查询 问卷内容和页面内容
            await ReloadPageData()
        }
    }
}

// 
// 处理页面的倒计时
const HandleTimeDeadline = ()=>{
    DestoryInterval()
    // 获取到剩余时间后，开始执行倒计时
    StartCounDown(deadlineTime.value,1000)
}

// 获取评价教师列表
const GetEvaluationProcessMsg = async ()=>{
    let res = await getEvaluationProcessMsgApi()
    if(res?.code == 200){
        teacherList.value = res.data.dataList
    }
}

// 重新加载页面数据
const ReloadPageData = async ()=>{
    await GetEvaluationProcessMsg()
    if(defaultQuestionnaireMode.value == 'full'){
        await GetFullQuestionnaireData()
    }else if(defaultQuestionnaireMode.value == 'split'){
        await GetSplitQuestionnaireData()
    }
}

watch(()=>questionaireMsg?.value?.deadlineTime,async (newVal)=>{
    deadlineTime.value = newVal
    await nextTick()
    HandleTimeDeadline()
})

onMounted( async ()=>{
    await ReloadPageData()
})

</script>


<style lang="scss" scoped>
.main_container{
    > *{
        flex-shrink: 0;
    }
}

.top_header{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding:10px 20px;
    .info_tip{
        margin-right: 240px;
        margin-left: 10px;
        flex: 1 1;
        display: flex;
        justify-content: flex-end;
        gap:40px;
        align-items: center;

        font-size: 14px;
        line-height: 24px;
        .process_tip{
            color: #2E64FA;
        }
        .time_tip{
            display: flex;
            align-items: center;
            gap:4px;
            color:#f56C6c; 
        }
    }
    :deep(.button_default_background){
        padding:8px 10px;
        >span{
            gap:4px;
        }
    }
}

.center_content{
    display: flex;
    gap:20px;
    align-items: flex-start;

    height: calc(100% - 56px - 20px);
    overflow: auto;

    .left_teacher_nav{
        width: 160px;
        max-height: 100%;
        overflow: auto;

        .teacher_list{
            display: flex;
            flex-direction: column;
            gap:16px;
            margin-top: 16px;

            .teacher_card{
                display: flex;
                gap:8px;
                cursor: pointer;

                &.disabled{
                    cursor:not-allowed
                }

                &.active{
                    .status,
                    .teacher_name{
                        color:#2E64FA !important;
                    }
                    .teacher_name{
                        font-weight: 600;
                    }
                }

                .teacher_tag{
                    display: flex;
                    justify-content: center;
                    align-items: center;

                    width: 44px;
                    height: 44px;
                    border-radius: 4px 4px 4px 4px;
                    font-weight: 600;
                    font-size: 12px;
                    color: #FFFFFF;
                }

                .info_text{
                    display: flex;
                    flex-direction: column;
                    justify-content: space-between;
                    .teacher_name{
                        font-size: 14px;
                        color: #333333;
                    }
                    .status{
                        font-size: 12px;
                    }
                }
            }
        }
    }

    .right_title_nav{
        width: 240px;
        max-height: 100%;
        overflow: auto;
        padding:20px 10px;

        .question_list_brief{
            display: flex;
            flex-direction: column;
            font-size: 14px;
            li{
                display: flex;
                align-items: center;
                justify-content: space-between;
                gap:8px;
                padding:10px 0;
                cursor: pointer;

                .disabled{
                    cursor: not-allowed;
                }
                .active{
                    color: #2E64FA;
                }
                img{
                    width:16px;
                    height:16px;
                }
            }
        }
    }

    .center_questionnaire {
        flex: 1 1;
        display: flex;
        flex-direction: column;

        border-radius: 10px;
        background-color: white;
        overflow: auto;
        height: 100%;
        padding:20px 0 116px 0;
           

        /* --- 头部样式 --- */
        .questionnaire_head {
            text-align: center;
            margin-bottom: 30px;

            .head_title {
                font-size: 24px;
                line-height: 34px;
                font-weight: bold;
                color: #000;
                margin-bottom: 10px;
            }

            .head_desc {
                font-size: 14px;
                color: #999999;
                line-height: 1.6;
                margin: 0;
                padding:0 60px;
            }
        }

        .operation{
            flex: 1 1;
            display: flex;
            align-items: flex-end;
            justify-content: center;

            .el-button{
                margin-top: 60px;
                width: 160px;
                height: 48px;
            }
        }
    }
}

</style>