<template>
    <div class="page_dialog">
        <el-dialog 
            :title="title" 
            v-model="dialogVisible" 
            :close-on-click-modal="false"
            :width="answerOption.questionType == 2 ? '850px' : '480px'" 
            class="page_dialog"
        >
            <div class="padding_20" style="padding-bottom: 10px;">
                <div class="dialog_center">
                    <el-form ref="formRef" :model="answerOption" label-width="120px">
                        <el-form-item label="题目名称：">
                            <el-input v-model="answerOption.questionName" placeholder="请输入"></el-input>
                        </el-form-item>
                        <el-form-item label="题目类型：">
                            <el-select 
                                :popper-append-to-body="false" 
                                v-model="answerOption.questionType" 
                                @change="TypeChange"
                            >
                                <el-option :value="1" label="单选题"></el-option>
                                <el-option :value="2" label="多选题"></el-option>
                                <el-option :value="3" label="判断题" v-if="answerOption.optionsSize == 2"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <!-- 单选题标准答案 -->
                        <el-form-item label="标准答案：" v-if="answerOption.questionType == 1">
                            <el-select v-model="answerOption.standardAnswer" placeholder="请选择">
                                <el-option 
                                    :value="answerList[index]" 
                                    :label="answerList[index]"
                                    v-for="(item, index) in answerOption.optionsSize" 
                                    :key="index"
                                ></el-option>
                            </el-select>
                        </el-form-item>

                        <!-- 判断题标准答案 -->
                        <el-form-item label="标准答案：" v-if="answerOption.questionType == 3">
                            <el-select v-model="answerOption.standardAnswer" placeholder="请选择">
                                <el-option value="T" label="T"></el-option>
                                <el-option value="F" label="F"></el-option>
                            </el-select>
                        </el-form-item>

                        <!-- 多选题标准答案 -->
                        <el-form-item label="标准答案：" v-if="answerOption.questionType == 2">
                            <el-checkbox-group v-model="mulAnswerList" @change="MulAnswerChange">
                                <el-checkbox 
                                    v-for="(item, index) in answerOption.optionsSize" 
                                    :key="index"
                                    :label="answerList[index]" 
                                    :value="answerList[index]"
                                ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>

                        <el-form-item label="满分：">
                            <el-input v-model="answerOption.fullScore" maxlength="2" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-form>
                </div>

                <!-- 多选题给分规则 -->
                <div class="dialog_group" v-if="answerOption.questionType == 2">
                    <div class="radio_group_socre">
                        <el-radio v-model="answerOption.multipleRule" label="1">
                            <span class="radio_title">给分规则1：</span>全对得满分，少选得
                            <el-input 
                                v-model="ruleOneScore" 
                                class="radio_score" 
                                maxlength="3"
                                @input="ScoreChange('ruleOneScore')"
                            ></el-input>分，选错不得分。
                        </el-radio>
                    </div>
                    <div class="radio_group_socre">
                        <el-radio v-model="answerOption.multipleRule" label="2">
                            <span class="radio_title">给分规则2：</span>全对得满分，选对1个
                            <el-input 
                                v-model="ruleTwoScore1" 
                                @input="ScoreChange('ruleTwoScore1')" 
                                maxlength="3"
                            ></el-input>分，
                            选对2个
                            <el-input 
                                v-model="ruleTwoScore2" 
                                @input="ScoreChange('ruleTwoScore2')" 
                                maxlength="3"
                            ></el-input>分，
                            选对3个
                            <el-input 
                                v-model="ruleTwoScore3" 
                                @input="ScoreChange('ruleTwoScore3')" 
                                maxlength="3"
                            ></el-input>分，选错不得分
                        </el-radio>
                    </div>
                    <div class="radio_group_long_input">
                        <el-radio v-model="answerOption.multipleRule" label="3">
                            <span class="radio_title">给分规则3：</span>
                            <el-input 
                                placeholder="A=1，B=2，C=3" 
                                v-model="ruleThreeStr"
                                class="input_long_200"
                            ></el-input>
                        </el-radio>
                    </div>
                </div>
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="ConfirmEnter()">确 定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';

const emit = defineEmits(['answerEnter']);

const dialogVisible = ref(false);
const title = ref('编辑');
const formRef = ref(null);

const mulAnswerList = ref([]); // 多选答案

const answerList = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K']; // 答案列表

// 标准答案编辑对象数据
const answerOption = reactive({
    examSubjectId: '', // 考试科目id
    fullScore: 0, // 满分
    id: '', // id 修改id
    multipleRule: '', // 多选规则 类型 1 2 3
    multipleRuleDesc: null, // 多选题给分分布
    optionsSize: 4, // 答案数量
    standardAnswer: "", // 标准答案
    questionName: "", // 题目名称
    questionType: "1", // 题目类型 1 单选 2多选 3判断
});

// 给分规则输入框
const ruleOneScore = ref(0);
const ruleTwoScore1 = ref(0);
const ruleTwoScore2 = ref(0);
const ruleTwoScore3 = ref(0);
const ruleThreeStr = ref('');

