<template>
    <div  ref="courseDom" class="main_container">
        <TopBackNav>
            <template #back>
                <el-button class="button_default_background" @click="GoBack">
                    <el-icon class="img"><ArrowLeftBold /></el-icon>
                    返回
                </el-button>
            </template>

            <template #topRight>
                <span class="paper_score">阅卷总分：<span class="score">{{questionTotalScore}}分</span></span>
                <el-button class="button_refresh" @click="PreviewQuestionnaire">预览问卷</el-button>
                <el-button class="button_background" @click="SaveQuestionnaire">保存问卷</el-button>
            </template>
        </TopBackNav>

        <div class="page_jg_20" style="flex-shrink: 0;"></div>

        <div class="questionnaire_config" >
            <!-- 左侧题型栏 -->
            <div  class="left_panel">
                <div class="panel_section page_item">
                    <h3 class="section_title">统计题</h3>
                    <!-- 题型循环 -->
                    <div class="type_list">
                        <template v-for="typeItm in statisticQuestionType" :key="typeItm.value">
                            <el-button class="button_refresh" 
                                        @click="CheckedQuestionType(typeItm.value)" >
                                <component :is="typeItm.icon"  class="img_icon"></component>
                                 {{ typeItm.label }}
                            </el-button>
                        </template>
                    </div>
                </div>

                <div class="panel_section page_item">
                    <h3 class="section_title">评分题</h3>
                     <!-- 题型循环 -->
                    <div class="type_list">
                        <template v-for="typeItm in scoredQuestionType" :key="typeItm.value">
                            <el-button class="button_refresh"
                                     @click="CheckedQuestionType(typeItm.value)">
                                <component :is="typeItm.icon" class="img_icon" ></component>
                                 {{ typeItm.label }}
                            </el-button>
                        </template>
                    </div>
                </div>
            </div>

            <!-- 中间面板：预览/操作区域 -->
            <div class="center_panel">
                <div class="page_item questionnaire_base">
                    <QuestionnaireBaseForm 
                        v-model:formRef="questionnaireBaseFormRef" 
                        :defaultFormData="defaultQuestionnaireInfo"
                        @formChange="SyncQuestionnaireFormData"
                    ></QuestionnaireBaseForm>
                </div>

                <!-- 已添加题目展示区 -->
                <ul class="question_list_area">
                    <li v-for="(question,index) in addedQuestionList" :key="question.id">
                        <div class="question_title">
                            <span class="question_name" 
                                :class="{required:question.extraConfig.includes('required')}"
                            >{{index + 1}}.{{ question.questionTitleName }}</span>
                            <span class="question_type">[{{ qustionTypeToName(question.questionType) }}]</span>
                            
                            <div class="operation table_row_option">
                                <span class="el_button_editor" @click="EditQuestion(question)">编辑</span>
                                <span class="el_button_delete" @click="DeleteQuestion(question)">删除</span>
                            </div>
                        </div>
                        
                        <QuestionTypeShow 
                            :isHorizontal="question.extraConfig.includes('isHorizontal')"
                            :questionType="Number(question.questionType)"
                            :questionSubOptions="question.options"
                            :evaluationType="Number(question.evaluationType)"
                            :questionScore="Number(question.questionScore)"
                        ></QuestionTypeShow>
                    </li>
                </ul>


                <!-- 题目添加区域 -->
                 <div class=" add_question_area">
                    <div v-if="!selectedQuestionType" class="add_question">
                        <div class="add_action">
                            <AddIcon :style="{'--icon-color':'#CCCCCC'}"></AddIcon>
                            点击左侧添加题型</div>
                    </div>
                    <div   v-else class="question_itm_edit">
                        <QuestionConfig  
                            :displayMode="selectedQuestionGetScore ? 'scored' : 'statistic'"
                            :defaultFormData="defaultQuestionData"
                            @formChange="HandleQuestionChange"
                            @confirm="AddQuesiton"
                            @cancel="selectedQuestionType = ''"
                        ></QuestionConfig>
                    </div>
                 </div>
            </div>

            <!-- 右侧面板：目录 -->
            <div class="right_panel page_item">
                <h3 class="section_title right_title">问卷目录 (拖动排序)</h3>
                <div v-if="!(addedQuestionList?.length >0)" class="empty_state">暂无问卷题目</div>
                
                
                <ul v-else class="question_list_brief">
                    <li v-for="(question,index) in addedQuestionList" :key="question.id">
                        <img :src="moveUpDownIcon" alt=""
                            :draggable="true"
                            @dragstart="(e)=>HandleDragStart(e)"
                            @dragend="(e)=>HandleDragEnd(e,question,index)"
                        >
                        <span :title="question.questionTitleName" class="one_line_ellipsis">
                            {{ index + 1 }}.{{ question.questionTitleName }}
                        </span>
                    </li>
                </ul>
            </div>
        </div>

        <Dialog 
            :visible="dialogVisible" 
            :submitLoading="dialogSubmitLoading"
            @close="HandleDialogClose"
            @confirm="HandleSaveOrNotQuestionnare(true)"
        >
            <span>
                有未保存内容,要在关闭前保存更改吗?
            </span>

            <template #footerLeft>
                <el-button class="button_refresh" @click="HandleSaveOrNotQuestionnare(false)">不保存</el-button>
            </template>
        </Dialog>

    </div>
