<template>
     <div class="main_container hide_scrollbar">
        <!-- 顶部科目选择区域 -->
        <div class="section" v-if="electiveFormItm?.label">
            <div class="section_title">{{electiveFormItm?.label}}:</div>
            <el-checkbox-group  
                v-model="selectedElectives"
                class="check_group_btn_list"
                @change="(val)=>handleSelectChange(val)">
                <el-checkbox-button 
                    v-for="checkItem in electiveFormItm?.selectList" 
                    :key="checkItem.value"
                    :label="checkItem.label"
                    :value="checkItem.value"/>
            </el-checkbox-group>
        </div>

        <!-- 非选科班级列表 -->
        <template v-for="sub in noElectiveTeachingSubjectFormItms" :key="sub.key">
            <div class="section">
                <div class=" section_title">{{ sub.label }}:</div>
                <el-radio-group 
                    v-model="selectedTeachingClass[sub.key]" 
                    class="radio_group_list">
                    <el-radio v-for="classItm in sub.selectList" :key="classItm.value" :value="classItm.value">
                        {{ classItm.label }}
                    </el-radio>
                </el-radio-group>
            </div>
        </template>

        <!-- 动态渲染选科的班级列表区域 -->
        <template v-for="sub in electiveTeachingSubjectFormItms" :key="sub.key">
            <div class="section">
                <div class=" section_title">{{ sub.label }}:</div>
                <el-radio-group 
                    v-model="selectedTeachingClass[sub.key]" 
                    class="radio_group_list">
                    <el-radio v-for="classItm in sub.selectList" 
                            :key="classItm.value" 
                            :value="classItm.value">
                        {{ classItm.label }}
                    </el-radio>
                </el-radio-group>
            </div>
        </template>
        <!-- 底部确认按钮 -->
        <div class="bottom_action_bar">
            <el-button class="button_background" @click="HandleConfirm">确认</el-button>
        </div>
    </div>


</template>

<script setup lang="ts">
import { onMounted, ref,computed } from 'vue';
import { useRouter } from 'vue-router';
import {getEvaluationSubjectApi, saveEvaluationSubjectApi} from '@/api/questionnaireTaskListPage'
import { ElMessage } from 'element-plus';


interface FormItm  {
    key: String,
    label: String,
    type?:string,
    rules?: any[],
    hidden?: Boolean,
    custom:Boolean,
    style: Record<string, any>,
    selectList?: { label: string, value: any }[] | [],
}


const router = useRouter()

// 存储 获取到的选科 和教学班数据
const electiveFormItm = ref<FormItm|null>({})   // 选科 form项配置
const noElectiveTeachingSubjectFormItms = ref<FormItm[]>([])   // 非选科 教学班form项配置
const electiveSubjectClassData = ref([])   // 所有的选科教学班数据  ————后续动态过滤
const electiveTeachingSubjectFormItms = ref<FormItm[]>([])   // 选科 教学班form项配置 _动态变量

const electiveNeedCount = ref(0)  //选科的必选数量

// 存储选中的 选科/班级   项目
const selectedElectives = ref<string[]>([])  // 选中的选科项
const selectedTeachingClass = ref<Record<string,string[]>>({}) // 选中的教学班 班级项

// 切换科目选中状态
const handleSelectChange = (val)=>{
    // 先要限制科目数量
    // if(val.length >2){
    //     selectedElectives.value.splice(0, val.length- 2)
    // }
    
    // 动态的 选科 科目班级  配置（展示）项列表
    let finalElectiveTeachingSubjectData = LoadDynamicElectiveSubjectClass(val)
    // // 动态变更 教学班选项的信息
    electiveTeachingSubjectFormItms.value = finalElectiveTeachingSubjectData
}



