<template>
    <div class="page_item end_item">
        <div class=" page_search">
            <div class="search_content">
                <div class="content_left">
                    <FormSearchGroup :searchList="searchList" @searchChange="HandleSelectSearchChange"></FormSearchGroup>
                </div>
                <div class="content_right">
                    <el-button class="button_refresh">导出PDF</el-button>
                    <el-button class="button_refresh">导出Excel</el-button>
                    <el-button :class="[store.state.evaluationManageStepData.isAllowDeleteOrEdit ?  'button_border' : 'is-disabled']" 
                        @click="store.state.evaluationManageStepData.isAllowDeleteOrEdit ?  GoToReviewAccountConfig() : ''">重新生成</el-button>
                    <el-button :class="[store.state.evaluationManageStepData.isAllowDeleteOrEdit ? 'button_background' : 'is-disabled']" 
                        @click="store.state.evaluationManageStepData.isAllowDeleteOrEdit ? FinishReviewAccount() : ''">完成</el-button>
                </div>
            </div>
        </div>
        <div class="page_jg_20"></div>
        <Table 
            :currentPage="currentPage" 
            :pageSize="pageSize"  
            :tableData="tableData" 
            :tableColumns="generateCodeTableColumns" 
            :totalNum="totalNum"
            @paginationChange="HandlePaginationChange"
        >
            <template #num="{row,currentIndex}">
                {{ currentIndex + pageSize * (currentPage - 1) }}
            </template>

            <template #requestUrl="{row}">
                <div class="request_url">
                    <img class="qr_code" :src="row?.qrCode" @click="downloadQRCode(row?.qrCode)" alt="QR Code" />
                    {{ row.requestUrl }}
                </div>
            </template>
        </Table>
    </div>
</template>   


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

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

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


import {makeQRCode,downloadQRCode } from '@/utils/makeQRCode'

import { searchList } from './formSearchGroup';
import { generateCodeTableColumns } from './table';

import {
    generateReviewCodeListApi,finishReviewAccountApi,getReviewAccountListApi,
    getGradeAndClassListApi,
} from '@/api/reviewAccountComponent'
import { onMounted } from 'vue';

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

// store.state.evaluationManageStepData.isGenerateAccountByGender // //按男女生成
const store = useStore()
const GoToReviewAccountConfig = ()=>{
   router.push(`reviewAccount?id=${route.query.id}`)
}


// 1. 生成评价账号 
const GenerateReviewCode = async ()=>{
    let paramsStr = sessionStorage.getItem('reviewAccountOptionData')  //是否需要生成评价码 的 标识
    let reviewAccountOptionData =  JSON.parse(paramsStr || '{}')
    if(paramsStr){
        // 有生成评价码的传参 _需要生成评价码
        let res = undefined
        try{
            res = await generateReviewCodeListApi(reviewAccountOptionData)
        }catch{}
        if(res?.code == 200){
            sessionStorage.removeItem('reviewAccountOptionData')   // 评价码生成后清除传参
            sessionStorage.removeItem('reviewAccountMsg') // 评价码生成成功，配置状态的旧数据 不再需要保留
            return true
        }else{
            return false
        }
    }else{
        // 没有生成评价码的传参 _不需要生成评价码
        return true
    }
}


// .2. 评价码数据获取 
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const totalNum = ref(0)
// 获取评价码
const GetReviewCode = async ()=>{
    // 获取评价码信息
    let params = {
        evaluationId: route.query.id,
        evaluationGradeId: searchParams.value.evaluationGradeId == 'all' ? '' : JSON.parse(searchParams.value.evaluationGradeId || '{}')?.id,
        evaluationClassId:searchParams.value.evaluationClassId == 'all' ? '' : searchParams.value.evaluationClassId ,
        gender:searchParams.value.gender == 'all' ? '' : searchParams.value.gender,
        pageNum: currentPage.value,
        pageSize: pageSize.value
    }
    let res = await getReviewAccountListApi(params)
    if(res?.code == 200){
        const {codeDataList} = res.data
        tableData.value = await Promise.all(codeDataList.records.map(async item=>{
            return {
                ...item,
                qrCode:await makeQRCode(item.requestUrl)
            }
        }))

        totalNum.value = codeDataList.total
    }
}
// 表格分页切换
const HandlePaginationChange = async (params)=>{
    const {type,val} = params
    if(type == 'currentPage'){
        currentPage.value = val
    }
   await GetReviewCode()
}

