<template>
    <div class="main_container hide_scrollbar">
        <!-- 问卷头部 -->
        <div class="questionnaire_head">
            <h1 class="head_title">{{ questionaireMsg?.assessmentTitle }}</h1>
            <p class="head_desc">{{ questionaireMsg?.assessmentIllustrate }}</p>
        </div>

        <!-- 整卷填写问卷内容 -->
        <AppQuestionnaireQuestionList 
            :allowEdit="!isCurrentQuestionnaireTaskFinish"
            :questionaireData="questionaireMsg.questionData" 
            @formListAnswerChange="HandleQuestionnaireFormChange"
        />
        <div class="operation">
            <el-button :class="[isCurrentQuestionnaireTaskFinish ? 'is-disabled' :  'button_background']" 
                @click="isCurrentQuestionnaireTaskFinish ? '' : HandleFinishReview()">完成本科目</el-button>
        </div>
    </div>
</template>


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

import AppQuestionnaireQuestionList from '@/components/AppQuestionnaireQuestionList.vue';

import {getEvaluationProcessMsgApi} from '@/api/selfQuestionnaireProcess'
import { getEvaluationQuestionDataApi, saveEvaluationQuestionDataApi } from '@/api/questionnaireCommit'
import { unioformDateTransform } from '@/utils/dateTransform';


const store = useStore()

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


/**
 * 2. 问卷整体数据
 */
// 进入某个问卷（整卷）或者 某个试题（按题） 的时间
const enterTime = ref<any>('')

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

// 问卷是否结束
const isQuestionnaireEnd = computed(()=>{
    let timestamp = new Date(deadlineTime.value).getTime()
    let currentTimestamp = new Date().getTime()
    let sectionTime = timestamp - currentTimestamp
    if(sectionTime > 0){
        return false
    }else{
        return true
    }
})

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

/**
 * 3. 整卷填写相关变量 和操作
 */

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

// 待评价教师列表
const teacherList = ref<TeacherItm[]>([])
// 【整卷填写】 —— 全部数据内容
const teacherQuestionnaireData = ref([])
// 当前选中的待评价科目教师 
const currentActiveTeacherId = ref<number|string>('') 


// 当前选择的教师问卷（整卷填写）  或者 题目问卷（按题填写） 全部信息
const currentSelectedQuestionnaireData = computed(()=>{
    return teacherQuestionnaireData.value.find((item:any)=>{
        return item.evaluationCodeRelationId == currentActiveTeacherId.value
    })
})

// 最终渲染的整体问卷数据
const questionaireMsg = computed(()=>{
    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,
    }
})


watch(()=>questionaireMsg?.value?.deadlineTime,async (newVal)=>{
    deadlineTime.value = newVal
},{deep:true})

// 接收问卷表单填写信息的变更
const HandleQuestionnaireFormChange = (val)=>{
    fullQuestionnaireAnswer.value = val
}
// 问卷整卷提交
const HandleFinishReview = async ()=>{
    console.log('整卷提交的问卷答案--',fullQuestionnaireAnswer.value)

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

    let res = await saveEvaluationQuestionDataApi(params)

    if(res?.code == 200){
        ElMessage({
            message: '问卷评价提交成功',
            type: 'success',
            customClass:'app_el_message',
        })
        // 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 || ''
            enterTime.value = unioformDateTransform(new Date())
            store.commit('updateSubjectQuestionnaireTitle',teacherList.value?.[currentIndex + 1]?.evaluationSubjectName + '-' + teacherList.value?.[currentIndex + 1]?.teacherName + '问卷')
        }else{
            // 重新查询教师状态和问卷状态
            await ReloadPageData()
        }
    }
}


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

//  获取整卷填写问卷数据
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
    }


    
    // 获取第一个 进行中
    const firstActiveIndex =  teacherList.value.findIndex(item => item.evaluationStatus === 1);
    const hasActive = firstActiveIndex !== -1;

    // 获取第一个待评价
    const firstPendingIndex = hasActive 
        ? -1 
        : teacherList.value.findIndex(item => item.evaluationStatus === 0);
    const hasPending = firstPendingIndex != -1

    let finalIndex = hasActive ? firstActiveIndex :
                    (hasPending ? firstPendingIndex : 0)
                    
    // 这个要默认打开最新的 第一个进行中  或第一个待评价 
    currentActiveTeacherId.value = teacherList.value?.[finalIndex]?.id || ''
    enterTime.value = unioformDateTransform(new Date())
    store.commit('updateSubjectQuestionnaireTitle',teacherList.value?.[finalIndex]?.evaluationSubjectName + '-' + teacherList.value?.[finalIndex]?.teacherName + '问卷')
}

// 重新加载页面数据
const ReloadPageData = async ()=>{
    await GetEvaluationProcessMsg()
    await GetFullQuestionnaireData()
}

onMounted(()=>{
    let currentEditTeacherQuestionnaire = sessionStorage.getItem('currentEditTeacherQuestionnaire')
    if(currentEditTeacherQuestionnaire){
        let localQuestionnaire = JSON.parse(currentEditTeacherQuestionnaire || '{}')
        currentActiveTeacherId.value = localQuestionnaire?.id
        enterTime.value = unioformDateTransform(new Date())
        store.commit('updateSubjectQuestionnaireTitle',localQuestionnaire?.subjectName + '-' + localQuestionnaire?.teacherName+ '问卷')
        sessionStorage.removeItem('currentEditTeacherQuestionnaire')
    }
    ReloadPageData()
})

</script>


<style lang="scss" scoped>
.main_container {
    display: flex;
    flex-direction: column;
    background-color: #ffffff !important;
    padding:calc(20 * var(--app-rpx)) !important;

    // 浏览器访问 底部多占  90 * var(--app-rpx) —— 待完善
    padding-bottom: calc((90 + 20) * var(--app-rpx)) !important;
    
    /* --- 头部样式 --- */
    .questionnaire_head {
        text-align: center;
        margin-bottom: calc(20 * var(--app-rpx));
        .head_title {
            font-size: calc(18 * var(--app-rpx));
            line-height: calc(25 * var(--app-rpx));
            font-weight: 600;
            color: #000;
            margin-bottom: calc(8 * var(--app-rpx));
        }
        .head_desc {
            font-size:calc(12 * var(--app-rpx));
            color: #999999;
            line-height:calc(17 * var(--app-rpx));
        }
    }

    .operation{
        flex: 1 1;
        display: flex;
        align-items: flex-end;
        justify-content: center;
        .el-button{
            margin-top: calc(40 * var(--app-rpx));
            width: 100%;
            height: calc(44 * var(--app-rpx));
            font-size: calc(16 * var(--app-rpx));
            font-weight: 600;
            border-radius: calc(4 * var(--app-rpx));
        }
    }
}

</style>