// 点击确认
const HandleConfirm = async () => {
    // 最终提交只保留 展示的项
    let exitstSelectedKeys = Object.keys(selectedTeachingClass.value)
    let fixedKeys= noElectiveTeachingSubjectFormItms.value?.map(item=>item.key)
    let deleteKeys = exitstSelectedKeys.filter(key=>{
        return !(fixedKeys.includes(key) || selectedElectives.value.includes(key))
    })
    // 删除不在页面上展示的已选中班级项
    deleteKeys.map(item=>{
        delete selectedTeachingClass.value[item]
    })

    // 添加选科校验
    let evaluationClassIds = Object.values(selectedTeachingClass.value)
    if(selectedElectives.value.length > electiveNeedCount.value){
        ElMessage({
            message:`选科数量最多为${electiveNeedCount.value}个`,
            type: 'warning',
            customClass:'app_el_message',
        })
        return
    }else if(selectedElectives.value.length < electiveNeedCount.value){
        ElMessage({
            message:`选科数量最少为${electiveNeedCount.value}个`,
            type: 'warning',
            customClass:'app_el_message',
        })
        return 
    }
    if(evaluationClassIds.length < (noElectiveTeachingSubjectFormItms.value.length + electiveTeachingSubjectFormItms.value.length)){
        ElMessage({
            message:'请确保选科班级填写完整',
            type: 'warning',
            customClass:'app_el_message',
        })
        return
    }

    // 保存选科
    let transferParams = {
        evaluationSubjectIds:selectedElectives.value,
        evaluationClassIds
    }
    let res = undefined
    try{
        res = await saveEvaluationSubjectApi(transferParams)
    }catch{}
    if(res?.code == 200){
        router.push('/app/selfQuestionnaireProcess')
    }
};


// 动态加载 不定项选科数据
const LoadDynamicElectiveSubjectClass = (selectedSubject:string[])=>{
    // 动态的 选科 科目班级  配置（展示）项列表
    return electiveSubjectClassData.value?.filter(item=>{
        return selectedSubject.includes(item.evaluationSubjectId)
    })?.map(subjectMsg=>{
        let classOpts = subjectMsg?.classData?.map(classItm=>{
            return {label:classItm.name, value:classItm.evaluationClassId}
        }) || []
        return {
            key: subjectMsg.evaluationSubjectId,
            label: subjectMsg.subjectName,
            type:'radio',
            rules:[
                {required:true,trigger:'blur',message:'请选择'}
            ],
            hidden:false,
            custom:false,
            style:{},
            selectList:classOpts,
        }
    }) || []
}


onMounted( async()=>{
    console.log('加载了')
    let res = await getEvaluationSubjectApi()
    if(res?.code == 200){
        const {classData, subjectData,needCount,selectionCount,selectionStatus } = res.data

        // 1.  选科数据 配置项
        let electiveSubjectOptions = subjectData?.map(item=>{
            return {
                label:item.name,
                value:item.evaluationSubjectId
            }
        }) || []
        // 默认选中的选科数据
        selectedElectives.value = subjectData?.filter(subject=>{
            return subject.usedStatus    // 是否选中，false-否，true-是
        }).map(itm=>{
            return itm.evaluationSubjectId
        })


        // 选科表单项配置
        electiveNeedCount.value = needCount
        // selectionStatus 选科状态，0-未勾选，1-已勾选
        if(selectionStatus == 1){
            electiveFormItm.value = {
                key: 'electiveSubject',
                label: `选择科目（${selectionCount}选${needCount}）`,
                type:'checkboxButton',
                rules:[
                    {required:true,trigger:'blur',message:'请选择'}
                ],
                hidden:false,
                custom:false,
                style:{},
                selectList:electiveSubjectOptions,
            }
        }else{
            electiveFormItm.value = null
        }


        // 2. 教学班数据
        // 分为在选科中的和不在选科中的
        // （1）非选科的 科目教学班数据
        const noElectiveSubjectClassData = classData.filter(item=>{
            return item.subjectStatus === 0
        })
         // 非选科的 科目教学班配置项列表
        noElectiveTeachingSubjectFormItms.value = noElectiveSubjectClassData.map(subjectMsg=>{
            let classOpts = subjectMsg?.classData?.map(classItm=>{
                return {label:classItm.name, value:classItm.evaluationClassId}
            }) || []

            return {
                key: subjectMsg.evaluationSubjectId,
                label: subjectMsg.subjectName,
                type:'radio',
                rules:[
                    {required:true,trigger:'blur',message:'请选择'}
                ],
                hidden:false,
                custom:false,
                style:{},
                selectList:classOpts,
            }
        })


        // （2）选科 的科目教学班数据
        electiveSubjectClassData.value = classData?.filter(item=>{
            return item.subjectStatus === 1
        }) || []


        //（3） 每个科目的默认选中班级赋值
        classData?.map(subjectClass=>{
            let selectedClass = subjectClass.classData.find(classItm=>{
                return classItm.usedStatus
            })?.evaluationClassId
            selectedTeachingClass.value[subjectClass.evaluationSubjectId] = selectedClass
        })



        // 3. 最终的教学班配置项列表

        let initFormItm = []

        if(electiveFormItm.value){
            initFormItm.push(electiveFormItm.value)
        }
        if(noElectiveTeachingSubjectFormItms.value.length > 0){
            initFormItm.push(...noElectiveTeachingSubjectFormItms.value)
        }

        // 获取需要加载的 动态数据
        let finalElectiveTeachingSubjectData = LoadDynamicElectiveSubjectClass(selectedElectives.value)
        electiveTeachingSubjectFormItms.value = finalElectiveTeachingSubjectData
    }
})


