<template>
    <div class="page_item   end_item">
        <div class="page_search">
            <div class="search_content">
                <div class="content_left">
                    <el-checkbox v-model="evaluationManageData.isGenerateAccountByGender"  
                        @change="(val)=>GenerateAccountByGenderOrNot(val)" >
                        按男女生成
                    </el-checkbox>
                </div>
                <div class="content_right">
                    <el-button  class="delete_button_border_no_bg" @click="ClearReviewAccount">全部清空</el-button>
                    <el-button  class="button_border" @click="OpenBatchEditForm">批量编辑</el-button>
                    <el-button  class="button_refresh" @click="">批量导出</el-button>
                    <el-button  class="button_refresh" @click="">批量导入</el-button>
                    <el-button  class="button_background" @click="GoToGenerateCodePage">生成评价码</el-button>
                </div>
            </div>
        </div>
        <div class="page_jg_20"></div>
        <Table 
            :currentPage="1" :pageSize="200"
            :tableColumns="tableColumns" 
            :tableData="tableData"
            :totalNum="0"
            :hidePagination="true"
        >
            <template v-for="item in Object.values(originReviewAccount)" 
                v-slot:[`class_${item.evaluationGradeId}`]="{row}" :key="item">
                {{ row[`class_${item.evaluationGradeId}`]?.className }}
            </template>

            <template v-for="item in Object.values(originReviewAccount)" 
                    v-slot:[`num_${item.evaluationGradeId}`]="{row}" :key="item">
                    <!-- 没有班级的行不渲染 -->
                <el-input v-if="row[`class_${item.evaluationGradeId}`]?.classId"  type="number"  v-model="row[`num_${item.evaluationGradeId}`]"   placeholder="请输入"/>
            </template>

            <template v-for="item in Object.values(originReviewAccount)" 
                v-slot:[`male_${item.evaluationGradeId}`]="{row}" :key="item">
                <el-input  v-if="row[`class_${item.evaluationGradeId}`]?.classId"  type="number"  v-model="row[`male_${item.evaluationGradeId}`]"   placeholder="请输入"/>
            </template>

            <template v-for="item in Object.values(originReviewAccount)" 
                    v-slot:[`female_${item.evaluationGradeId}`]="{row}" :key="item">
                <el-input v-if="row[`class_${item.evaluationGradeId}`]?.classId"   type="number"  v-model="row[`female_${item.evaluationGradeId}`]"   placeholder="请输入"/>
            </template>
        </Table>

        <FormDialog 
            width="800px"
            :visible="batchEditFormVisible" :defaultFormData="{}" 
            title="批量编辑" :submitLoading="batchEditFormLoading"
            @close="CloseBatchEditForm" 
            @confirm="SaveBatchEditForm">

            <template #form_pre>
                <ul class="grade_form_item">
                    <li v-for="grade in batchEditGradeList" :key="grade.evaluationGradeId">
                        <div class="grade_name">{{ grade.evaluationGradeName }}</div>
                        <div class="class_list">
                            <el-checkbox
                                v-model="grade.isSelectAll"
                                :indeterminate="grade.selectedClassList?.length < grade.classList?.length && grade.selectedClassList?.length !==0  ? true : false"
                                @change="(val)=>HandleGradeSelectAllOrNot(grade,val)"
                            >
                                全选
                            </el-checkbox>

                            <el-checkbox 
                                v-model="grade.selectedClassList "
                                v-for="checkItem in grade.classList" 
                                :key="checkItem.value"
                                :label="checkItem.label"
                                :value="checkItem.value"
                                @change="(val)=>HandleGradeClassSelectChange(grade,val)"
                            />
                        </div>
                    </li>
                </ul>
            </template>


            <template #footerRight="{formRef}">
                <div v-if="!evaluationManageData.isGenerateAccountByGender" class="batch_num">
                    <span>数量：<el-input  type="number"  v-model="batchAccountNum"   placeholder="请输入"/></span>
                </div>
                <div v-else class="group_batch_num">
                    <span>男生：<el-input  type="number"  v-model="batchMaleNum"   placeholder="请输入"/></span>
                    <span>女生：<el-input  type="number"  v-model="batchFemaleNum"   placeholder="请输入"/></span>
                </div>
            </template>
        </FormDialog>
    
    </div>
