<template>
  <div class="detail_main">
    <div class="question_header">
        <div class="item_title">
            <div class="item_step">1</div>
            扫描标准答案：<el-button type="primary"  style="width: 88px;">开始扫描</el-button>  
            <!-- <span class="preview_btn">预览</span> -->
            <!-- <el-button style="margin-left: 10px;width: 116px;">引用试题结构</el-button> -->
        </div>
        <div class="choose_template">
            当前模板：{{templateName}}  
             <!-- <span class="choose_btn" @click="OpenChooseTemplate()">更换</span> -->
        </div>
    </div>
    <div class="page_jg_20"></div>
    <div class="page_module">
        <div class="item_title">
            <div class="item_step">2</div>
            设置分值：
            <div class="item_search">
                <div class="search_name">题目从</div>
                <el-select  v-model="queryParams.start"   placeholder="请选择"  class="select_width" >
                    <el-option :label="number" :value="number" v-for="number in templateQuestionCount"></el-option>
                </el-select>
                <div class="search_name">至</div>
                <el-select  v-model="queryParams.end"   placeholder="请选择"  class="select_width" >
                    <el-option :label="number" :value="number" v-for="number in templateQuestionCount"></el-option>
                </el-select>
            </div>
            <div class="item_search">
                <div class="search_name">题目类型：</div>
                <el-select  v-model="queryParams.questionType"   placeholder="请选择"  class="select_width" >
                    <el-option label="单选题" :value="1"></el-option>
                    <el-option label="多选题" :value="2"></el-option>
                </el-select>
            </div>
            <div class="item_search">
                <div class="search_name">每题满分：</div>
                <el-input v-model="queryParams.fullMark" placeholder="请输入" maxlength="3" @input="(val: any) => onScoreInput(queryParams, 'fullMark', val)"   class="select_width" ></el-input>
            </div>
            <div class="item_search">
                <div class="search_name">分组：</div>
                <el-input v-model="queryParams.groupName" placeholder="请输入"  class="select_width" ></el-input>
            </div>
            <div class="item_search">
                <el-button type="primary"  style="width: 68px;" @click="EnterSetQuestion()">确定</el-button>
            </div>

            <div class="delete_all">
                <div  class="delete_btn" @click="DeleteAll()">全部删除</div>
            </div>
        </div>
        <div class="page_jg_16"></div>
        <div class="table_42">
            <el-table :data="tableData" style="width: 100%" :height="tableHeight">
                <el-table-column prop="questionName" label="题目名称" width="100">
                </el-table-column>
                <!-- 题目类型 questionType 1 单校  2多选 -->
                <el-table-column prop="questionType" label="题目类型" width="120">
                    <template v-slot="scope">
                        <el-select  v-model="scope.row.questionType"  style="width: calc(100% - 32px);" @change="TypeChange(scope.row)">
                            <el-option :value="1" label="单选题"></el-option>
                            <el-option :value="2" label="多选题"></el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column prop="date" label="标注答案" width="242">
                    <template v-slot="scope">
                        <div class="answer_input">
                            <!-- 单选题 -->
                            <div class="single_selected"  v-if="scope.row.questionType == 1">
                                <el-button  v-for="(item,index) in scope.row.optionsSize" :type="scope.row.standardAnswer === answerList[index] ? 'primary': ''"  class="selected_button" @click="SingleClick(scope.row,answerList[index])">{{answerList[index]}}</el-button>
                            </div>
                            <!-- 多选 -->
                            <div class="single_selected"  v-if="scope.row.questionType == 2">
                                <el-button v-for="(item,index) in scope.row.optionsSize" :type="scope.row.standardAnswer?.includes(answerList[index]) ? 'primary': ''"  class="selected_button" @click="MultiClick(answerList[index],scope.row)">{{answerList[index]}}</el-button>
                                
                            </div>
                            <!-- 判断题 -->
                            <div class="single_selected" v-if="scope.row.questionType == 3">
                                <el-button  v-for="(item,index) in 2" :type="scope.row.standardAnswer === tflist[index]   ? 'primary': ''" class="selected_button" @click="SingleClick(tflist[index],scope.row)">{{tflist[index]}}</el-button>
                                
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="fullScore" label="满分" width="120">
                    <template v-slot="scope">
                        <div class="full_mark_input">
                            <el-input v-model="scope.row.fullScore" maxlength="3" @input="(val: any) => onScoreInput(scope.row, 'fullScore', val)"></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="多选题给分分布">
                    <template v-slot="scope">
                        <div v-if="scope.row.questionType == '1' || scope.row.questionType == '3'">
                            {{ '-' }}
                        </div>
                        <div v-if="scope.row.questionType == '2'">
                            <div v-if="scope.row.multipleRule == '1'"> 
                                全对得满分
                                <span>,少选得{{ scope.row.multipleRuleDesc || 0 }}分，选错不得分</span>
                            </div>
                            <div v-if="scope.row.multipleRule == '2'">
                                全对得满分，选对1个得{{ scope.row.multipleRuleDesc?.split(',')[0] }}分
                                <span v-if="scope.row.multipleRuleDesc && scope.row.standardAnswer.split(',').length > 2">，选对2个得{{ scope.row.multipleRuleDesc?.split(',')[1] }}分</span>
                                <span v-if="scope.row.multipleRuleDesc && scope.row.standardAnswer.split(',').length == 4">，选对3个得{{ scope.row.multipleRuleDesc?.split(',')[2] }}分</span>
                            </div>
                            <div v-if="scope.row.multipleRule == '3'">
                                {{scope.row.multipleRuleDesc}}
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="groupName" label="分组">
                    <template v-slot="scope">
                        <div class="input_width">
                            <el-input v-model="scope.row.groupName" maxlength="3" ></el-input>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="操作" width="150">
                    <template v-slot="scope">
                        <div class="ele_button table_row_button">
                            <span class="btn_editor" @click="EditorSingle(scope.row)">编辑</span>
                            <span class="btn_delete" @click="DeleteSingle(scope.row)">删除</span>
                        </div>
                   </template>
                </el-table-column>
            </el-table>
            <div class="page_info">
                共{{tableData.length}}题   总分：{{totalScore}}分
            </div>
        </div>
        <div class="page_button">
            <el-button type="primary"  style="width: 200px;" @click="FinishQuestion()">完成</el-button>
        </div>
    </div>
    <ChooseTemplate v-model="showChooseTemplate"></ChooseTemplate>
    <EditorQuestion ref="enterStandardEdit" @AnswerEnter="EditorAnswerEnter"></EditorQuestion>
  </div>