</script>



<style lang="scss" scoped>
.main_container {
    display: flex;
    flex-direction: column;
    gap:calc(32 * var(--app-rpx));

    background-color: #ffffff !important;

    // 浏览器端的底部 工具栏高度   90 * var(--app-rpx))
    // 手机微信 工具栏高度  不影响 __ 待完善
    padding:calc(30 * var(--app-rpx)) 
            calc(19 * var(--app-rpx)) 
            // calc((84 + 90 + 20) * var(--app-rpx)) !important; /* 为底部按钮留出空间 */
            calc((90) * var(--app-rpx)) !important; /* 为底部按钮留出空间 */
    > * {
        flex-shrink: 0;
    }
}

.section{
    .section_title {
        font-weight: 600;
        color: #000000;
        font-size: calc(16 * var(--app-rpx));
        margin-bottom: calc(16 * var(--app-rpx));
    }
}

.check_group_btn_list{
    display: flex;
    flex-wrap: wrap;
    gap:calc(16 * var(--app-rpx));

    :deep(.el-checkbox-button){
        .el-checkbox-button__inner{
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius:calc(4 * var(--app-rpx));
            border:solid #dcdfe6 calc(1 * var(--app-rpx));
            width: calc(72 * var(--app-rpx));
            height: calc( 40 * var(--app-rpx));
            font-size:calc( 16 * var(--app-rpx));
            &:hover {
                color: #666666;
            }
        }
        &.is-focus{
        .el-checkbox-button__inner{
            border:solid #dcdfe6 calc(1 * var(--app-rpx));
        }
        }
        &.is-checked{
        .el-checkbox-button__inner{
            background: #2E64FA;
            border: calc(1 * var(--app-rpx)) solid  #2E64FA;
            color: #fff;
            &:hover {
            background: #2E64FA;
            }
        }
        }
    }
}

.radio_group_list{
    display: flex;
    flex-wrap: wrap;
    gap:calc(12 * var(--app-rpx));
    :deep(.el-radio){
        margin:0;
        .el-radio__inner{
            width: calc(14 * var(--app-rpx));
            height: calc(14 * var(--app-rpx));
            &::after{
                width: calc(4 * var(--app-rpx));
                height: calc(4 * var(--app-rpx));
            }
        }
        .el-radio__label{
            min-width: calc(80 * var(--app-rpx));
            font-size:calc(14 * var(--app-rpx));
            color: #666666;
        }
    }
}


/* --- 底部按钮 --- */
.bottom_action_bar {
    flex: 1 1;
    display: flex;
    align-items: flex-end;
    width: 100%;
    background-color: #fff;
    padding: calc(8 * var(--app-rpx)) 0 calc(20 * var(--app-rpx));
    box-sizing: border-box;
        
    .button_background {
        width: 100%;
        height: calc(44 * var(--app-rpx));
        border-radius: calc(4 * var(--app-rpx));
        font-size: calc(16 * var(--app-rpx));
    }
}

</style>