</template>



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

import { useRoute,useRouter } from 'vue-router';

import Table from '@/baseComponents/Table.vue';
import FormDialog from '@/baseComponents/FormDialog.vue';

import {
    getReviewAccountListApi,
} from '@/api/step4Component'
import { ElMessage } from 'element-plus';


const route = useRoute()
const router = useRouter()

// evaluationManageData.isGenerateAccountByGender // //按男女生成
const evaluationManageData = inject('commonStepData')



// 1. 评价账号数据 渲染 及 操作
// 评价账号原始数据
const originReviewAccount = ref({})
// 渲染到表格中的评价账号数据
const tableData = ref([]);
const tableColumns = ref([])
// 表头初始赋值 和 表行初始赋值 以及 批量编辑弹窗变量赋值
const GetReviewAccountList = async ()=>{
    let params = {
        evaluationId: route.query.id,
       
        pageNum: 1,
        pageSize: 20
    }
    let res = await getReviewAccountListApi(params)
    if(res?.code == 200){
        ElMessage.success(res?.msg)

        let gradeMsg = res.data?.dataList || {}
        originReviewAccount.value = gradeMsg || {}

        // 批量编辑弹窗变量赋值
        batchEditGradeList.value = Object.values(gradeMsg).map(item=>{
            return {
                ...item,
                isSelectAll:false,
                selectedClassList:[],
                classList:item.classData.map(classItm=>{
                    return {
                        label: classItm.evaluationClassName, 
                        value: classItm.id 
                    }
                })
            }
        })

        //表头赋值
        tableColumns.value = Object.values(gradeMsg)?.map(grade=>{
            let gradeId =   grade.evaluationGradeId
            return [
                {
                    name: `grade_${gradeId}`,
                    label: '年级',
                    width: '80',
                    align: 'center',
                    custom: false, 
                    hidden: false,
                },
                {
                    name: `class_${gradeId}`,
                    label: '班级',
                    width: '80',
                    align: 'center',
                    custom: true, 
                    hidden: false,
                },
                {
                    name: `num_${gradeId}`,
                    label: '数量',
                    width: '80',
                    align: 'center',
                    custom: true, 
                    hidden: false,
                },
                {
                    name: `male_${gradeId}`,
                    label: '男生',
                    width: '80',
                    align: 'center',
                    custom: true, 
                    hidden: true,
                },
                {
                    name: `female_${gradeId}`,
                    label: '女生',
                    width: '80',
                    align: 'center',
                    custom: true, 
                    hidden: true,
                },
            ]
        }).flat()

        //初次赋值,要检查 上一次生成账号是否按男女生成 
        ChangeHeaderShowItem(evaluationManageData.isGenerateAccountByGender)

        // 表行赋值
        Object.values(gradeMsg)?.map(grade=>{
            let gradeId =  grade.evaluationGradeId
            let gradeName = grade.evaluationGradeName
            let classDataList = grade.classData
            
            classDataList.map((classItm,index)=>{
                if(typeof tableData.value[index] !== 'object'){
                    tableData.value[index] = {}
                }
                // 当前年级下的行赋值
                tableData.value[index][`grade_${gradeId}`] = gradeName
                tableData.value[index][`class_${gradeId}`] = {
                    className:classItm.evaluationClassName,
                    classId:classItm.id,
                }
                tableData.value[index][`num_${gradeId}`] = classItm.evaluationCount
                tableData.value[index][`male_${gradeId}`] = classItm.boyCount
                tableData.value[index][`female_${gradeId}`] = classItm.girlCount
            })        
        })
    }
}
// 切换评价账号的表头展示项 _ 根据 是否按男女生成 来判断
const ChangeHeaderShowItem = (isGenerateByGender:Boolean)=>{
    if(isGenerateByGender){
        // 打开
        tableColumns.value = tableColumns.value.map(item=>{
            if(item?.name.startsWith('num_')){
                item.hidden = true
            }else if(item?.name.startsWith('male_') || item?.name.startsWith('female_')){
                item.hidden = false
            }
            return item
        })
    }else{
        // 关闭
        tableColumns.value = tableColumns.value.map(item=>{
            if(item?.name.startsWith('num_')){
                item.hidden = false
            }else if(item?.name.startsWith('male_') || item?.name.startsWith('female_')){
                item.hidden = true
            }
            return item
        })
    }
}