</template>
<script lang="ts" setup>
import { useExamStore } from '@/store/exam'
import { useRouter } from 'vue-router'
import { onMounted,computed ,onUnmounted,ref,nextTick } from 'vue';
import ChooseTemplate from './components/chooseTemplate.vue';
import EditorQuestion from './components/EditorQuestion.vue';

import { ElMessageBox,ElMessage } from 'element-plus' 
import { getSmartQuestionList,getTemplateInfo,setQuestion,saveQuestion,deleteAllQuestion,deleteSingleQuestion} from '@/api/exam'



// 实例化 Store
const examStore = useExamStore()
const router = useRouter()

// 定义题目数据的接口类型
interface QuestionItem {
  id?: string;
  questionName?: string;
  questionType?: number; // 1:单选, 2:多选, 3:判断
  standardAnswer?: string;
  fullScore?: string | number;
  groupName?: string;
  optionsSize?: number;
  multipleRule?: string;
  multipleRuleDesc?: string;
  [key: string]: any; // 允许其他动态属性
}

const queryParams= ref({
    start:'',
    end:'',
    questionType:null,
    fullMark:'',
    groupName:'',//分组名称
})

const templateName=ref('机读卡');
const templateQuestionCount=ref(0);//模板题目总数量
const showChooseTemplate=ref(false);// 弹出选择模板的弹窗
const tableData = ref<QuestionItem[]>([])
const enterStandardEdit=ref<HTMLElement>();//标准答案编辑组件实例

const tableHeight = ref(400)// 表格高度
const answerList=['A','B','C','D','E','F','G','H','I','J','K']//答案列表
const tflist=['T','F']//判断题列表


// 考试科目 ID
const examSubjectId = computed(() => {
  return examStore.currentExam?.id
})//计算属性

const templateId=computed(() => {
  return examStore.currentExam?.templateId
})//计算属性

const totalScore=computed(() => {
  if (!tableData.value || tableData.value.length === 0) {
    return 0;
  }
  
  // 累加所有题目的 fullScore，防止值为空或非数字时出错
  const sum = tableData.value.reduce((total, item) => {
    // 确保 fullScore 是有效数字，如果是空字符串或 null 则视为 0
    const score = Number(item.fullScore);
    return total + (isNaN(score) ? 0 : score);
  }, 0);

  return sum;
})

