<template>
    <div class="page_item end_item template_component">
        <div class="page_search">
            <div class="search_content">
            <div class="content_left">
                <el-checkbox
                    v-if="!(store.state.evaluationManageStepData.isHeadTeacherInvolved)"
                    v-model="isUnifiedTemplate" >所有单科统一模版</el-checkbox>
            </div>
            <div class="content_right">
                <el-button  class="button_background" @click="FinishQuestionnaireTemplateConfig">完成</el-button>
            </div>
            </div>
        </div>
        <div class="page_jg_20"></div>
        <Table :tableColumns="tableColumns" class="table_content"
            :tableData="tableData"
            :hidePagination="true">
            <template #gender="{row}">
                <el-select v-model="row.gender">
                    <el-option
                        v-for="opt in gradeOptionList"
                        :key="opt.value"
                        :label="opt.label"
                        :value="opt.value"
                    />
                </el-select>
            </template>
            <template #assessmentId="{row}">
                <div class="questionnaire_cell table_row_option">
                    <el-select 
                        v-model="row.assessmentId"
                        filterable
                        @change="(val)=>HandleQuestionnaireTemplateChange(row,val)">
                        <el-option
                            v-for="opt in quesitonnaireOptionList"
                            :key="opt.value"
                            :label="opt.label"
                            :value="opt.value"
                        />
                    </el-select>
                    <span v-if="row.assessmentId" class="el_button_editor" @click="GoToPreviewQuestionnaire(row.assessmentId)">预览</span>
                    <span v-else class="el_button_editor"></span>
                </div>
            </template>
        </Table>
    
    </div>
</template>



<script setup lang="ts">
import { onMounted, ref, watch } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import { useStore } from 'vuex';


import Table from '@/baseComponents/Table.vue';
import {tableColumns} from './table'

import { getQuestionnaireTemplateListApi,saveQuestionnaireTemplateListApi} from '@/api/questionnaireTemplateComponent'
import {getAllQuestionnaireListApi} from   '@/api/surveyManagement'

const route = useRoute()
const router = useRouter()
const store = useStore()


// 默认值 和 班主任是否勾选  以及  是否手动触发有关
const isUnifiedTemplate = ref(true)  //所有单科统一模版

//  1. 下拉选项 
// 年级下拉
const gradeOptionList = ref([
    {
        label:'全部',
        value:2
    },
    {
        label:'男',
        value:0
    },
    {
        label:'女',
        value:1
    },
])

// 问卷下拉
const quesitonnaireOptionList = ref([])
// 获取问卷列表
const GetQuestionnaireList = async ()=>{
   let res = await getAllQuestionnaireListApi()
   if(res?.code == 200){
    quesitonnaireOptionList.value = res?.data?.map(item=>{
        return {
            label:item.assessmentTitle,
            fullScore:item.fullScore,  //问卷满分
            questionCount:item.questionCount,  // 题目数量
            value:item.id,
        }
    })
   }
}


// 2. 问卷模板列表 获取 及 相关操作
const tableData = ref([]);
// 获取问卷模板列表
const GetQuestionnaireTemplateList = async ()=>{
    let res =  await getQuestionnaireTemplateListApi(route.query.id)
    if(res?.code == 200){
        tableData.value = res.data || []
    }
}

// 变更  选中的问卷
const HandleQuestionnaireTemplateChange = (row,val)=>{
    let aimQuesitonnaire = quesitonnaireOptionList.value.find(item=>{
        return item.value == val
    })
    if(isUnifiedTemplate.value){
        // 同步统一问卷模板
        tableData.value = tableData.value.map((item,index)=>{
            // if(index !== 0){
                item.assessmentId = val

                item.fullScore = aimQuesitonnaire.fullScore,
                item.questionCount = aimQuesitonnaire.questionCount
            // }
            return item
        })
    }else{
        tableData.value = tableData.value.map(item=>{
            if(item.name === row.name){
                return {
                        ...item,
                        fullScore:aimQuesitonnaire.fullScore,
                        questionCount:aimQuesitonnaire.questionCount
                    }
                }else{
                    return item
                }
            })
        }
}

// 预览问卷
const GoToPreviewQuestionnaire = (id)=>{
    sessionStorage.setItem('questionnaireAndTemplateList',JSON.stringify({
        tableData:tableData.value,
        quesitonnaireOptionList:quesitonnaireOptionList.value
    }))
    router.push(`/main/previewQuestionnaire?id=${id}`)
}


// 完成问卷模板配置
const FinishQuestionnaireTemplateConfig = async ()=>{
    let params = tableData.value.map(item=>{
        return {
            ids: item.ids,  //
            evaluationId:route.query.id,  // 评价任务id
            assessmentId: item?.assessmentId,  //问卷名称
            gender: item.gender,   //性别
        }
    })
    let res =  await saveQuestionnaireTemplateListApi(params)
    if(res?.code == 200){
        // 更新全局状态 
        await store.dispatch('updateEvaluationManageStepData',route.query.id)
        store.commit('updateEvaluationManageStepData',{currentActiveStepName:'reviewAccount'})  //更新全局活跃路由
        // 这里跳转到评价账号的时候，需要判断 评价码有没有生成，如果已经生成，跳到评价码页；
        // 如果没有生成，跳到 生成配置页
        let  isGenerateReviewCode = store.state.evaluationManageStepData.isGenerateReviewCode  //是否已生成评价码
        // 跳转到下一步 
        if(isGenerateReviewCode){
            router.push(`generateReviewCode?id=${route.query.id}`)
        }else{
            router.push(`reviewAccount?id=${route.query.id}`)
        }
    }
}


onMounted(async ()=>{
    let sessionQuestionnaireTemplateList = sessionStorage.getItem('questionnaireAndTemplateList')
    // 先判断是否有缓存 —— 从预览页跳转过来
    if(sessionQuestionnaireTemplateList){
        tableData.value = JSON.parse(sessionQuestionnaireTemplateList).tableData
        quesitonnaireOptionList.value = JSON.parse(sessionQuestionnaireTemplateList).quesitonnaireOptionList
        sessionStorage.removeItem('questionnaireAndTemplateList')  //获取完后清空
    }else{
        await GetQuestionnaireList()
        await GetQuestionnaireTemplateList()
    }
})

watch(()=>store.state.evaluationManageStepData.isHeadTeacherInvolved,(newVal)=>{
    // 初始值 和 班主任是否参与评价有关
    isUnifiedTemplate.value  =  !newVal
})
</script>



<style lang="scss" scoped>
.template_component{
    height: 100%;
    overflow: auto;
}

.questionnaire_cell{
    gap:16px;
    word-break: keep-all;

}
.table_content{
    overflow: auto;
}

</style>