<!-- 题目配置 -->

<template>
    <div class="test_question_config">
        <Form
            :v-model:formRef="formRefDom"
            :form-item-list="finalFormItemList"
            :default-form-data="questionFormData"
            @form-item-change="HandleFormItemChange"
            labelWidth="92px"
        >
            <template #questionType>
                <div class="question_type">
                    <!-- 题目类型下拉 -->
                    <el-select   
                        v-model="questionFormData.questionType" 
                        class="type_select"
                        @change="(val)=>HandleFormItemChange({key:'question_type',val,formData:questionFormData})"
                        placeholder="请选择">
                        <el-option
                            v-for="selectItem in questionTypeOptions"
                            :key="selectItem.value"
                            :label="selectItem.label"
                            :value="selectItem.value"
                        />
                    </el-select>

                    <!-- 题目额外 展示配置 -->
                    <el-checkbox-group  
                        class="type_cofig_check"
                        v-model="questionFormData.extraConfig"
                    >
                        <el-checkbox 
                            v-for="checkItem in questionConfig" 
                            :key="checkItem.value"
                            :label="checkItem.label"
                            :value="checkItem.value"
                        />
                    </el-checkbox-group>
                </div>
            </template>

            <template #evaluationType="{formData}">
                <div class="score_reviewType">
                    <el-radio-group v-model="questionFormData.evaluationType">
                        <el-radio v-for="radioItem in scoreReviewTypeList" :key="radioItem.value" :value="radioItem.value">{{ radioItem.label }}</el-radio>
                    </el-radio-group>

                    <ul class="num_score" v-if="Number(formData.evaluationType) === 0 && Number(formData.questionScore)">
                        <li v-for="value in Number(formData.questionScore)">
                            {{ value }}分
                        </li>
                    </ul>
                    <div class="star_score" v-else-if="Number(formData.evaluationType) === 1 && Number(formData.questionScore)">
                        非常不满意
                        <el-rate size="large" 
                            :model-value="0" 
                            :disabled="true" 
                            disabled-void-color="#c6d1de" 
                            disabled-void-icon="Star" 
                            :max="Number(formData.questionScore)" 
                            clearable />
                        非常满意
                    </div>
                    <div class="null_score" v-else>
                        未查询到结果,请至题目分值处设置分值
                    </div>
                </div>
            </template>


            <template #options="{ formData }">
                <div class="options_list_container">
                    <div v-for="(option,index) in formData.options" :key="option.id" class="option_item">
                        
                        <div class="input_option">
                            <el-input 
                                v-model="option.content" 
                                placeholder="请输入选项内容" 
                            />
                            <!-- 统计题 -->
                            <template v-if="displayMode === 'statistic'">
                                <el-icon v-if="Number(questionFormData.questionType) === 0 && Number(index) > 1 ||
                                               Number(questionFormData.questionType) === 1 && Number(index) > 2  "
                                    class="delete_icon" 
                                    @click="removeOption(option.id)"
                                >
                                    <Close/>
                                </el-icon>
                                <div class="blank_icon"  v-else></div>
                            </template>
                            
                        </div>
                        <!-- 得分题 -->
                        <div v-if="displayMode === 'scored'" class="score_option">
                            <span class="row_label">选项分值：</span>
                            <el-input 
                                @change="(val)=>HandleInputNumberChange(val,option)"
                                :step="0.01"
                                type="number"
                                v-model="option.score" 
                                placeholder="请输入分值" 
                            />
                            <el-icon  v-if="Number(questionFormData.questionType) === 3 && Number(index) > 1"
                                class="delete_icon" 
                                @click="removeOption(option.id)"
                            >
                                <Close/>
                            </el-icon>
                            <div class="blank_icon"  v-else></div>
                        </div>

                    </div>
                </div>
                
                <div class="add_option_area">
                    <el-button type="primary" link @click="addOption">
                        <el-icon><CirclePlus /></el-icon>
                        添加选项
                    </el-button>
                </div>
            </template>

            <template #submit="{formRef,formData}">
                <div class="action_bar">
                    <el-button class="button_background" @click="HandleAddConfirm({formRef,formData})">确定</el-button>
                    <el-button class="button_refresh" @click="HandleCancel({formRef,formData})">取消</el-button>
                </div>
            </template>
        </Form>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { Close, CirclePlus } from '@element-plus/icons-vue'