// 通用分数输入处理函数
// target: 需要更新的目标对象 (如 scope.row 或 queryParams)
// key: 目标对象中的属性名 (如 'fullScore' 或 'fullMark')
// // val: 当前输入的值
const onScoreInput = (target: any, key: string, val: any) => {
    // 1. 确保 val 是字符串
    let strVal = String(val || '');
    
    // 2. 正则替换：只保留数字和小数点
    strVal = strVal.replace(/[^\d.]/g, '');
    
    // 3. 逻辑：只允许一个小数点
    const parts = strVal.split('.');
    if (parts.length > 2) {
        strVal = parts[0] + '.' + parts.slice(1).join('');
    }
    
    // 4. 逻辑：限制总长度不超过3
    if (strVal.length > 3) {
        strVal = strVal.slice(0, 3);
    }
    
    // 5. 逻辑：如果不以数字开头且不为空，防止单独输入 '.'
    // 注意：如果允许 "0." 这种输入，则不需要此步，但通常 "0." 后面还得跟数字，这里暂时保留防止非法状态
    if (strVal === '.') {
        strVal = ''; 
    }

    // 6. 关键步骤：直接修改目标对象的属性
    if (target && key) {
        target[key] = strVal;
    }
};

//打开选择模板弹窗
const OpenChooseTemplate=()=>{
    showChooseTemplate.value=true;
}

//切换题目类型
const TypeChange=(item:any)=>{
    console.log("打印题目类型",item)
    
}

//单选点击事件
const SingleClick=(item:any,answer:any)=>{
    console.log("打印单选点击",item,answer)
    item.standardAnswer = answer;
    console.log(item);//打印当前标准客户题题列表
}

// 多选点击事件
const MultiClick=(answer:any,item:any)=>{
    console.log("打印多选点击",answer,item)

            // console.log("打印当前questionTable",this.questionTable);

    if(item.standardAnswer==undefined)
    {
        item.standardAnswer='';
    }
    // let answerlist=item.standardAnswer==''?[]:item.standardAnswer?.split(",");
    let answerlist = item.standardAnswer === '' ? [] : (item.standardAnswer || '').replace(/\s+/g, '').split(',').flatMap(item => item === '' ? [] : item.split(''));
    if (!answerlist?.includes(answer)) 
    {
        answerlist?.push(answer)

    }
    else 
    {
        answerlist?.forEach((i,index) => {
            if (i === answer) {
                answerlist?.splice(index,1)
            }
        })
    }
    item.standardAnswer = answerlist?.join(",")
    //     // 给当前题选择的答案赋值
    // for(var i=0;i<this.questionTable.length;i++)
    // {
    //     if(item.id==this.questionTable[i].id)
    //     {
    //         this.questionTable[i].standardAnswer=item.standardAnswer;
    //     }
    // }
    // console.log("打印当前questionTable",this.questionTable);
}

//删除全部 需要二次弹窗确认提示
const DeleteAll=()=>{
    console.log("打印删除全部")
    ElMessageBox.confirm('确认删除所有题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        customClass:'page_dialog',
    }).then(async () => {
        console.log('删除考试')
        const param={
            id:examSubjectId.value,
        };
        const res = await deleteAllQuestion(param)
        if(res.code == 200) 
        {
            ElMessage.success("删除成功!")
            GetSmartQuestionList();
        }
        else
        {
            ElMessage.error(res.msg)
        }
    })
}

//确定完成
const FinishQuestion=async ()=>{
    console.log("打印完成")
    ElMessageBox.confirm('确认完成吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        console.log('完成',tableData.value)

        const res = await saveQuestion(tableData.value)
        if(res.code == 200) 
        {
            ElMessage.success("保存成功!")
            GetSmartQuestionList();
        }
        else
        {
            ElMessage.error(res.msg)
        }
    })
}

//确定编辑
const EditorAnswerEnter=async (item:any)=>{
    console.log("打印确定编辑",item)
    let params=[];
    params.push(item);
    const res = await saveQuestion(params)
    if(res.code == 200) 
    {
        ElMessage.success("保存成功!")
        GetSmartQuestionList();
    }
    else
    {
        ElMessage.error(res.msg)
    }
}

//删除单个题目 需要二次弹窗确认提示
const DeleteSingle=(item:any)=>{
    console.log("打印删除单个",item)
    ElMessageBox.confirm('确认删除该题目吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        customClass:'page_dialog',
        type: 'warning'
    }).then(async () => {
        console.log('删除考试')
        const param={
            id:item.id,
            examSubjectId:examSubjectId.value,
        };
        const res = await deleteSingleQuestion(param)
        if(res.code == 200) 
        {
            ElMessage.success("删除成功!")
            GetSmartQuestionList(); 
        }
        else
        {
            ElMessage.error(res.msg);
        }
    })
}

//编辑单个题目
const EditorSingle=(item:any)=>{
    console.log("打印编辑单个题目",item)
    enterStandardEdit.value.InitData(item);
}
// 4. 计算高度的函数
const CalculateTableHeight = () => {

  // 获取父容器的高度
  const containerHeight = window.innerHeight 
  
  // 减去其他固定元素的高度（需要根据实际布局调整这些数值）
  // 例如：header(64px) + 间距(20px) + 标题区域(约50px) + 底部按钮区域(约60px) + 分页信息(56px)
  // 建议通过浏览器控制台检查实际占用高度
  const offset = 320 // 这是一个预估值，请根据实际 CSS 调整
  
  tableHeight.value = containerHeight - offset
}

