<template>
    <div class="test-box">
        <div class="test-paper flex">
            <!-- 装订线 -->
            <div class="stander-box" ref="standerBox"></div>
            <div class="line-box" v-show="settingGroup('gutter').isSet">
                <div class="line-group" ref="lineGroup">
                    <div class="line-info flex m-b8" style="width:100%;" v-if="settingGroup('gutter').isSet">
                        <TextEdit v-model="settingGroup('gutter').realParam.WriteText" str="装订栏信息" />
                    </div>
                    <myDivider ref="myDivider" />
                </div>
            </div>
            <div class="test-content">
                <div class="test-head">
                    <TextEdit v-if="settingGroup('mainTitle').isSet" v-model="settingGroup('mainTitle').realParam.Name"
                        str="试卷主标题" size="20" weight="bold" style="color:#000000" />
                    <TextEdit str="试卷副标题" size="20" v-model="settingGroup('subTitle').realParam.Name"
                        v-if="settingGroup('subTitle').isSet" />
                    <div class="flex m-b8" style="width:100%;" v-if="settingGroup('candidateInformationBar').isSet">
                        <TextEdit v-model="settingGroup('candidateInformationBar').realParam.Name" str="考生信息栏" />
                    </div>
                    <div class="flex" style="width:100%;" v-if="settingGroup('testInformationBar').isSet">
                        <TextEdit str="考试信息栏" v-model="settingGroup('testInformationBar').realParam.Name" />
                    </div>
                </div>
                <div class="flex" style="width:100%;" v-if="settingGroup('attentionNotice').isSet">
                    <span style="font-weight: bold;">注意事项：</span>
                    <TextEdit str="注意事项" :textCenter="false" v-model="settingGroup('attentionNotice').realParam.Name" />
                </div>
                <div v-if="settingGroup('subsection').isSet" class="subsection-box">第1卷</div>
                <a-spin :spinning="spinning">
                    <template v-if="questionGroup.length>0">
                        <div v-for="(item,index) in questionGroup" :key="item.type">
                            <div class="gray-border flex-align">
                                <div class="flex" style="font-weight: bolder;width:100%;">
                                    <span>{{(index+1)|NoToChinese}}、</span>
                                    <span v-if="!settingGroup('auestionTypeTitle').isSet">{{qtSetting(item)}}</span>
                                    <TextEdit :textCenter="false" v-if="settingGroup('auestionTypeTitle').isSet"
                                        v-model="item.str" @callBack="(data)=>callBack(data,item)" />
                                </div>
                                <div class="gray-border-action">
                                    <!-- <a class="m-r8">上移</a>
                                    <a class="m-r8">下移</a> -->
                                    <a class="m-r8" @click="editAnswerSheet(item)">答题卡样式</a>
                                    <a class="m-r8" @click="_PaperQuestionDeleteList(item)">移出题型</a>
                                </div>
                            </div>
                            <div class="flex gray-border" style="padding:0" v-for="(v,index2) in item.data" :key="v.id">
                                <span class="test-num">{{index2+1}}.</span>
                                <QuestionItem :ref="'QuestionItem'+v.id" :data="v">
                                    <div class="question-action" style="padding:0">
                                        <div class="flex-align">
                                            <div></div>
                                            <div>
                                                <!-- <a class="m-r16">替换</a> -->
                                                <a class="m-r16" @click="_PaperQuestionSort(v.id,0,item,index2)">上移</a>
                                                <a class="m-r16" @click="_PaperQuestionSort(v.id,1,item,index2)">下移</a>
                                                <a class="m-r16" @click="showDetail(v.id)">详情</a>
                                                <a class="m-r16" @click="_PaperQuestionDelete(v)">移出试卷</a>
                                            </div>
                                        </div>
                                    </div>
                                </QuestionItem>
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <a-empty />
                    </template>
                </a-spin>
            </div>
        </div>
        <div class="test-set">
            <a-button type="primary" class="score-set m-b8" @click="SortSet">排序设置</a-button>
            <a-button type="primary" class="score-set" @click="scoreSet">分值设置</a-button>
            <div class="blue-title">试卷结构设置</div>
            <div class="box-group">
                <div>
                    <a-checkbox v-for="item in papaerInfo.paperSetting" :key="item.id"
                        v-if="item.code!='auestionTypeTitle'" @change="e=>onChange(e,item)" :checked="item.isSet">
                        {{item.name}}
                    </a-checkbox>
                </div>
            </div>
            <template v-if="settingGroup('answerSheet').isSet">
                <div class="blue-title">答题卡设置</div>
                <div class="box-group">
                    <div style="margin:4px 0;">类型：</div>
                    <a-radio-group v-model="settingGroup('answerSheet').realParam.AnswerSheetStyle">
                        <a-radio :value="0">
                            机读卡
                        </a-radio>
                        <a-radio :value="1">
                            人阅卡
                        </a-radio>
                    </a-radio-group>
                    <div style="margin:4px 0;">纸张大小：</div>
                    <a-radio-group v-model="settingGroup('answerSheet').realParam.AnswerSheetSize">
                        <a-radio :value="0">
                            A4（不分栏）
                        </a-radio>
                        <a-radio :value="1">
                            A3（分两栏）
                        </a-radio>
                        <a-radio :value="2">
                            A3（分三栏）
                        </a-radio>
                    </a-radio-group>
                    <div class="margin-h6">
                        <span>准考证号位数：</span>
                        <a-input-number v-model="settingGroup('answerSheet').realParam.CandidateNoCount"
                            id="inputNumber" :min="1"
                            :max="settingGroup('answerSheet').realParam.AnswerSheetSize==1?12:8" size="small" />
                    </div>
                    <div class="margin-h6">
                        <span>是否需要二维码：</span>
                        <a-radio-group v-model="settingGroup('answerSheet').realParam.IsShowQrCode">
                            <a-radio :value="true">
                                是
                            </a-radio>
                            <a-radio :value="false">
                                否
                            </a-radio>
                        </a-radio-group>
                    </div>
                </div>
            </template>
            <a-button :loading="setLoading" type="primary" class="score-set" @click="_SavePaperSetting">保存设置</a-button>
            <div class="blue-title">知识点统计</div>
            <div class="box-group">
                <div class="m-b8">
                    章节：{{papaerInfo.paperChapters||'无'}}
                </div>
                <div class="m-b8">
                    知识点：{{papaerInfo.paperKnowledgePoints||'无'}}
                </div>
                <div class="flex-around">
                    <a-button :loading="produceLoading" type="primary" @click="_PaperProduce">生成试卷</a-button>
                    <a-button :loading="saveLoading" type="primary" @click="_PaperSave">保存试卷</a-button>
                </div>
            </div>
        </div>
        <ScoreSet ref="ScoreSet" />
        <PaperProduce ref="PaperProduce" />
        <SortSet ref="SortSet" />
        <EditAnswerSheet ref="EditAnswerSheet" />
    </div>