import Form from '@/baseComponents/Form.vue'

import { questionFormItemList } from './form'
import {
    statisticQuestionType, scoredQuestionType
} from './questionTypeList'
import { ElMessage } from 'element-plus'

type DisplayMode = 'scored' | 'statistic'

interface Option {
    content: String
    score?: String
    id?: Number | String
}

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

const props = defineProps({
    displayMode: {     // 展示形式  带分值 scored 不带分值 statistic
        type: String as () => DisplayMode,
        default: 'statistic',
        required:true,
    },
    defaultFormData:{
        type:Object as ()=> FormData,
    }
})
const emit = defineEmits(['confirm', 'cancel', 'formChange'])

const formRefDom = ref()

// 试题题目信息 
const questionFormData = ref<FormData>({
    questionTitleName: '',  
    questionScore: '',   
    questionType: '', 
    extraConfig: [],  //默认勾选必答题
    options: [],
    evaluationType:0  //默认展示 数字式
 })



/*
  监听 props.displayMode  展示 不同的 题型配置 和 试卷配置 
*/
// 题型选项配置 监听 动态切换
const questionTypeOptions = computed(() => {
    if (props.displayMode === 'scored') {
        return [...scoredQuestionType.value]
    } else {
        return  [... statisticQuestionType.value]
    }
})
// 表单试题 展示项配置  监听 表单元素 动态显隐
const finalFormItemList = computed(() => {
    return questionFormItemList.value.map(item => {
        const newItem = { ...item }
        // 题目分值仅在 scored 模式显示
        if (item.key === 'questionScore') {
            newItem.hidden = props.displayMode !== 'scored'
            newItem.rules = Number(questionFormData.value?.questionType)  === 3 ?
            [
                {required:true,message:'请填写信息', trigger:'blur' },
                {
                    // 允许整数或最多两位小数的数字
                    pattern: /^\d+(\.\d{1,2})?$/,
                    message: '请输入有效的数值，且最多保留两位小数',
                    trigger: 'blur'
                }
            ] : (Number(questionFormData.value?.questionType)  === 5  ? [
                    {required:true,message:'请填写信息', trigger:'blur' },
                    {
                        // 允许整数数字
                        pattern: /^\d+$/,
                        message: '请输入整数',
                        trigger: 'blur'
                    }
                ] : [])

        }else if(item.key == 'options'){
            // 评价题  和 问答题 不展示 题目子选项配置
            newItem.hidden = [2,5].includes(Number(questionFormData.value.questionType))  
        }else if(item.key == 'evaluationType'){
            // 评价题 展示评分的格式
            newItem.hidden = Number(questionFormData.value.questionType) !== 5
        }
        return newItem
    })
})


// 试题额外配置项   // 评价题 和 问答题 展示不同的配置项
const questionConfig = computed(()=>{
    // 评价题 和 问答题
    if([2,5].includes(Number(questionFormData.value.questionType)) ){
        return [
            { label: '必答题', value: 'required' },
        ]
    }else{
        return [
            { label: '必答题', value: 'required' },
            { label: '选项横排', value: 'isHorizontal' }
        ]
    }
})

// 评价题 评分形式 列表
const scoreReviewTypeList = ref([
    {label:'数字式',value:0},
    {label:'星星式', value:1},
])



//最多保留两位小数 
const HandleInputNumberChange = (val,option)=>{
    console.log('输入的值---',val)
    if(String(val).split('.')[1]?.length > 2){
        let splitArray =  String(val).split('.')
        option.score = Number(splitArray[0] +'.' + splitArray[1].slice(0,2))
    }
}

// 表单内部某些变化 触发 的操作
const HandleFormItemChange = (params: any) => {
    const { key, val, formData: data } = params
    // console.log('表单项目变化了--',formData)
    emit('formChange', params)
}

// 添加题目选项配置
const addOption = () => {
    questionFormData.value.options.push({ 
        content: '', score: '',
        // 这个会有重复的可能 ——绑定时间 确保唯一
         // 绑定时间戳，保证临时id唯一
        id:`tmp_${new Date().getTime()}_${questionFormData.value.options.length + 1}`
    })
}
// 删除题目选项配置
const removeOption = (id: number) => {
    questionFormData.value.options = questionFormData.value.options.filter((opt)=>{
        return opt.id !== id
    })
}

