<template>
    <div class="scroll_content">
        <div class="select_box">
            <el-radio-group v-model="errorType" size="medium" @change="_queryStudentErrorQuestion">
                <el-radio-button :label="-1">全部试题（{{ allErrorCount }}）</el-radio-button>
                <el-radio-button :label="0">未掌握（{{ unMasterCount }}）</el-radio-button>
                <el-radio-button :label="1">已掌握（{{ masterCount }}）</el-radio-button>
                <el-radio-button :label="2">复习题（{{ reviewCount }}）</el-radio-button>
            </el-radio-group>
        </div>

        <div class="content">
            <div class="right_btn" v-if="errorType !== 1">
                <el-button size="medium" :disabled="!canBtnClick"
                    @click="downloadDialogVisible = true; isVariation = 0">下载错题本</el-button>
                <el-button :disabled="!canBtnClick" type="primary" size="medium"
                    @click="downLoadPapers">下载个性化提升手册</el-button>
            </div>

            <Download :visible.sync="downloadDialogVisible" :examId="examId" :subjectCode="subjectCode"
                :isVariation="isVariation" :questionList="questionList" />

            <template v-if="questionList.length > 0">
                <div v-for="(question, index) in questionList" :key="question.questionId">
                    <div class="question_card">
                        <div class="card_top">
                            <div class="card_top_info">
                                <div class="left">
                                    <span class="number mr_10">{{ countGlobalIndex(index + 1) }}</span>
                                    <span class="gray">试题类型：<span v-if="!question.questionType">暂无试题类型</span></span>
                                    <span class="black mr_10" style="font-weight: 500;">
                                        {{ question.questionType }}
                                    </span>
                                    <span class="tag" v-if="question.classScoreRate < 40">高频错题</span>
                                </div>
                            </div>

                            <div class="question_content line_height_20">
                                <template v-if="question.questionData?.questionStem || question.questionImg">
                                    <Preview :type="question.sourceType" :content="question.questionData?.questionStem"
                                        :imgBase64="question.questionImg" />
                                </template>
                                <template v-else>
                                    <div style="color: #999;">暂无数据</div>
                                </template>
                            </div>

                            <div class="card_footer">
                                <div class="footer_item">
                                    <span class="gray">满分：</span>
                                    <span class="blue">{{ question.fullScore }}</span>
                                    <span class="gray">分</span>
                                </div>
                                <div class="footer_item">
                                    <span class="gray">我的得分：</span>
                                    <span class="blue">{{ question.score }}</span>
                                    <span class="gray">分</span>
                                </div>
                                <div class="footer_item">
                                    <span class="gray">难度：</span>
                                    <span style="font-weight: bold;" :class="countDiffcutyClass(question.difficulty)">
                                        {{ question.difficulty }}
                                    </span>
                                </div>
                            </div>
                        </div>

                        <div class="card_buttom">
                            <div class="btn_box">
                                <span class="black ml_30" :class="{ blue: question.answerShow }" size="small"
                                    @click="ShowAnserAndParse(1, question);">
                                    <i class="iconfont icon_daan"></i>
                                    我的答案
                                    <i class="answerShow_content" v-if="question.answerShow && !question.parseShow"></i>
                                </span>

                                <span class="black ml_30" :class="{ blue: question.parseShow }" size="small"
                                    @click="ShowAnserAndParse(2, question);">
                                    <i class="iconfont icon_jiexi"></i>
                                    查看解析
                                    <i class="parseShow_content" v-if="question.parseShow && !question.answerShow"></i>
                                </span>

                                <template v-if="question.errorStatus === 0">
                                    <template v-if="errorType === -1 || errorType === 0">
                                        <span class="black ml_30" size="small"
                                            @click="_markStudentErrorQuestion(question, 1)">
                                            <i class="iconfont icon_biaojiyizhangwo"></i>
                                            标记为已掌握
                                        </span>
                                        <span class="black ml_30" size="small"
                                            @click="_markStudentErrorQuestion(question, 2)">
                                            <i class="iconfont icon_jiarufuxiben"></i>
                                            加入复习本
                                        </span>
                                    </template>
                                </template>

                                <template v-if="errorType === 1 || question.errorStatus === 1">
                                    <span class="black ml_30" size="small"
                                        @click="_markStudentErrorQuestion(question, 0)">
                                        <i class="iconfont icon_biaojiweizhangwo"></i>
                                        标记为未掌握
                                    </span>
                                </template>

                                <template v-if="errorType === 2 || question.errorStatus === 2">
                                    <span class="black ml_30" size="small"
                                        @click="_markStudentErrorQuestion(question, 0)">
                                        <i class="iconfont icon_yichufuxiben"></i>
                                        移除复习本
                                    </span>
                                </template>
                            </div>

                            <div class="content" v-if="question.parseShow && !question.answerShow">
                                <div class="flex">
                                    <template v-if="question.knowledgePoint && question.knowledgePoint.length > 0">
                                        <div class="flex_left" style="line-height: 28px;">【知识点】</div>
                                        <div class="flex_right">
                                            <KnowledgePoint v-for="know in question.knowledgePoint" :key="know"
                                                :text="know" />
                                        </div>
                                    </template>

                                    <template v-else>
                                        <div class="flex_left">【知识点】</div>
                                        <div class="flex_right">
                                            <div style="color: #999;">暂无数据</div>
                                        </div>
                                    </template>
                                </div>

                                <div class="flex" style="line-height: 1.6 !important;">
                                    <div class="flex_left">【答&nbsp;&nbsp;&nbsp;&nbsp;案】</div>
                                    <div class="flex_right">
                                        <template
                                            v-if="question.questionData?.answer || question.answerImg || question.answer">
                                            <template v-if="question.isObjective === 1">
                                                <div>{{ question.answer }}</div>
                                            </template>

                                            <template v-else>
                                                <Preview :type="question.sourceType"
                                                    :content="question.questionData?.answer"
                                                    :imgBase64="question.answerImg" />
                                            </template>
                                        </template>

                                        <template v-else>
                                            <div style="color: #999;">暂无数据</div>
                                        </template>
                                    </div>
                                </div>

                                <div class="flex" style="line-height: 1.6 !important;">
                                    <div class="flex_left">【解&nbsp;&nbsp;&nbsp;&nbsp;析】</div>
                                    <div class="flex_right">
                                        <template v-if="question.questionData?.analysis || question.parseImg">
                                            <Preview :type="question.sourceType"
                                                :content="question.questionData?.analysis"
                                                :imgBase64="question.parseImg" />
                                        </template>
                                        <template v-else>
                                            <div style="color: #999;">暂无数据</div>
                                        </template>
                                    </div>
                                </div>
                            </div>

                            <div class="content" v-if="question.answerShow && !question.parseShow">
                                <template v-if="question.isObjective === 1">
                                    <div v-if="question.studentAnswer">{{ question.studentAnswer }}</div>
                                    <div v-else style="color: #999;">暂无数据</div>
                                </template>

                                <template v-else>
                                    <template v-if="picUrl && questionVOS">
                                        <div style="height: 300px;">
                                            <PaperImage :imageIndex="index" :scoreFontSize="20" :rtOrWrSize="10"
                                                :paperImgUrl="picUrl" :usedCardType="usedCardType" :drawData="questionVOS" />
                                        </div>
                                    </template>
                                    <div v-else style="color: #999;">暂无数据</div>
                                </template>
                            </div>
                        </div>
                    </div>

                    <!-- 变式题推送 -->
                    <div class="question_card" v-if="question.variationQuestion">
                        <div class="card_top">
                            <div class="card_top_info">
                                <div class="left">
                                    <span class="number mr_10"
                                        :class="countLevel(question.variationQuestion.questionLevel).color">
                                        {{ countLevel(question.variationQuestion.questionLevel).text }}
                                    </span>
                                    <span class="gray">试题类型：</span>
                                    <span class="black" style="margin-right: 20px;">
                                        {{ question.variationQuestion.questionType }}
                                    </span>
                                    <span class="gray">难度：</span>
                                    <span style="font-weight: bold;"
                                        :class="countDiffcutyClass(question.variationQuestion.difficulty)">
                                        {{ question.variationQuestion.difficulty }}
                                    </span>
                                </div>
                            </div>

                            <div class="question_content line_height_20">
                                <Preview :type="1" :content="question.variationQuestion?.questionStem" />
                            </div>

                            <!-- <div class="yuwen">
                                <span class="btn_span active">1</span>
                                <span class="btn_span">2</span>
                                <div class="question_list"></div>
                            </div> -->

                            <div class="card_footer">
                                <div class="gray">知识点：</div>
                                <template v-for="(know, index) in question.variationQuestion.knowledgePoint">
                                    <KnowledgePoint :text="know" />
                                </template>
                            </div>
                        </div>
                    </div>
                </div>

                <div style="text-align: right;">
                    <el-pagination background layout="prev, pager, next" :total="pageParam.total"
                        :page-size="pageParam.pageSize" :current-page="pageParam.pageNum"
                        @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </template>

            <NoData v-else>暂无数据</NoData>
        </div>
    </div>