//获取模板信息
const GetTemplateInfo=()=>{
    const params={
        templateId:templateId.value,
    };
    getTemplateInfo(params).then((res) => {
        console.log("打印获取模板信息结果",res)
        if(res.code==200)
        {
            templateQuestionCount.value=res.data.totalQuestionSize;//题目数量
            templateName.value=res.data.templateName;
        }
    })
}

//获取试题列表
const GetSmartQuestionList=()=>{
    const params={
        examSubjectId: examSubjectId.value,
    };
    getSmartQuestionList(params).then((res) => {
        console.log("打印获取试题结构列表结果",res)
        if(res.code==200)
        {
            // tableData.value=res.data;
            // 增加空值保护，确保 tableData 始终是数组
            tableData.value = Array.isArray(res.data) ? res.data : [];
        }
    })
}

//确定设置题目
const EnterSetQuestion=()=>{
    console.log("打印提交参数",queryParams.value)

    const params={
        examSubjectId: examSubjectId.value,//考试科目id
        questionMin: queryParams.value.start,//起始题号
        questionMax: queryParams.value.end,//结束题号
        questionType: queryParams.value.questionType,
        fullScore: queryParams.value.fullMark,
        groupName: queryParams.value.groupName,
    };
    setQuestion(params).then((res) => {
        console.log("打印设置题目结果",res)
        if(res.code==200)
        {
           //设置成功 更新列表
           GetSmartQuestionList();
        }
    })
}

onMounted(() => {
  
    if (!examStore.currentExam) {
        console.warn('当前没有选中的考试信息')
        // 可选：如果没有数据，可以重定向回列表页或提示用户
    }
    GetSmartQuestionList();
    GetTemplateInfo();
    // 初始化计算
    nextTick(() => {
        CalculateTableHeight()
    })

    window.addEventListener('resize', CalculateTableHeight)
})


onUnmounted(() => {
    // 移除监听，防止内存泄漏
    window.removeEventListener('resize', CalculateTableHeight)
})
</script>
 
<style lang="scss" scoped>
.detail_main
{
    height: 100vh; /* 或 100% */
    display: flex;
    flex-direction: column;
}
.question_header
{
    width: 100%;
    height: 64px;
    line-height: 64px;
    background: #FFFFFF;
    border-radius: 10px 10px 10px 10px;
    padding: 0 20px;
    box-sizing: border-box;

    display: flex;
    justify-content: space-between;

    .choose_template
    {
        font-weight: 500;
        font-size: 16px;
        color: #333333;

        .choose_btn
        {
            font-weight: 500;
            font-size: 16px;
            color: #2E64FA;
            margin-left: 10px;
            cursor: pointer;
        }

    }

}
.item_step
{
    width: 20px;
    height: 20px;
    background: #2E64FA;
    border-radius: 50%;
    font-weight: 500;
    font-size: 14px;
    color: #FFFFFF;
    text-align: center;
    line-height: 20px;

}

.item_search
{
    display: flex;
    align-items: center;
    gap: 10px;
    margin-right: 10px;
    .search_name
    {
        width: auto;
        font-weight: 400;
        font-size: 16px;
        color: #666666;
    }
    
    .select_width
    {
        width: 100px;
    }
}
.item_title
{
    font-weight: 500;
    font-size: 16px;
    color: #333333;

    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
    position: relative;

    .preview_btn
    {
        font-weight: 500;
        font-size: 16px;
        color: #2E64FA;
        cursor: pointer;
    }

    .delete_all
    {
        position: absolute;
        right: 0;
        top: 0;
        width: 100px;
        height: 36px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .delete_btn
        {
            width: 88px;
            height: 34px;
            line-height: 34px;
            text-align: center;
            border-radius: 4px 4px 4px 4px;
            border: 1px solid #F56C6C;
            font-weight: 500;
            font-size: 14px;
            color: #F56C6C;
            cursor: pointer;
        }
    }
}

.page_info
{
    font-weight: 500;
    font-size: 16px;
    color: #333333;
    text-align: right;
    height: 56px;
    line-height: 56px;
}

.page_button
{
    text-align: center;
}

//标准答案录入
.answer_input {
    width: 100%;
    padding-top: 8px;
    padding-bottom: 8px;
    margin: auto;
    // background-color: red;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    height: auto;

    .single_selected {
      width: auto;
      margin: auto;
      display: flex;
      justify-content: flex-start;
      flex-wrap: wrap;

      gap: 8px;

      .selected_button {
        width: 32px;
        height: 32px;
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 5px;
        padding: 0 !important;
        border-radius: 50%;
        margin: 0;

      }
    }


  }
</style>