<!-- 自主练习——查看练习结果 -->
<template>
    <div class="practice_result">
        <div class="page_search">
            <div class="search_content">
                <div class="content_left">
                    <div class="grade_title">练习记录</div>
                </div>
            </div>
        </div>

        <FiltersItem :filtersData="filtersData"  @selectItem="ChangeFilters">
            <template #rowItem-time>
                <el-date-picker
                    v-if="filtersData[0].value == 'custom'"
                    style="height: 28px;flex-grow: 0;width: 225px;"
                    v-model="startAndEndTime"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    size="default"
                    @change="GetTargetExerciseResult"
                />
            </template>
        </FiltersItem>
      
        <Table class="practice_table" 
            :currentPage="currentPage" :pageSize="pageSize" :totalNum="totalNum"
            :tableData="tableData"  :tableColumns="tableColumns" 
            @paginationChange="HandlePaginationChange">

            <template v-slot:exerciseType="{row}">
                {{ HandlePracticeNumTypeToStr(row.exerciseType) }}
            </template>
            <template v-slot:exerciseStatus="{row}">
                <TableRowStatus :useStatus="row.exerciseStatus"
                    :statusMsg="[
                        {
                            statusFlag:1,
                            title:'未批阅',
                            themeClass:'need_summary_icon'
                        },
                        {
                            statusFlag:2,
                            title:'批阅中',
                            themeClass:'no_release_icon'
                        },
                        {
                            statusFlag:3,
                            title:'已批阅',
                            themeClass:'normal_icon'
                        },
                        {
                            statusFlag:4,  // 已发布成绩
                            title:'已批阅',
                            themeClass:'normal_icon'
                        },
                    ]">
                </TableRowStatus>
            </template>
                
            <template v-slot:frontRate="{row}">
                {{ row.frontRate === '-' ? row.frontRate : row.frontRate + '%' }}
            </template>
            <!-- exerciseStatus 批阅状态（1未批阅 2批阅中 3已批阅） -->
            <template v-slot:afterRate="{row}">
                {{ row.exerciseStatus === 3 ? row.afterRate + '%'  : row.afterRate}}
            </template>

            <template v-slot:difference="{row}">
                <img v-if="row.exerciseStatus === 3" 
                    width="16px" height="16px" style="margin-right: 2px;" 
                    :src="Number(row.afterRate) > Number(row.frontRate) ? upIcon : downIcon" alt="" />
                {{ row.exerciseStatus === 3 ?  row.difference + '%' : 0 }}
            </template>
            <template v-slot:action="{row}">
                <div class="table_row_operation">
                    <el-button type="text" @click="viewDetails(row)">查看</el-button>
                </div>
            </template>
        </Table>
    </div>

</template>

<script>
import dayjs from 'dayjs';
// 1. 引入 isoWeek 插件
import isoWeek from 'dayjs/plugin/isoWeek';

import { mapState } from "vuex";

import FiltersItem from "../components/FiltersItem_ruoyan.vue"//筛选组件
import Table from "../components/Table.vue";
import TableRowStatus from "../components/TableRowStatus.vue";

import upIcon from '@/assets/arrow-up.png'
import downIcon from '@/assets/arrow-down.png'

// 2. 全局扩展插件（只需调用一次即可）
dayjs.extend(isoWeek);