</template>

<script>
import {
    queryStudentErrorQuestion,
    markStudentErrorQuestion,
    downloadStudentErrorQuestion,
    findStudentCard
} from '../../../http/api/errorQuestion';
import Download from './Download.vue';
import { mergeImage } from './loadImg.js'
import { Loading } from 'element-ui';
import NoData from './NoData/NoData.vue';
import KnowledgePoint from './KnowledgePoint.vue';
import Preview from './Preview.vue';
import PaperImage from '@/components/PaperImage.vue';
import { confirm } from '../../../utils/common.js'

export default {
    components: {
        Download,
        NoData,
        KnowledgePoint,
        Preview,
        PaperImage,

    },

    data() {
        return {
            pageParam: {
                pageNum: 1,
                pageSize: 10,
                total: 0,
            },
            questionList: [],
            allErrorCount: 0,
            unMasterCount: 0,
            masterCount: 0,
            reviewCount: 0,
            answerUrls: [],
            uploadPaperUrls: [],
            errorType: -1, // -1全部 0未掌握 1已掌握 2复习题

            examId: null,
            examType: null,
            gradeCode: null,

            downloadDialogVisible: false,
            isVariation: 0,
            picUrl: null,
            usedCardType: null,
            questionVOS: [],

        };
    },

    computed: {
        subjectCode() {
            return this.$store.state.report.filterObject.subjectCode;
        }, //分析报告公共参数变量

        IsVariation() {
            return this.$store.state.question.isVariation;
        },

        canBtnClick() {
            const has = this.questionList.find(question => {
                return !question.questionImg && !question.questionData?.questionStem
            })

            console.log('has', has)

            if (has) {
                this.$store.commit('question/setCanDownloanBtnClick', false)
                return false
            } else {
                this.$store.commit('question/setCanDownloanBtnClick', true)
                return true
            }
        }
    },

    watch: {
        subjectCode(newVal, oldVal) {
            if (newVal !== oldVal) {
                this.pageParam.pageNum = 1;
                this._queryStudentErrorQuestion();
            }
        },

        IsVariation(newVal) {
            if (newVal === 0 || newVal === 1) {
                this.downloadDialogVisible = true
                this.isVariation = newVal
            }
        },
    },

    created() {
        this.$store.commit('report/SetShowTotalScore', false)
        const ExamInfoItem = JSON.parse(localStorage.getItem("ExamInfoItem") || "{}");
        const reportExamCourseItem = JSON.parse(localStorage.getItem("reportExamCourseItem") || "{}");
        this.examId = reportExamCourseItem.examId;
        this.gradeCode = ExamInfoItem.examData.gradeCode;
        this.examType = ExamInfoItem.examData.examType;
    },

    async mounted() {
        await this._queryStudentErrorQuestion();
    },

    beforeDestroy() {
        this.$store.commit('report/SetShowTotalScore', true)
    },

    methods: {
        countGlobalIndex(index) {
            return (this.pageParam.pageNum - 1) * this.pageParam.pageSize + index;
        },

        countDiffcutyClass(difficulty) {
            // 容易：#90CB75    较易：#FAC858  一般：#5470C6  较难：#EA7ACB  困难：#EE6666
            const classMap = {
                '容易': 'easy',
                '较易': 'medium_easy',
                '一般': 'medium',
                '较难': 'medium_hard',
                '困难': 'hard'
            }
            return classMap[difficulty] || ''
        },

        countLevel(num) {
            // 1 :拔高题  2:进阶题  3:巩固题
            const arr = ['拔高题', '进阶题', '巩固题']
            const color = ['bg_hard', 'bg_medium', 'bg_easy',]
            return {
                text: arr[num - 1],
                color: color[num - 1],
            }
        },

        ShowAnserAndParse(type, question) {
            if (type === 1) {
                if (question.isObjective === 1) {
                    question.answerShow = !question.answerShow;
                    question.parseShow = false
                    return;
                }

                findStudentCard({
                    examId: this.examId,
                    subjectCode: this.subjectCode,
                    questionId: question.questionId,
                }).then(res => {
                    if (res.code === 200) {
                        if (res.data && res.data.pageVOS && res.data.pageVOS.length > 0) {


                            const data = res.data.pageVOS[0]
                            this.picUrl = data.picUrl;
                            this.usedCardType = data.useType;
                            this.questionVOS = data.questionVOS.map(item => {
                                return {
                                    ...item,
                                    samplingPosition: '{"x":195,"y":247,"page":1}'
                                }
                            });
                        } else {
                            this.picUrl = null;
                            this.usedCardType = null;
                            this.questionVOS = [];
                        }


                        question.answerShow = !question.answerShow;
                        question.parseShow = false
                    }
                })
            }

            if (type === 2) {
                question.parseShow = !question.parseShow;
                question.answerShow = false
            }
        },

        async _queryStudentErrorQuestion() {
            const instance = Loading.service({ fullscreen: true });
            const { subjectCode, gradeCode, examType, examId, errorType, pageParam: { pageNum, pageSize } } = this
            const res = await queryStudentErrorQuestion({ subjectCode, gradeCode, examType, examId, errorType, pageNum, pageSize });

            if (res.code === 200) {
                const { allErrorCount, unMasterCount, masterCount, reviewCount, questionList, answerUrls, uploadPaperUrls } = res.data.records[0];

                this.allErrorCount = allErrorCount;
                this.masterCount = masterCount;
                this.unMasterCount = unMasterCount;
                this.reviewCount = reviewCount;
                this.answerUrls = answerUrls;
                this.uploadPaperUrls = uploadPaperUrls;
                this.pageParam.total = res.data.total * 1;

                // 并行合并图片：先为每道题准备 promise，然后使用 Promise.all 并发执行
                const processedQuestions = await Promise.all(questionList.map(async (q) => {
                    q.answerShow = false;
                    q.parseShow = false;
                    const { sourceType, titleCoordinates, answerCoordinates, parseCoordinates } = q;

                    if (sourceType === 2) {
                        try {
                            const [questionImg, answerImg, parseImg] = await Promise.all([
                                mergeImage(this.uploadPaperUrls, titleCoordinates),
                                mergeImage(this.answerUrls, answerCoordinates),
                                mergeImage(this.answerUrls, parseCoordinates),
                            ]);
                            q.questionImg = questionImg || '';
                            q.answerImg = answerImg || '';
                            q.parseImg = parseImg || '';
                        } catch (e) {
                            // 如果合并过程中某张图失败，记录空字符串并继续，避免阻塞全部渲染
                            q.questionImg = q.questionImg || '';
                            q.answerImg = q.answerImg || '';
                            q.parseImg = q.parseImg || '';
                        }
                    }

                    return q;
                }));

                this.questionList = processedQuestions;

                // 缓慢滚动到顶部
                this.scrollToTop();
            }

            instance.close();
        },

        scrollToTop() {
            // 等待 DOM 更新完成
            this.$nextTick(() => {
                const container = document.querySelector('.content_right');
                if (container) {
                    container.scrollTo({ top: 0, behavior: 'smooth' });
                }
            });
        },


        async _markStudentErrorQuestion(question, markStatus) {
            const res = await markStudentErrorQuestion({
                questionId: question.questionId,
                examId: this.examId,
                subjectCode: this.subjectCode,
                markStatus
            })

            if (res.code === 200) {
                this.$message.success('操作成功');
                await this._queryStudentErrorQuestion();
            } else {
                this.$message.error(res.message || '操作失败');
            }
        },

        async handleCurrentChange(page) {
            this.pageParam.pageNum = page;
            await this._queryStudentErrorQuestion();
        },

        hasTuozhan() {
            // 查看题目中第一个 变式题为空 的题目
            const questionWithVariation = this.questionList.find(q => !q.variationQuestion);

            if (questionWithVariation) {
                return false; // 存在题目没有变式题
            }

            return true; // 所有题目都有变式题
        },

        downLoadPapers() {
            const hasVariation = this.hasTuozhan();
            if (!hasVariation) {
                confirm('教师还未确认变式题，是否继续下载？', () => {
                    this.downloadDialogVisible = true;
                    this.isVariation = 1;
                })
            } else {
                this.downloadDialogVisible = true;
                this.isVariation = 1;
            }
        }
    },
}
</script>