</template>

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


import TopBackNav from '@/components/TopBackNav.vue';
import {statisticQuestionType,scoredQuestionType,qustionTypeToName} from '@/components/questionConfig/questionTypeList'
import QuestionConfig from '@/components/questionConfig/QuestionConfig.vue';
import QuestionnaireBaseForm from '@/components/questionConfig/QuestionnaireBaseForm.vue';
import Dialog from '@/baseComponents/Dialog.vue';


import { unioformDateTransform } from '@/utils/dateTransform';
import { useHandleMoveUpAndDown } from '@/baseComponents/useHandleMoveUpAndDown';

import QuestionTypeShow from '@/components/QuestionTypeShow.vue';
import moveUpDownIcon from '@/assets/icon/move_up_down.png'
import AddIcon from '@/assets/icon/AddIcon.vue'

import {addQuestionnaireApi,editQuestionnaireApi, getQuestionnaireDetailApi} from '@/api/surveyManagement'

// 题目选项信息 参数
interface Option {
    content: String
    score?: String
    id?: Number
}
// 题目信息 参数
interface QuestionItm {
    id:Number
    questionTitleName: String   //题目名称
    questionScore?: String | Number  //题目分值
    questionType: String | String   //题目类型
    extraConfig: String[]    // 是否必答 required, 是否横排 isHorizontal
    options: Option[],  //单选/多选 的 选项配置
    evaluationType: Number|String   // 评分题 的 分值展示形式
}

interface QuestionnaireInfo {
    assessmentTitle:String, //问卷标题
    assessmentIllustrate:String,  //问卷说明
    createdAt?:String,   //创建时间
    teacherName?:String,  //创建人
    useStatus?:String | Number,  //使用状态

}


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

// 试卷头表单
const questionnaireBaseFormRef = ref()

// 试卷头的默认信息
const defaultQuestionnaireInfo = ref<QuestionnaireInfo>({})
// 试卷头基本信息
const questionnaireInfo = ref<QuestionnaireInfo>({
    assessmentTitle:'',
    assessmentIllustrate:'',
    createdAt:'',
    teacherName:'',
    useStatus:''
})
// 已经添加的题型
const addedQuestionList = ref<QuestionItm[]>([])

// 默认的试题信息
const defaultQuestionData = ref({})

// 当前选中的题型
const selectedQuestionType = ref('')
// 选中题型 是否得分 // 得分题  true  非得分题 false 
const selectedQuestionGetScore = ref(false)
// 试卷总分
const questionTotalScore = computed(()=>{
    return addedQuestionList.value?.reduce((a,b)=>{
        let aScore =  Number(a.questionScore || 0)
        let bScore =  Number(b.questionScore || 0)
        return {
            questionScore:aScore + bScore
        }
    },{questionScore:0}).questionScore
})

// 当前选择修改的题目 id
const currentEditQuestionId = ref()

// 当前问卷信息是否已经保存
const isSaveQuestionnaire = ref(true)


// 选中题型时的处理  
const CheckedQuestionType = (type:any) => {
    console.log('触发操作了',type)
    selectedQuestionType.value = String(type)
    resetQuestionForm(type)

    switch(Number(type)){
        case 0:
        case 1:
        case 2:
            selectedQuestionGetScore.value = false
            break
        case 3:
        case 5:
            selectedQuestionGetScore.value = true
            break
    }
}

// 同步问卷头表单数据
const SyncQuestionnaireFormData = (params)=>{
    isSaveQuestionnaire.value = false
    questionnaireInfo.value = {...params}
}