watch(()=>evaluationManageData.isGenerateAccountByGender,(val)=>{
    ChangeHeaderShowItem(val)   
})

// 2. 批量编辑弹窗操作
const batchEditFormVisible = ref(false)
const batchEditFormLoading = ref(false)
const batchAccountNum = ref()  //批量的所有数据
const batchFemaleNum = ref()  //批量的女性数据
const batchMaleNum = ref()  //批量的男性数据
interface  batchEditGradeItm {
    evaluationGradeName: string,
    evaluationGradeId: string,
    classList: {label: string, value: string }[],
    selectedClassList:string[],
    isSelectAll:boolean,
}
// 批量编辑 弹窗数据
const batchEditGradeList = ref<batchEditGradeItm[]>([]);
// 关闭批量编辑弹窗
const CloseBatchEditForm = ()=>{
    batchEditFormVisible.value = false
    batchAccountNum.value = null
    batchMaleNum.value = null
    batchFemaleNum.value = null
    // 清除 批量弹窗编辑 的批量选中数据
    batchEditGradeList.value = batchEditGradeList.value.map(item=>{
        return {
            ...item,
            selectedClassList:[],
            isSelectAll:false
        }
    })
}
// 打开批量编辑弹窗
const OpenBatchEditForm = ()=>{
    batchEditFormVisible.value = true
}

// 保存批量编辑配置 —— 
const SaveBatchEditForm = (params:any)=>{
    const batchData = batchEditGradeList.value.map(item=>{
        return {
            gradeName: item.evaluationGradeName,
            gradeId: item.evaluationGradeId,
            selectedClassList:item.selectedClassList
        }
    })?.filter(item=>{return item.selectedClassList?.length > 0})

    // 选中的值赋值
    batchEditGradeList.value.map(grade=>{
        let gradeId =  grade.evaluationGradeId
        let classDataList = grade.classData
        let changeAim = batchData.find(itm=>itm.gradeId == gradeId)
        // 有需要批量修改的 年级
        if(changeAim){
            classDataList.map((classItm,index)=>{
                // 有需要批量修改的 班级
                if(changeAim.selectedClassList.find(classId=>classId == classItm.id )){
                    if(typeof tableData.value[index] !== 'object'){
                        tableData.value[index] = {}
                    }
                    // 当前年级下  某个班级 的行赋值
                    if(evaluationManageData.isGenerateAccountByGender){
                        // 按男女生成
                        tableData.value[index][`num_${gradeId}`] = Number(batchMaleNum.value) + Number(batchFemaleNum.value)
                        tableData.value[index][`male_${gradeId}`] = batchMaleNum.value
                        tableData.value[index][`female_${gradeId}`] = batchFemaleNum.value
                    }else{
                        // 按总人数生成
                        tableData.value[index][`num_${gradeId}`] = batchAccountNum.value
                        tableData.value[index][`male_${gradeId}`] = Math.floor(batchAccountNum.value / 2)
                        tableData.value[index][`female_${gradeId}`] = Math.ceil(batchAccountNum.value / 2)
                    }
                }
            })      
        }
    })
    CloseBatchEditForm()
}

// 年级全选/全不选
const HandleGradeSelectAllOrNot = (grade,val)=>{
    if(val){
        // 全选
        batchEditGradeList.value = batchEditGradeList.value.map(item=>{
            if(item.evaluationGradeId == grade.evaluationGradeId){
                item.selectedClassList = item.classList.map(classItm=>{
                    return classItm.value
                })
            }
            return item
        })
    }else{{
        // 全不选
         batchEditGradeList.value = batchEditGradeList.value.map(item=>{
            if(item.evaluationGradeId == grade.evaluationGradeId){
                item.selectedClassList = []
            }
            return item
        })
    }}
}