</template>
<script>
    import QuestionItem from '@/components/Questions/QuestionItem'
    import PaperProduce from './components/PaperProduce.vue'
    import ScoreSet from './components/ScoreSet.vue'
    import SortSet from './components/SortSet.vue'
    import myDivider from '@/components/myDivider'
    import TextEdit from '@/components/TextEdit'
    import EditAnswerSheet from './components/EditAnswerSheet.vue'
    import { groupArr } from '@/utils/tools'
    import { PaperGetPaperInfo, SavePaperSetting, GetDisciplineSortSetting, PaperQuestionSort, PaperQuestionDelete, PaperQuestionDeleteList, PaperSave } from '@/api/api'
    export default {
        components: {
            QuestionItem,
            ScoreSet,
            myDivider,
            TextEdit,
            PaperProduce,
            SortSet,
            EditAnswerSheet
        },
        data() {
            return {
                spinning: false,
                setLoading: false,
                saveLoading: false,
                produceLoading: false,
                examId: '',
                lineHeight: 0,
                checkedList: [],
                indeterminate: true,
                subtitle: '',//副标题
                papaerInfo: {
                    paperQuestions: [],
                    paperSetting: []
                },
                totalScore: 0,//总分
                qualifiedScore: 0,//合格分
            }
        },
        computed: {
            settingGroup() {
                return function (key) {
                    let len = this.papaerInfo.paperSetting.length;
                    if (len > 0) {
                        let arr = this.papaerInfo.paperSetting.filter(v => v.code == key)
                        let obj = arr.length > 0 ? arr[0] : {};
                        return obj
                    } else {
                        return {};
                    }
                }
            },
            questionGroup() {
                let oArr = groupArr(this.papaerInfo.paperQuestions, 'disciplineQuestionTypeId', 'disciplineQuestionType')
                let paperSetting = this.papaerInfo.paperSetting;
                if (paperSetting.length > 0) {
                    let arr = paperSetting.filter(v => v.code == 'auestionTypeTitle')
                    let obj = arr.length > 0 ? arr[0] : {};
                    if (obj.realParam && obj.realParam.length > 0) {
                        oArr.forEach(item => {
                            let o = obj.realParam.filter(v => v.DisciplineQuestionTypeId == item.type);
                            if (o.length > 0) {
                                item.str = o[0].Title;
                            } else {
                                item.str = item.name;
                            }
                        })
                    }
                }
                return oArr;
            },
            //题型名称
            qtSetting() {
                return (data) => {
                    console.log(data, '每个的')
                    let len = this.papaerInfo.paperSetting.length;
                    if (len > 0) {
                        let arr = this.papaerInfo.paperSetting.filter(v => v.code == 'auestionTypeTitle')
                        let obj = arr.length > 0 ? arr[0] : {};
                        return '66'
                        if (obj.realParam && obj.realParam.length > 0) {
                            console.log(obj.realParam, 'obj.realParam6666666666')
                            let o = obj.realParam.filter(v => v.DisciplineQuestionTypeId == data.type)
                            if (o.length > 0) {
                                return o[0].Title
                            } else {
                                return data.str;
                            }
                        }
                    } else {
                        return data.str;
                    }
                }
            }
        },
        mounted() {
            this.examId = this.$route.query.examId
            console.log(this.examId, 'this.examId')
            this.lineHeight = this.$refs.standerBox.offsetHeight;
            let lineHeight = this.$refs.standerBox.offsetHeight;
            this.$refs.lineGroup.style.width = this.$refs.standerBox.offsetHeight + 'px';
            this.$refs.lineGroup.style.transform = 'translate(' + (-lineHeight) + 'px) rotate(-90deg)';
            console.log(this.$refs.lineGroup.style, 'this.lineHeight')
            // this._GetDisciplineSortSetting();
            this._PaperGetPaperInfo();
        },
        methods: {
            callBack(data, item) {
                let len = this.papaerInfo.paperSetting.length;
                let params = {};
                if (len > 0) {
                    let arr = this.papaerInfo.paperSetting.filter(v => v.code == 'auestionTypeTitle')
                    let obj = arr.length > 0 ? arr[0] : {};
                    console.log(obj, 'obj')
                    if (obj.realParam && obj.realParam.length > 0) {
                        let o = obj.realParam.filter(v => v.DisciplineQuestionTypeId == item.type)
                        let params = {};
                        if (o.length > 0) {
                            params = o[0];
                            params.Title = data;
                        } else {
                            params = {
                                DisciplineQuestionTypeId: item.type,
                                Title: data
                            }
                            obj.realParam.push(params)
                        }
                    }
                }
            },
            //答题卡样式模态框
            editAnswerSheet(item) {
                this.$refs.EditAnswerSheet.showModal(item, this.papaerInfo)
            },
            //排序设置
            SortSet() {
                this.$refs.SortSet.showModal(this.questionGroup)
            },
            //生成试卷
            _PaperProduce() {
                this.$refs.PaperProduce.showModal(this.examId)
            },
            //保存试卷
            _PaperSave() {
                if (this.qualifiedScore == 0) {
                    this.$message.error('请先在分值设置中设置合格分！')
                    return;
                }
                this.saveLoading = true;
                let questionArr = this.papaerInfo.paperQuestions,
                    arr = [];
                questionArr.forEach(item => {
                    arr.push({
                        paperQuestionId: item.id,
                        singleScore: item.singleScore
                    })
                })
                let data = {
                    id: this.examId,
                    totalScore: this.totalScore,
                    passingScore: this.qualifiedScore,
                    paperQuestions: arr
                }
                console.log(data, 'data')
                PaperSave(data).then(res => {
                    this.$message.success('保存成功！');
                    this.saveLoading = false;
                }).catch(err => {
                    this.saveLoading = false;
                })
            },
            //删除试题
            _PaperQuestionDelete(data) {
                this.spinning = true;
                let params = {
                    id: data.id
                }
                PaperQuestionDelete(params).then(res => {
                    this.$message.success('移出成功！')
                    let arr = this.papaerInfo.paperQuestions;
                    this.papaerInfo.paperQuestions = arr.filter(item => {
                        return item.id != data.id;
                    })
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            //删除题型
            _PaperQuestionDeleteList(data) {
                this.spinning = true;
                console.log(data, 'data')
                let arr = this.papaerInfo.paperQuestions,
                    delArr = [];
                arr.forEach(item => {
                    if (item.disciplineQuestionTypeId == data.type) {
                        delArr.push(item.id)
                    }
                })
                let params = {
                    idList: delArr
                }
                PaperQuestionDeleteList(params).then(res => {
                    this.$message.success('移出成功！')
                    this.papaerInfo.paperQuestions = arr.filter(item => {
                        return item.disciplineQuestionTypeId != data.type;
                    })
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            //试题排序
            _PaperQuestionSort(id, num, item) {

                let data = {
                    SortType: num
                }, params = {
                    paperQuestionId: id
                };
                console.log(id, 'id')
                console.log(item, 'item')

                if (num == 0) {
                    let index = item.data.findIndex(v => v.id == id);
                    if (index == 0) {
                        this.$message.error('该题已在此题型第一题！')
                        return;
                    }
                }
                if (num == 1) {
                    let index = item.data.findIndex(v => v.id == id);
                    if (index == item.data.length - 1) {
                        this.$message.error('该题已是此题型最后一题！')
                        return;
                    }
                }
                this.spinning = true;
                console.log(this.papaerInfo, 'this.papaerInfo')
                PaperQuestionSort(num, params).then(res => {
                    this.$message.success('操作成功！')
                    let arr = this.papaerInfo.paperQuestions;
                    let arrIndex = '';
                    arr.forEach((v, k) => {
                        if (v.id == id) {
                            arrIndex = k
                        }
                    })
                    if (num == 0) {
                        arr[arrIndex - 1] = arr.splice(arrIndex, 1, arr[arrIndex - 1])[0];
                    }
                    if (num == 1) {
                        arr[arrIndex + 1] = arr.splice(arrIndex, 1, arr[arrIndex + 1])[0];
                    }
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            //保存设置
            _SavePaperSetting() {
                this.setLoading = true;
                console.log(this.papaerInfo.paperSetting, 'paperSetting')
                let arr = [];
                this.papaerInfo.paperSetting.forEach(item => {
                    if (item.isSet) {
                        arr.push({
                            paperSetId: item.id,
                            param: JSON.stringify(item.realParam)
                        })
                    }

                })
                console.log(arr, 'arr')
                let params = {
                    paperId: this.examId
                }
                SavePaperSetting(arr, params).then(res => {
                    this.$message.success('设置成功！')
                    this.setLoading = false;
                }).catch(err => {
                    this.setLoading = false;
                })
            },
            onChange(e, item) {
                if (this.$store.state.textIsEdit) {
                    this.$message.error('您当前有正在编辑的内容，请完成编辑！')
                    return;
                }
                let checked = e.target.checked
                item.isSet = checked;
                if (checked) {
                    let p1 = JSON.parse(item.defaultParam),
                        p2 = JSON.parse(item.param);
                    if (Object.prototype.toString.call(p1) == '[object Array]') {
                        console.log(p1, 'p1')
                        console.log(p2, 'p2')
                        item.realParam = [];
                        let arr = [...p1, ...p2];
                        arr.forEach(v => {
                            let len = item.realParam.filter(val => val.DisciplineQuestionTypeId == v.DisciplineQuestionTypeId).length;
                            if (len == 0) {
                                item.realParam.push(v);
                            }
                        })
                    } else {
                        item.realParam = {
                            ...p1,
                            ...p2
                        }
                    }
                } else {
                    item.realParam = item.param
                }
                console.log(e.target.checked, 'e.target.checked');
                console.log(item, 'item');
            },
            //试卷详情
            _PaperGetPaperInfo() {
                this.spinning = true;
                let data = {
                    paperId: this.examId
                }
                PaperGetPaperInfo(data).then(res => {
                    console.log(res, '试卷详情')
                    res.paperSetting.map(item => {
                        if (item.isSet) {
                            let p1 = JSON.parse(item.defaultParam),
                                p2 = JSON.parse(item.param);
                            if (Object.prototype.toString.call(p1) == '[object Array]') {
                                console.log(p1, 'p1')
                                console.log(p2, 'p2')
                                item.realParam = [];
                                let arr = [...p1, ...p2];
                                arr.forEach(v => {
                                    let len = item.realParam.filter(val => val.DisciplineQuestionTypeId == v.DisciplineQuestionTypeId).length;
                                    if (len == 0) {
                                        item.realParam.push(v);
                                    }
                                })
                                console.log(item.realParam, 'item.realParam')
                            } else {
                                item.realParam = {
                                    ...p1,
                                    ...p2
                                }
                            }
                        } else {
                            item.realParam = item.param
                        }
                        return item;
                    });
                    this.papaerInfo = res;
                    this.qualifiedScore = res.passingScore;
                    this.$refs.PaperProduce.qualifiedScore = res.passingScore;
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            showDetail(index) {
                this.$refs['QuestionItem' + index][0].toggle();
            },
            scoreSet() {
                this.$refs.ScoreSet.showModal(this.papaerInfo.paperQuestions);
            }
        }
    }
</script>
<style scoped>
    html,
    body {
        width: 100%;
        height: 100%;
    }

    .stander-box {
        width: 1px;
        height: 100%;
    }

    .line-box {
        width: 120px;
        height: 100%;
        /* writing-mode: vertical-lr; */
    }

    .line-group {
        height: 120px;
        transform-origin: right top;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
    }

    .line-info {
        margin-bottom: 32px;
    }

    .test-box {
        width: 100%;
        height: 100%;
        background-color: #f2f2f2 !important;
        display: flex;
        justify-content: space-between;
    }

    .test-paper {
        width: 1050px;
        height: 100%;
        background-color: #fff;
    }

    .test-set {
        width: 250px;
    }

    .test-content {
        padding: 16px;
        box-sizing: border-box;
        /* width:100%; */
        height: 100%;
        overflow: auto;
        /* background-color: pink; */
        flex: 1;
    }

    .test-head {
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
    }

    .subsection-box {
        background-color: #e8e8e8;
        padding: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-weight: bold;
        font-size: 28px;
        color: black
    }

    .gray-border {
        border: 1px solid transparent;
        padding: 8px;
    }

    .gray-border:hover {
        border: 1px solid rgba(232, 232, 232, 1);
    }

    .gray-border-action {
        display: none;
        width: 180px;
    }

    .gray-border:hover .gray-border-action {
        display: block;
    }

    .question-action {
        position: absolute;
        top: 0;
        right: 0;
        display: none;
        width: 100%;
    }

    .gray-border:hover .question-action {
        display: block;
    }

    .test-num {
        margin-top: 16px;
        margin-left: 8px;
    }

    .score-set {
        /* color: #fff;
        background-color: #1890ff; */
        width: 100%;
        font-size: 18px;
        /* padding: 8px 0; */
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
    }

    .blue-title {
        color: rgb(24, 144, 255);
        padding: 4px 8px;
        font-weight: bold;
    }

    .box-group {
        background-color: #fff;
        padding: 8px;
    }

    .margin-h6 {
        margin: 6px 0;
    }
</style>