// 重置试题表单数据
const resetQuestionForm = (questionType)=>{

    // 重置逻辑要修改 _ 不同类型表单的重置逻辑不一样
    let options:any[] = []
    switch(Number(questionType)){
        case 0:
        case 1: 
        case 3: 
        {
            options = [
                {
                    content: '',
                    score: '',
                    id:1 ,
                },
                {
                    content: '',
                    score: '',
                    id:2 ,
                },
                {
                    content: '',
                    score: '',
                    id:3 ,
                },
                {
                    content: '',
                    score: '',
                    id:4 ,
                },
            ]
            break
        }
    }

  

    defaultQuestionData.value = {
        questionTitleName: '',  
        questionScore: '',   
        questionType: questionType, 
        extraConfig: Number(questionType) === 2 ? [] :  ['required'],  //默认勾选必答题
        options: [...options],
        evaluationType:0  //默认展示 数字式
    }
}
// 表单数据触发变化了
const HandleQuestionChange = (params)=>{
    const { key, val, formData: data } = params
    switch(key){
        case 'question_type':{
            console.log('表单重置了--')
            
            resetQuestionForm(val)


        }
    }
}

// 处理试题排序
const { HandleDragStart, HandleDragEnd } = useHandleMoveUpAndDown(addedQuestionList,42)

// 添加/修改 试题信息
const AddQuesiton = (params)=>{
    // 评分题目 _ 要添加选项的分值判断 _待确认
    // if(Number(params.questionType) === 3){
    //     params.options.map(itm=>{

    //     })

    // }



    isSaveQuestionnaire.value = false
    const {formRef,formData} = params
    console.log('获取到试题信息了',formData)
    // 试题选项配置 _如果有的话
     let options = formData?.options?.map(item=>{
        return {
            content:item.content,
            id:item.id,
            score:item.score
        }
    }) || []
    if(currentEditQuestionId.value){
        // 修改试题
        addedQuestionList.value  = addedQuestionList.value.map(item=>{
            if(item.id == currentEditQuestionId.value){
                return {
                    ...formData,
                    options
                }
            }else{
                return item
            }
        })
        currentEditQuestionId.value = ''
    }else{
        // 新增试题
        // 绑定时间戳，保证临时id唯一
        let id =`tmp_${new Date().getTime()}_${addedQuestionList.value.length + 1}`
        addedQuestionList.value.push({id ,...formData,options})
    }
    formRef.resetFields()
    selectedQuestionType.value = ''
}



// 删除当前题目
const DeleteQuestion = (row)=>{
    addedQuestionList.value = addedQuestionList.value.filter(item=>{
        return item.id !== row.id   
    })
}

// 修改选择的题目
const EditQuestion = (row)=>{
    console.log('当前编辑的行',row)
    currentEditQuestionId.value = row.id  
    // 先后顺序不要反
    CheckedQuestionType(row.questionType)

    defaultQuestionData.value = {
        // 格式化一下，防止 obj值 修改过程中的错误引用，
        ...(JSON.parse(JSON.stringify(row))),  
        questionType:String(row.questionType)
    }
}

// 保存试卷
const SaveQuestionnaire = async ()=>{
    if(selectedQuestionType.value){
        ElMessage.warning('请先保存当前正在编辑的内容')
        return
    }

    let saveSuccess =  false
    // 试卷总表单
    let formRef = questionnaireBaseFormRef.value

    if (!formRef) return
    await formRef.validate(async(valid) => {
        if (valid) {
            if(addedQuestionList.value.length > 0){
                // 限40字
                if(questionnaireInfo.value?.assessmentTitle?.length > 40){
                    ElMessage.warning('问卷标题不得超过40字')
                    return
                }
                // 限100字
                if(questionnaireInfo.value?.assessmentIllustrate?.length > 100){
                    ElMessage.warning('问卷说明不得超过100字')
                    return
                }

                let questionData = addedQuestionList.value.map((item,index)=>{
                    return {
                        questionTitleName: item.questionTitleName,
                        questionType: item.questionType,
                        questionScore: item.questionScore,
                        evaluationType: item.evaluationType,

                        questionAnswerType:item.extraConfig.includes('required') ? 1 : 0,  // 是否必答，0-否，1-是
                        questionSortRole:item.extraConfig.includes('isHorizontal') ? 1 : 0, // 0-竖排，1-横排
                        questionSortCode:index + 1,
                        answerData:item.options.map((opt,optIndex)=>{
                            return {
                                questionSortCode: optIndex + 1,
                                answerName: opt.content,
                                answerScore: opt.score
                            }
                        })
                    }
                })
                 // 不带id的基础信息
                let params = {
                    assessmentTitle: questionnaireInfo.value.assessmentTitle,
                    assessmentIllustrate: questionnaireInfo.value.assessmentIllustrate,

                    questionData:questionData,
                    assessmentScore:questionTotalScore.value
                }
                let res = undefined
                if(route.query.id){
                    // 编辑问卷
                    res = await editQuestionnaireApi({...params,id:route.query.id})
                 }else{
                    // 新增问卷
                    res = await addQuestionnaireApi(params)
                }
                if(res?.code == 200){
                    ElMessage.success(res?.msg)
                    saveSuccess = true
                    isSaveQuestionnaire.value = true
                }
            }else{
                ElMessage.warning('请添加问卷题目')
            }
        }
    }).catch(err=>{
        console.log('报错信息',err)
    })
    return saveSuccess
}