export default ({
    components: {
        FiltersItem,
        Table,
        TableRowStatus
    },
    data(){
        return {
            upIcon:upIcon,
            downIcon:downIcon,
            currentPage:1,
            pageSize:20,
            totalNum:0,
            tableColumns: [
                {
                    name: 'submitTime',      
                    label: '练习时间',
                    minWidth: '180',              
                    hidden: false,
                    custom: false,
                },
                {
                    name: 'exerciseType',     
                    label: '练习类型',
                    minWidth: '120',
                    align: 'center',         
                    hidden: false,
                    custom: true,
                },
                {
                    name: 'knowledgeName',     
                    label: '知识点名称',
                    minWidth: '150',           
                    hidden: false,
                    custom: false,
                },
                {
                    name: 'questionNum',    
                    label: '试题数量',
                    minWidth: '100',
                    align: 'center',
                    hidden: false,
                    custom: false,
                },
                {
                    name: 'exerciseStatus',   
                    label: '批阅状态',
                    minWidth: '120',
                    align: 'center',
                    hidden: false,
                    custom: true,             
                },
                {
                    name: 'frontRate',    
                    label: '练前得分率',
                    minWidth: '120',
                    align: 'center',
                    hidden: false,
                    custom: true,            
                },
                {
                    name: 'afterRate',    
                    label: '练后得分率',
                    minWidth: '120',
                    align: 'center',
                    hidden: false,
                    custom: true,
                },
                {
                    name: 'difference',       
                    label: '提升情况',
                    minWidth: '120',
                    align: 'center',
                    hidden: false,
                    custom: true,              
                },
                {
                    name: 'action',       
                    label: '操作',
                    minWidth: '100',
                    fixed: 'right',   
                    align: 'center',
                    hidden: false,
                    custom: true,   
                }
            ],
            tableData: [],
            filtersData: [
                {
                    key:'time',
                    name: '时间',
                    value: 'all', // 默认选中项
                    list: [
                        { label: '全部', value: 'all' },
                        { label: '本周', value: 'this_week' },
                        { label: '最近1月', value: 'last_1_month' },
                        { label: '最近3月', value: 'last_3_months' },
                        { label: '自定义', value: 'custom' }
                    ]
                },
                {
                    key:'type',
                    name: '类型',
                    value: 'all', // 默认选中项
                    list: [
                        { label: '全部', value: 'all' },
                        { label: '指定练习', value: '2' },
                        { label: '自主练习', value: '1' }
                    ]
                }
            ],
            startAndEndTime:undefined,
        }
    },
    methods: {
        // 处理练习类型转换
        HandlePracticeNumTypeToStr(num){
            switch(Number(num)){
                case 1:
                    return '自主练习'
                case 2:
                    return '指定练习'
                default:
                    return ''
            }
        },
        // 筛选组件回调
        ChangeFilters(e) {
            // console.log('当前选中的信息',e)
            this.filtersData[e.index].value = e.value;
            this.GetTargetExerciseResult()
        },
        // 处理表格分页变化
        HandlePaginationChange(params){
            const {type, val} = params
            if(type == 'currentPage'){
                this.currentPage = Number(val)
            }else if(type == 'pageSize'){
                this.pageSize = Number(val)
            }
            this.GetTargetExerciseResult()
        },
        // 获取本周一（本周起始日）的 00:00:00
        getCurrentWeekStart(){
            return  dayjs().startOf('isoWeek').format("YYYY-MM-DD HH:mm:ss");
        }, 
        // 获取一个月前的时间
        getOneMonthAgo(){
            return dayjs().subtract(1, 'month').format("YYYY-MM-DD HH:mm:ss");
        },
        // 获取三个月前的时间
        getThreeMonthsAgo(){
            return dayjs().subtract(3, 'month').format("YYYY-MM-DD HH:mm:ss");
        },

        // 获取练习结果列表
        GetTargetExerciseResult(){
            let startDate = ''
            let endDate = ''
            switch(this.filtersData[0].value){
                case 'all':
                    startDate = ''
                    endDate = ''
                    break
                case 'this_week':
                    startDate = this.getCurrentWeekStart()
                    endDate = dayjs().format("YYYY-MM-DD HH:mm:ss")
                    break
                case 'last_1_month':
                    startDate = this.getOneMonthAgo()
                    endDate = dayjs().format("YYYY-MM-DD HH:mm:ss")
                    break
                case 'last_3_months':
                    startDate = this.getThreeMonthsAgo()
                    endDate = dayjs().format("YYYY-MM-DD HH:mm:ss")
                    break
                case 'custom':
                    startDate = this.startAndEndTime?.[0] ?  dayjs(this.startAndEndTime?.[0]).format("YYYY-MM-DD HH:mm:ss") : ''
                    endDate = this.startAndEndTime?.[1] ? dayjs(this.startAndEndTime?.[1]).format("YYYY-MM-DD HH:mm:ss") : ''
                    break
            }
            let prams = {
                pageParam: {
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                },
                beginAt: startDate,   //开始时间
                endAt: endDate,      //结束时间
                exerciseType: this.filtersData[1].value == 'all' ? '' : this.filtersData[1].value ,   // 练习类型0全部 1自主练习 2指定练习
                levelCode: this.$store.state.target.levelCode,      // 学段code
                subjectCode: this.$store.state.target.subjectCode     //学科code
            }
            this.$api.target.getTargetExerciseResult(prams).then(res=>{
                if(res?.code == 200){
                    this.tableData = res.data.records
                    this.totalNum = Number(res.data.total)
                    this.currentPage = Number( res.data.current)
                }
            }).catch()
        },
        // 跳转练习结果详情
        viewDetails(row){
            let tmpStorage = {
                practiceTime:row.submitTime,  //练习时间(提交时间)
                frontRate:row.frontRate,   //练前得分率
                afterRate:row.afterRate,   //练后得分率
                difference:row.difference,   //提升情况
                exerciseStatus:row.exerciseStatus,   // 批阅状态（1未批阅 2批阅中 3已批阅）
            }
            sessionStorage.setItem('practice_detail',JSON.stringify(tmpStorage))
            this.$router.push(`/targetImprove/praciceResultDetail?id=${row.exerciseId}`);
        },
     },
    computed:{
      ...mapState("target", ["subjectCode"]),

    },
    mounted() {
        this.GetTargetExerciseResult();
    },
    watch:{
        subjectCode(newVal){
            this.GetTargetExerciseResult();
        }
    }

})


</script>


<style lang="scss" scoped>
.practice_result{
    display: flex;
    flex-direction: column;
    overflow: auto;

    width: 100%;
    height: calc(100% - 60px - 88px );
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 10px;
    margin-bottom: 10px;
    padding: 10px;

    > *:last-child{
        flex-grow: 1;
    }
    .page_search{
        margin-bottom: 16px;
    }
    .practice_table{
        margin-top: 2px;
        ::v-deep .el-table {
            thead{
                height: 40px !important;
            }
            .el-table__cell {
                height: 40px;
            }
        }
    }
}
</style>
