<template>
    <FormDialog class="select_subject_form_dialog" width="760px" 
        :defaultFormData="defaultFormData" 
        :submitLoading="formSubmitLoading"
        :title="formTitle" :visible="formVisible"
        :formItemList="formItemList"
        @formItemChange="HandleFormChange"
        @close="CloseFormDialog"
        @confirm="ConfirmFormDialog"
        >
    </FormDialog>
</template>


<script setup lang="ts">
import { onMounted, ref } from 'vue';

import FormDialog from '@/baseComponents/FormDialog.vue';
import {formItemList} from './formDialog'

import {getEvaluationSubjectApi,saveEvaluationSubjectApi} from '@/api/questionnaireTaskListPage'

const emit = defineEmits(['confirm'])


// 存储 获取到的选科 和教学班数据
const electiveFormItm = ref()   // 选科 form项配置
const electiveNeedCount = ref(0)   //选科必选数量

const noElectiveTeachingSubjectFormItms = ref([])   // 非选科 教学班form项配置
const electiveSubjectClassData = ref([])   // 所有的选科教学班数据  ————后续动态过滤

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


// 选择科目/班级弹窗
const formVisible = defineModel('formVisible')
const defaultFormData = ref({})
const formSubmitLoading = ref(false)
const formTitle = ref('选择科目班级')

const CloseFormDialog = ()=>{
    formVisible.value = false
}
const ConfirmFormDialog = async (params)=>{
    formSubmitLoading.value = true
    const {formData,formRef} = params
    console.log('提交的表单信息---',formData)

    // 教学班的班级数据
    let subjectClassObj = {...formData}
    delete subjectClassObj.electiveSubject


    // 删除不在页面上展示的数据
    let exitstSelectedKeys = Object.keys(subjectClassObj)  //已勾选的班级选中
    let fixedKeys= noElectiveTeachingSubjectFormItms.value?.map(item=>item.key)  // 必须勾选的班级选中
    let existElectiveSubject = formData.electiveSubject   // （展示）的可选科目
    let deleteKeys = exitstSelectedKeys.filter(key=>{
        return !(fixedKeys.includes(key) || existElectiveSubject.includes(key))
    })
    // 删除不在页面上展示的已勾选班级项
    deleteKeys.map(item=>{
        delete subjectClassObj[item]
    })
    
    let evaluationClassIds = Object.values(subjectClassObj)  // 最终传递的 选科班级 ids
    let evaluationSubjectIds = formData.electiveSubject   // 选中的选科 ids



    // 保存表单信息
    let transferParams = {
        evaluationSubjectIds,
        evaluationClassIds
    }
    let res = undefined
    try{
        res = await saveEvaluationSubjectApi(transferParams)
    }catch{}
    if(res?.code == 200){
        CloseFormDialog()
        emit('confirm')
    }
    formSubmitLoading.value = false
}



// 动态加载 不定项选科数据
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,
        }
    }) || []
}

const HandleFormChange = (params)=>{
    const {key,val,formData} = params
    if(key == 'electiveSubject'){
        console.log('触发的变化',key,val)

        // 数量不定
        // 先要限制科目数量
        // if(val.length > electiveNeedCount.value){
        //     formData[key].splice(0, val.length- electiveNeedCount.value)
        // }
        // 动态的 选科 科目班级  配置（展示）项列表
        let finalElectiveTeachingSubjectData = LoadDynamicElectiveSubjectClass(val)
       
        // 动态变更 教学班选项的显示隐藏
        formItemList.value = electiveFormItm.value ? [
            electiveFormItm.value,
            ...noElectiveTeachingSubjectFormItms.value,
            ...finalElectiveTeachingSubjectData
        ] : noElectiveTeachingSubjectFormItms.value
    }
}

// 数组长度校验
const validateArrayLength = (limitLength:number)=> (rule, value, callback) => {
    // value 即为绑定的数组
    if (!value || value.length === 0) {
        return callback(new Error('请至少选择一项'));
    }
    if (value.length < limitLength) {
        return callback(new Error(`最少需要选择${limitLength}项`));
    }
    if (value.length > limitLength) {
        return callback(new Error(`最多只能选择${limitLength}项`));
    }
    // 校验通过
    callback();
};

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:'change',message:'请选择'},
                    { validator: validateArrayLength(needCount), trigger: 'change' }     // 长度校验
                ],
                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)
        formItemList.value = [...initFormItm,...finalElectiveTeachingSubjectData]
    
        console.log('默认选中的选科数据',selectedElectives.value)
        console.log('默认选中的班级数据',selectedTeachingClass.value)

        defaultFormData.value.electiveSubject = selectedElectives.value
        defaultFormData.value = {...defaultFormData.value,...selectedTeachingClass.value}
    }
})

</script>



<style lang="scss" scoped>

.select_subject_form_dialog{
    :deep(.el-dialog){
        margin:0 !important;
        top: 50% !important;
        left: 50% !important; /* 若需水平居中可加上此行 */
        transform: translate(-50%, -50%); /* 核心：基于自身宽高反向偏移 */
    }

    :deep(.el-dialog__body){
        min-height: 450px !important;
        max-height: 450px !important;
        padding:20px;
    }

    :deep(.el-form){
        .el-form-item .el-form-item__label{
            font-size: 14px;
            color: #000000;
        }
        .el-form-item{
            margin-right:0;
        }
    }
}
</style>