// 初始化数据
const InitData = (item) => {
    Object.assign(answerOption, {
        examSubjectId: item.examSubjectId,
        fullScore: item.fullScore, // 满分
        id: item.id,
        multipleRule: item.multipleRule,
        multipleRuleDesc: item.multipleRuleDesc,
        optionsSize: item.optionsSize,
        standardAnswer: item.standardAnswer,
        questionName: item.questionName,
        questionType: item.questionType,
    });

    console.log("打印编辑对象", answerOption);

    if (item.multipleRule == '1') {
        ruleOneScore.value = item.multipleRuleDesc || 0;
    } else if (item.multipleRule == '2') {
        const parts = item.multipleRuleDesc?.split(",") || [];
        ruleTwoScore1.value = parts[0] || 0;
        ruleTwoScore2.value = parts[1] || 0;
        ruleTwoScore3.value = parts[2] || 0;
    } else {
        ruleThreeStr.value = item.multipleRuleDesc || "";
    }

    const answerStr = item.standardAnswer?.replace(/\s+/g, '') || '';
    mulAnswerList.value = answerStr.includes(',') ? answerStr.split(',') : answerStr.split('');
    
    dialogVisible.value = true;
};

// 少选分数验证
const ScoreChange = (valueKey) => {
    let val = 0;
    if (valueKey === 'ruleOneScore') val = ruleOneScore.value;
    else if (valueKey === 'ruleTwoScore1') val = ruleTwoScore1.value;
    else if (valueKey === 'ruleTwoScore2') val = ruleTwoScore2.value;
    else if (valueKey === 'ruleTwoScore3') val = ruleTwoScore3.value;

    if (val > answerOption.fullScore) {
        if (valueKey === 'ruleOneScore') ruleOneScore.value = 0;
        else if (valueKey === 'ruleTwoScore1') ruleTwoScore1.value = 0;
        else if (valueKey === 'ruleTwoScore2') ruleTwoScore2.value = 0;
        else if (valueKey === 'ruleTwoScore3') ruleTwoScore3.value = 0;
        
        ElMessage.warning('分数不能大于满分!');
    }
};

// 多选题答案选择事件
const MulAnswerChange = () => {
    console.log("打印多选题答案", mulAnswerList.value);
    answerOption.standardAnswer = mulAnswerList.value.toString(); // 默认的是英文逗号
    console.log("answerOption", answerOption);
};

// 题目类型切换事件
const TypeChange = () => {
    // 单选题
    if (answerOption.questionType == 1) {
        answerOption.multipleRuleDesc = "";
        answerOption.multipleRule = "";
        answerOption.standardAnswer = "";
    } 
    // 多选
    else if (answerOption.questionType == 2) {
        answerOption.multipleRuleDesc = "";
        answerOption.multipleRule = "1"; // 给分规则默认1
        answerOption.standardAnswer = "";
        mulAnswerList.value = [];
    } 
    // 判断题
    else if (answerOption.questionType == 3) {
        answerOption.multipleRuleDesc = "";
        answerOption.multipleRule = "";
        answerOption.standardAnswer = "";
    }
    console.log("切换题目类型打印", answerOption);
};

// 确定弹窗
const ConfirmEnter = () => {
    // 给分规则1
    if (answerOption.multipleRule == '1') {
        answerOption.isMul = true;
        answerOption.multipleRuleDesc = ruleOneScore.value || 0;
    } 
    // 给分规则2
    else if (answerOption.multipleRule == '2') {
        answerOption.isMul = true;
        answerOption.multipleRuleDesc = `${ruleTwoScore1.value},${ruleTwoScore2.value},${ruleTwoScore3.value}`;
    }
    // 给分规则3
    else if (answerOption.multipleRule == '3') {
        // 这里需要做下处理 this.ruleThreeStr 里的逗号需要转义成英文的逗号
        answerOption.multipleRuleDesc = ruleThreeStr.value.replace(/，/g, ',');

        if (validateMultipleQuestionsName(answerOption.multipleRuleDesc)) {
            answerOption.isMul = true;
        } else {
            ElMessage.warning('请填写正确的格式!');
            return;
        }
    }

    emit('answerEnter', { ...answerOption });
    dialogVisible.value = false;
};

// 校验格式是否为 字母=内容,字母=内容 的格式
const validateMultipleQuestionsName = (value) => {
    console.log("校验格式", value);
    // 如果为空，直接返回true（或根据业务需求决定）
    if (!value || value.trim() === '') {
        return true;
    }
    // 分割成各个部分
    const parts = value.split(',');
    // 检查每个部分是否符合 字母=内容 的格式
    for (let part of parts) {
        // 去掉首尾空格
        part = part.trim();
        
        // 检查是否符合 字母=内容 的格式（支持多个字母）
        if (!/^[A-Za-z]+=.+$/.test(part)) {
            return false;
        }
    }
    return true;
};

// 暴露方法供父组件调用
defineExpose({
    InitData
});
</script>

<style lang="scss" scoped>
/* 保持原有样式 */
</style>