// 预览试卷
const PreviewQuestionnaire =()=>{
    // 存储本地存储
    let finalMsg = {
        ...(questionnaireInfo.value),
        questionData:addedQuestionList.value,
    }
    sessionStorage.setItem('questionnaireTmpMsg',JSON.stringify(finalMsg))
    router.push(`/main/previewQuestionnaire`)
}

// 编辑状态 获取问卷信息
const GetQuestionnaireDetail =async ()=>{
    let res = await getQuestionnaireDetailApi(route.query.id)
    if(res?.code == 200){
        const  {assessmentTitle,assessmentIllustrate,questionData,
                createdAt,teacherName,useStatus

         } = res.data

        defaultQuestionnaireInfo.value = {
            assessmentTitle:assessmentTitle,
            assessmentIllustrate:assessmentIllustrate,
            createdAt,
            teacherName,
            useStatus
        }
        addedQuestionList.value = questionData.map(item=>{
            let options = item.answerData.map(opt=>{
                return{
                    content: opt.answerName,
                    score: opt.answerScore,
                    // id: opt.questionId
                    id: opt.id
                }
            })

            let extraConfig = []
            if(Number(item.questionAnswerType) === 1){
                extraConfig.push('required')
            }
            if(Number(item.questionSortRole) === 1){
                extraConfig.push('isHorizontal')
            }
            return {
                ...item,
                // id:item.assessmentId,
                id:item.id,
                extraConfig,    // 是否必答 required, 是否横排 isHorizontal
                options
            }
        })
    }
}


// 关闭 试卷 提示
const dialogVisible= ref(false)
const dialogSubmitLoading = ref(false)
// 打开删除弹窗
const OpenDeleteDialog = ()=>{
    dialogVisible.value = true
}
// 关闭删除弹窗
const HandleDialogClose = ()=>{
    dialogVisible.value = false
    dialogSubmitLoading.value = false
}
// 确认保存/不保存 操作
const HandleSaveOrNotQuestionnare = async (flag)=>{
    if(flag){
        // 保存
        dialogSubmitLoading.value = true
        // 保存接口
        let successFlag =   await SaveQuestionnaire()
        if(successFlag){
            HandleDialogClose()
            router.go(-1)
        }else{
            ElMessage.warning('请检查问卷信息是否完整')
            dialogSubmitLoading.value = false
        }
    }else{
        // 不保存
        HandleDialogClose()
        router.go(-1)
    }
}


// 返回前添加判断
const GoBack = ()=>{
    if(isSaveQuestionnaire.value){
        router.go(-1)
    }else{
        // 弹出问卷提示
        OpenDeleteDialog()
    }
}
onMounted(async ()=>{
    

    let localQuestionnaireMsg = sessionStorage.getItem('questionnaireTmpMsg')
    // 先取本地数据__如果有,证明是从预览页返回来的
    if(localQuestionnaireMsg){
        let localMsg = JSON.parse(localQuestionnaireMsg)

         const  {assessmentTitle,assessmentIllustrate,questionData,
                createdAt,teacherName,useStatus

         } = localMsg

        defaultQuestionnaireInfo.value = {
            assessmentTitle,
            assessmentIllustrate,
            createdAt,
            teacherName,
            useStatus
        }
        addedQuestionList.value = questionData
        // 获取到后清除数据_防止后续从列表页预览访问过程中的数据污染
        sessionStorage.removeItem('questionnaireTmpMsg')
    
    }else{
        // 正常编辑问卷
        if(route.query.id){
            await GetQuestionnaireDetail()
        }else{
            // 创建问卷 状态 ——  不执行操作
        }
    }
})
</script>