// 题目信息校验 并传递信息给父级
const HandleAddConfirm = async (params:any)=>{
    const {formRef,formData} = params
    if (!formRef) return
    await formRef.validate(async(valid) => {
        if (valid) {
            // 要判断添加的选项是否有没有填写完的
            console.log('传递的表单数据---',formData)
            if(formData?.options?.length > 0){
                // 有选项
                let isOptNameFinished = true
                let isScoreFinished = true
                formData?.options.map(opt=>{
                    if(!opt.content){
                        isOptNameFinished = false
                    }
                    if(props.displayMode === 'scored' && !(opt.score || opt.score === 0)){
                        isScoreFinished = false
                    }
                })
                if(!isOptNameFinished){
                    ElMessage.warning('请确保选项内容不为空')
                    return
                }
                if(!isScoreFinished){
                     ElMessage.warning('请确保选项分值不为空')
                    return
                }
            }
            emit('confirm', {formData:formData,formRef})
        }
    }).catch(err=>{
        console.log('报错信息',err)
    })
}

const HandleCancel =  async (params:any)=>{
    const {formRef} = params
    formRef.resetFields()
    emit('cancel')
}

// 同步监听 1
watch(()=>props.defaultFormData,(newVal)=>{
    // 赋值除了类型之外的其他值
    console.log('监听到赋值了',newVal)
    if (newVal) {
        // 避免首次赋值选项置空的情况 _ 待完善 _ 可能发生
        questionFormData.value = newVal
    }
},{deep:true, immediate:true})


</script>

<style lang="scss" scoped>
.test_question_config {
    padding: 20px;
    background-color: #F8FAFE;
}


.question_type{
    display: flex;
    gap:32px;
    align-items: center;
    width: 100%;
    .type_select{
        width: 200px;
    }
}

.score_reviewType{
    display: flex;
    flex-direction: column;

    .num_score,
    .star_score,
    .null_score
    {
        display: flex;
        align-items: center;
        gap:16px;
        color: #CCCCCC;
        line-height: 1;
    }
    .num_score{
        flex-wrap: wrap;
        li{
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: 4px ;
            border: 1px solid #CCCCCC;
            width: 44px;
            height: 32px;
            font-size: 14px;
            background-color: white;
        }
    }

    .star_score{
        word-break: keep-all;
        .el-rate{
            display: flex;
            flex-wrap: wrap;
            gap:10px 20px;
            height: auto;
        }
    } 


}

// 选项列表样式
.options_list_container {
    width:100% ;
    display: flex;
    flex-direction: column;
    gap: 16px;
    margin-bottom: 16px;

    .option_item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 16px;

        .input_option{
            width:60% ;
            display: flex;
            align-items: center;
            padding-left: 92px;
            .blank_icon{
                margin-left: 20px;
                width: 20px !important;
                height: 20px;
            }


        }
        .score_option{
            width: 35%;
            display: flex;
            align-items: center;

            .row_label {
                color: #999999;
                font-size: 14px;
                flex-shrink: 0;
            }

            .blank_icon{
                margin-left: calc(20px + 6px);
                width: 20px !important;
                height: 20px;
            }
        }

        .input_option,
        .score_option{
            .delete_icon {
                font-size: 20px;
                color: #c0c4cc;
                cursor: pointer;
                margin-left: 20px;
                width: 20px !important;
                height: 20px;
                &:hover {
                    color: #f56c6c;
                }
            }
            
        }
    }
}

// 添加选项按钮
.add_option_area {
    margin-left: 92px;
}

// 底部操作栏
.action_bar {
    margin-left: 75px;
    display: flex;
    gap:20px;
    .el-button {
        margin:0;
        padding:10px 36px;
        height: 40px;
    }
}

// 表单项样式
:deep(.el-form) {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    gap: 16px 0;

    .el-form-item {
        margin: 0px;
        &.custom_itm {
            width: 100%;
            .el-form-item__content{
                display: flex;
                flex-direction: column;
                align-items: flex-start;
            }
        }

        &.percent_70 {
            width: 60%;
        }

        &.percent_30 {
            width: 35%;
        }
    }
}
</style>