//3. 查询参数变更
const searchParams = ref({
    evaluationGradeId:'all',  //年级
    evaluationClassId:'all',   //班级
    gender:'all',          //性别
})

// 获取 评价账号 年级/班级 筛选下拉
const GetGradeAndClassListOption = async ()=>{
    let res = await getGradeAndClassListApi(route.query.id)
    if(res?.code == 200){
        let gradeOptions = res.data?.map(item=>{
            return {
                label:item.gradeName,
                value:JSON.stringify({
                    id:item.id,
                    classData:item.classData
                })
            }
        }) || []
        // 初始赋值,班级只展示 [全部] 项
        let classOptions = [
            {
                label:'全部班级',
                value:'all'
            }
        ]
        searchList.value = searchList.value.map(item=>{
            if(item.key == 'evaluationGradeId'){
                item.options = [
                    {
                        label:'全部年级',
                        value:'all'
                    },
                    ...gradeOptions
                ]
            }else if(item.key == 'evaluationClassId'){
                item.options = classOptions
            }
            return item
        })
    }
}

// 搜索项下拉列表变更
const HandleSelectSearchChange = async (params,key)=>{
    console.log('查询搜素项参数__',params)
    searchParams.value = {...searchParams.value,...params}
    searchList.value = searchList.value.map(item=>{
        switch(item.key){
            case 'evaluationClassId':{
                // 当前触发的是年级下拉变更
                if(key == 'evaluationGradeId'){
                    // 重置班级的默认值
                    searchParams.value.evaluationClassId = 'all'
                    if(params.evaluationGradeId == 'all'){
                        // 班级下拉置空,只剩全部
                        item.options = [{label:'全部班级', value:'all' }]
                    }else{
                        // 班级下拉 动态变更
                        let classOptions = (JSON.parse(params.evaluationGradeId || '{}')?.classData || [])?.map(item=>{
                            return {
                                label:item.name,
                                value:item.id
                            }
                        })
                        item.options = [{label:'全部班级', value:'all'},
                                        ...classOptions]
                    }
                }
                break
            }
        }
        return {
            ...item,
            defaultValue:searchParams.value[item.key]
        }
    })

    // 调用查询接口
    await GetReviewCode()

}



// 3. 完成评价账号
const FinishReviewAccount = async()=>{
    let res = await finishReviewAccountApi(route.query.id)
    if(res?.code == 200){
        // 更新全局状态 
        await store.dispatch('updateEvaluationManageStepData',route.query.id)
        store.commit('updateEvaluationManageStepData',{currentActiveStepName:'parameterSetting'})  //更新全局活跃路由
        router.push(`parameterSetting?id=${route.query.id}`)
    }
}

// 根据是否按照性别生成评价码 控制 表格项和搜索项的显隐
watch(()=>store.state.evaluationManageStepData.isGenerateAccountByGender,(newVal)=>{
    generateCodeTableColumns.value = generateCodeTableColumns.value.map(item=>{
        if(item.name == 'genderName'){
            item.hidden = newVal ? false :true
        }
        return item
    })
    searchList.value = searchList.value.map(item=>{
        if(item.key == 'gender'){
            item.hidden = newVal ? false :true
        }
        return item 
    })
},{immediate:true})

onMounted(async ()=>{
    let generateFlag = await GenerateReviewCode()
    if(generateFlag){  // 这一步成功 才执行下一步
        await GetGradeAndClassListOption()
        await GetReviewCode()
    }else{
        // 评价码生成失败 返回配置页
        router.push(`reviewAccount?id=${route.query.id}`)
    }
})
</script>


<style lang="scss" scoped>

.request_url{
    display: flex;
    gap:16px;
    justify-content: center;
    align-items: center;
    .qr_code{
        width: 24px;
        height: 24px;
    }
}
</style>