<style scoped lang="scss">
.flex {
    display: flex;
    margin-bottom: 10px;

    .flex_left {
        width: 80px;
    }

    .flex_right {
        flex: 1;
        display: flex;
        flex-wrap: wrap;
    }
}

.bg_easy {
    background-color: #3BA272 !important;
}

.bg_medium {
    background-color: #5470C6 !important;
}

.bg_hard {
    background-color: #EE6666 !important;
}


.select_box {
    background-color: #ffffff;
    border-radius: 10px;
    padding: 10px;
    margin-bottom: 10px;
}

.content {
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 10px;
}

.right_btn {
    display: flex;
    justify-content: flex-end;
    margin-bottom: 10px;
}

.question_card {
    margin-bottom: 20px;
    border: 1px solid #ebeef5;
    border-radius: 10px;
    overflow: hidden;

    .card_top {
        padding: 20px;
    }

    .card_top_info {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20px;

        .left {
            display: flex;
            align-items: center;

            span {
                font-size: 14px;
            }

            .tag {
                color: #ffffff;
                padding: 4px 5px;
                font-size: 12px;
                background-color: #F56C6C;
                border-radius: 2px;
                position: relative;

                &::before {
                    content: '';
                    position: absolute;
                    left: -5px;
                    top: 50%;
                    transform: translateY(-50%);
                    width: 0;
                    height: 0;
                    border-top: 5px solid transparent;
                    border-bottom: 5px solid transparent;
                    border-right: 5px solid #EE6666;
                }
            }
        }
    }

    .number {
        color: #ffffff;
        font-size: 14px;
        padding: 5px 9px;
        background-color: #2E64FA;
        border-radius: 4px;
    }

    .btn_span {
        color: #2E64FA;
        font-size: 14px;
        padding: 5px 9px;
        border: 1px solid #2E64FA;
        border-radius: 4px;
        cursor: pointer;
        margin-right: 10px;

        &.active {
            color: #ffffff;
            background-color: #2E64FA;
            border-radius: 4px;
        }
    }

    .gray {
        color: #999;
    }

    .black {
        color: #333;
    }

    .blue {
        color: #2E64FA;
    }

    .question_content {
        margin-bottom: 20px;
    }

    .yuwen {
        margin-top: 20px;

        .question_list {
            margin-top: 20px;
            height: 100px;
            padding-top: 20px;
            border-top: 1px solid #EBEEF5;
        }
    }

    .card_footer {
        display: flex;
        align-items: center;
        padding-top: 20px;
        border-top: 1px solid #EBEEF5;

        .footer_item {
            margin-right: 40px;
        }
    }

    .card_buttom {
        background-color: #f7f7f8;
        padding: 15px 20px;

        .btn_box {
            display: flex;
            justify-content: flex-end;

            span {
                cursor: pointer;
            }
        }

        .content {
            padding: 20px;
            background-color: #ffffff;
            margin-top: 20px;
            border-radius: 10px;

            .content_inner {
                border: 2px dotted #DCDFE6;
                border-radius: 4px;
                padding: 10px;
            }
        }

        .parseShow_content {
            position: relative;

            &::before {
                content: '';
                position: absolute;
                right: 20px;
                /* 根据需要调整三角水平位置 */
                top: 24px;
                /* 三角放置在外部，超出上方 */
                width: 0;
                height: 0;
                border-left: 10px solid transparent;
                border-right: 10px solid transparent;
                border-bottom: 12px solid #ffffff;
                z-index: 2;
            }
        }

        .answerShow_content {
            position: relative;

            &::before {
                content: '';
                position: absolute;
                right: 20px;
                /* 根据需要调整三角水平位置 */
                top: 24px;
                /* 三角放置在外部，超出上方 */
                width: 0;
                height: 0;
                border-left: 10px solid transparent;
                border-right: 10px solid transparent;
                border-bottom: 12px solid #ffffff;
                z-index: 2;
            }
        }
    }

    ::v-deep .qml-answer {
        margin-left: 0;
        margin-bottom: 0;
    }

    ::v-deep .qml-explanation .qml-seg p {
        margin-left: 0 !important;
    }

    ::v-deep .qml-explanation .qml-seg p,
    ::v-deep .qml-exps-sq {
        margin-left: 0 !important;
    }

}
</style>