// 年级下 班级选择的变更
const HandleGradeClassSelectChange = (grade,val)=>{
    batchEditGradeList.value = batchEditGradeList.value.map(item=>{
        if(item.evaluationGradeId == grade.evaluationGradeId){
            item.isSelectAll = grade.selectedClassList?.length === grade.classList?.length && grade.selectedClassList?.length !==0 ? true : false
        }
        return item
    })
}

// 3. 清空配置的评价账号数据
const ClearReviewAccount = ()=>{
    batchEditGradeList.value?.map(grade=>{
        let gradeId =  grade.evaluationGradeId
        let classDataList = grade.classData
        classDataList.map((classItm,index)=>{
            if(typeof tableData.value[index] !== 'object'){
                tableData.value[index] = {}
            }
            // 当前年级下的行赋值
            tableData.value[index][`num_${gradeId}`] = null
            tableData.value[index][`male_${gradeId}`] = null
            tableData.value[index][`female_${gradeId}`] = null
        })        
    })
}


// 4. 生成评价码页面
const GoToGenerateCodePage = ()=>{
    // 跳转到生成评价码页面前要临时存储 当前页面的所有数据
    let reviewAccountMsg = {
        originReviewAccount:originReviewAccount.value,
        batchEditGradeList:batchEditGradeList.value,
        tableColumns:tableColumns.value,
        tableData:tableData.value
    }

    let accounts = batchEditGradeList.value?.map(grade=>{
        let gradeId =  grade.evaluationGradeId
        let classDataList = grade.classData

        return classDataList.map((classItm,index)=>{
            if(typeof tableData.value[index] !== 'object'){
                tableData.value[index] = {}
            }
            return {
                id:tableData.value[index][`class_${gradeId}`].classId,
                evaluationGradeName: tableData.value[index][`grade_${gradeId}`],
                evaluationDataClassName: tableData.value[index][`class_${gradeId}`]?.className,
                evaluationCount: tableData.value[index][`num_${gradeId}`],
                boyCount: tableData.value[index][`male_${gradeId}`],
                girlCount: tableData.value[index][`female_${gradeId}`]
            }
        })        
    })?.flat() || []

    let params = {
        evaluationId: route.query.id,
        genderStatus: evaluationManageData.isGenerateAccountByGender ?  1 : 0, 
        accounts
    }

    // 存储当前整个页面的内容——防止生成评价码失败后，不能继续延用 配置状态的旧数据
    sessionStorage.setItem('reviewAccountMsg',JSON.stringify(reviewAccountMsg))
    // 存储生成评价码需要的参数
    sessionStorage.setItem('reviewAccountOptionData',JSON.stringify(params))
    router.push(`generateReviewCode?id=${route.query.id}`)
}


onMounted(async ()=>{
    let reviewAccountMsg = sessionStorage.getItem('reviewAccountMsg')
    // 如果有缓存，说明是从生成评价码失败页面跳过来的
    if(reviewAccountMsg){
        let objMsg = JSON.parse(reviewAccountMsg || '{}')
        originReviewAccount.value = objMsg.originReviewAccount
        batchEditGradeList.value = objMsg.batchEditGradeList
        tableColumns.value = objMsg.tableColumns
        tableData.value  = objMsg.tableData
        sessionStorage.removeItem('reviewAccountMsg')  //获取完后清空数据
    }else{
        await GetReviewAccountList()
    }
})

</script>



<style lang="scss" scoped>

.grade_form_item{
    display: flex;
    flex-direction: column;
    gap:26px;

    .grade_name{
        font-weight: 600;
        font-size: 16px;
        color: #333333;
        margin-bottom: 10px;
    }
    .class_list .el-checkbox{
        font-weight: 400;
        font-size: 14px;
        color: #666666;
    }

}

.group_batch_num,
.batch_num{
    display: flex;
    align-items: center;
    gap:20px;
    word-break: keep-all;

    > span{
        display: flex;
        align-items: center;
        word-break: keep-all;
    }
}



</style>