<style lang="scss" scoped>

:deep(.top_header){
    .top_right{
        display: flex;
        align-items: center;
        .el-button{
            margin-left:0px !important;
            &.button_refresh{
                margin-right: 10px;
            }
        }
        .paper_score{
            font-weight: 600;
            margin-right: 20px;
            .score{
                color:#2E64FA;
            }
        }
    }
}

.questionnaire_config {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    gap: 20px;

    max-height: calc(100vh - 116px - 60px);
    height: calc(100vh - 116px - 60px);
    overflow-y:auto ;
    
    /* --- 左侧面板 --- */
    .left_panel {
        width: 200px;
        display: flex;
        flex-direction: column;
        gap: 20px;
        .panel_section {
            padding: 16px 20px;

            .type_list {
                display: flex;
                flex-direction: column;
                gap: 16px;
                                
                :deep(.el-button) {
                    display: flex;
                    justify-content: flex-start;
                    align-items: center;
                    padding:12px;
                    margin: 0;
                    font-size: 14px;
                    color:#666666;
                    >span{
                        display: flex;
                        justify-content: flex-start;
                        align-items: center;
                        gap:8px;
                    }
                 
                    &:hover{
                        color:#2E64FA;
                        border:solid #2E64FA 1px;
                        .img_icon{
                            --icon-color:#2E64FA;
                        }
                    }
                }
            }
        }
    }

    /* --- 中间面板 --- */
    .center_panel {
        max-height:100%;
        height:100%;
        width: calc(100vw - 440px - 80px);
        display: flex;
        flex-direction: column;
        border-radius: 10px;
        background-color: white;
        overflow-y:auto ;

        .questionnaire_base{
            border-radius:10px 10px 0 0;
            padding-bottom: 0;
        }
        
        // 已添加试题区
        .question_list_area{
            display: flex;
            flex-direction: column;
            gap:20px;
            padding-top:10px;
            font-size: 16px;
            color:#000;
            li{
                padding:10px 20px;

                .question_title{
                    display: flex;
                    justify-content: flex-start;
                    align-items: flex-start;
                    word-break: keep-all;
                    margin-bottom: 20px;
                    .question_type{
                        color:#2E64FA;
                        margin-left: 8px;
                    }

                    .question_name{
                        word-break: break-all;
                        &.required{
                            position: relative;
                            padding-right: 6px;
                            &::after{
                                position: absolute;
                                right: 0;
                                top:0;
                                content:'*';
                                width: 5px;
                                color: #f56c6c;
                                margin-left: 2px;
                                font-size: 18px;
                            }
                        }
                    }

                    .operation{
                        margin-left: 20px;
                        display: none;
                        flex: 1 1;
                        justify-content: flex-end;
                        gap:20px;

                    }
                }

                &:hover{
                    box-shadow: 0px 10px 20px 0px rgba(46,100,250,0.1), 
                                0px -10px 20px 0px rgba(46,100,250,0.1);
                    .question_title .operation{
                        display: flex;
                    }
                }
            }
        }

        // 添加试题区域
        .add_question_area{
            .add_question {
                // flex-grow: 0;
                margin:20px;
                border: 1px dashed #C0C4CC;
                border-radius: 4px;
                display: flex;
                justify-content: center;
                align-items: center;
                height: 240px;
                .add_action {
                    color: #cccccc;
                    font-size: 16px;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    gap:4px;
                }
            }
            .question_itm_edit {
                // flex-grow: 0;
                background-color: #F8FAFE;
            }
        }
    }

    /* --- 右侧面板 --- */
    .right_panel {
        max-height:100%;
        overflow-y:auto ;

        align-self: flex-start;
        width: 240px;
        min-height: calc(100vh - 156px - 40px);
        display: flex;
        flex-direction: column;
        .empty_state {
            flex: 1;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 16px;
            color: #C0C4CC;
        }

        .question_list_brief{
            display: flex;
            flex-direction: column;
            font-size: 14px;
            li{
                display: flex;
                align-items: center;
                gap:8px;
                padding:10px 0;
                img{
                    width:20px;
                    height:20px;
                }
            }
        }
    }

    .section_title {
        font-weight: 600;
        font-size: 16px;
        margin-bottom: 10px;
    }
}



</style>
