<template>
    <div class="question-box">
        <div style="width:100%;" v-show="type===1">
            <slot></slot>
        </div>
        <div class="p-8">
            <!-- 展示 -->
            <div class="question-des" v-show="type===1">
                <a-spin :spinning="spinning">
                    <div class="row-box question-describe" v-html="$options.filters.concatTIP(data.html?data.html:'')">
                    </div>
                    <div class="question-answer" ref="QDes">
                        <div class="row-box flex">
                            <div class="green-btn">答案:</div>
                            <template v-if="data.questionCategory!=1">
                                <div class="html-box" v-html="$options.filters.concatTIP(data.answer?data.answer:'')">
                                </div>
                            </template>
                            <template v-if="data.questionCategory==1">
                                <div>{{String(data.answer).toLocaleLowerCase()=='true'?'正确':'错误'}}</div>
                            </template>
                        </div>
                        <div class="row-box flex">
                            <div class="green-btn">解析:</div>
                            <div class="html-box" v-html="$options.filters.concatTIP(data.analysis?data.analysis:'')">
                            </div>
                        </div>
                    </div>
                </a-spin>
            </div>
            <!-- 编辑 -->
            <div class="edit-box" v-show="type===2">
                <a-spin :spinning="spinning">
                    <div class="edit-top flex-align">
                        <div class="flex-items">
                            <div class="blue-dot">
                                {{index+1}}
                            </div>
                            <span>{{data.disciplineQuestionTypeName}}</span>
                        </div>
                        <div>
                            <a class="m-r8" v-show="steps==1" @click="changeStep(2)">下一步</a>
                            <a class="m-r8" v-show="steps==2" @click="changeStep(1)">上一步</a>
                            <a class="m-r8" v-show="steps==2" @click="saveEdit">保存</a>
                            <a class="m-r8" @click="clearData">放弃</a>
                        </div>
                    </div>
                    <!-- 内容开始 -->
                    <div class="p-8" v-show="steps==1">
                        <div>题目：</div>
                        <Editor v-model="timuHtml" :isClear="false" />
                        <!-- 客观题选项 -->
                        <template v-if="data.questionCategory==0">
                            <div class="m-t16">选项：</div>
                            <div class="flex-align" v-for="(item,index) in html1" :key="item.id">
                                <span class="cards cards-dots cards-small">{{toLetter(index)}}</span>
                                <div class="m-t16" style="width:100%">
                                    <Editor v-model="item.html" />
                                </div>
                                <a class="qustion-li-delete" @click="delOption(item,index)">删除</a>
                            </div>
                            <a-button v-if="html1.length<10" type="primary" @click="addOption" class="m-t16">增加选项
                            </a-button>
                        </template>
                        <div class="edit-answer">
                            <div>答案：</div>
                            <!-- 客观题 -->
                            <template v-if="data.questionCategory==0">
                                <a-button-group>
                                    <a-radio-button v-for="(item,index) in html1" @click="multipleChange(item)"
                                        :class="{'ant-radio-button-wrapper-checked':item.isAnswer}" :key="item.id"
                                        :value="item">{{toLetter(index)}}</a-radio-button>
                                </a-button-group>
                            </template>
                            <!-- 判断题 -->
                            <template v-if="data.questionCategory==1">
                                <a-radio-group :value="html2.toLocaleLowerCase()=='true'" @change="singleChange">
                                    <a-radio-button :value="true">正确</a-radio-button>
                                    <a-radio-button :value="false">错误</a-radio-button>
                                </a-radio-group>
                            </template>
                            <!-- 其他题型 -->
                            <template v-if="data.questionCategory==2">
                                <Editor v-model="html2" />
                            </template>
                        </div>
                        <div>解析：</div>
                        <Editor v-model="html3" :isClear="false" />
                    </div>
                    <!-- 这里不能用v-show,焦点获取会有问题 -->
                    <div v-if="steps==2">
                        <div>版式：</div>
                        <Editor v-model="formatHtml" :isClear="false" />
                    </div>
                </a-spin>
            </div>
        </div>
    </div>
</template>
<script>
    import { QuestionResolveTaskGetInfo, QuestionGetInfo, QuestionUpdateOrigin, QuestionUpdate } from '@/api/api'
    import { stringToDom, domToStirng } from '@/utils/tools'
    import Editor from '@/components/Editor.vue'
    const fnObj = {
        'QuestionResolveTaskGetInfo': (data) => QuestionResolveTaskGetInfo(data),
        'QuestionGetInfo': (data) => QuestionGetInfo(data),
        'QuestionUpdateOrigin': (data, params) => QuestionUpdateOrigin(data, params),
        'QuestionUpdate': (data, params) => QuestionUpdate(data, params),
    }
    export default {
        components: {
            Editor
        },
        props: {
            index: {
                type: Number,
                default: 0
            },
            details: {
                type: Boolean,
                default: false
            },
            data: {
                type: Object,
                default: () => {
                    return {
                        html: '',
                        answer: '',
                        analysis: '',
                    }
                }
            }
        },
        data() {
            return {
                spinning: false,
                type: 1,//1查看 2编辑
                showDetails: this.details, //是否展示详情
                answerHeight: 0,    //答案和解析得高度
                infoDetails: {},//试题详情
                editArr: [],//正在被编辑的
                steps: 1,// 1编辑题 2编辑版式
                questionHtml: '',
                editType: null,//1解析试题的 2试题的
                addID: 0
            }
        },
        computed: {
            //版式
            formatHtml: {
                set(val) {
                    this.questionHtml = val;
                },
                get() {
                    if (this.data.questionCategory == 0) {
                        let str = '';
                        let arr = this.editArr.filter(item => item.resolveType == 1);
                        str = this.timuHtml + arr.reduce((total, item, index) => {
                            //这种好看些，但wps上不知道是不是样式不兼容展示会换行
                            // let optionHTML = '<br/><div style="display:flex;align-items:center"><span>' + this.toLetter(index) + '.&nbsp;</span>' + '<div style="display:flex;align-items:center">' + item.html + '</div></div>'
                            //这种选项标签会被文字包围不好看
                            let optionHTML = stringToDom(item.html);
                            var oDom = document.createElement('span');
                            oDom.innerHTML = this.toLetter(index) + '. ';
                            let arr = optionHTML.getElementsByClassName('MsoNormal');
                            if (arr.length > 0) {
                                optionHTML.getElementsByClassName('MsoNormal')[0].prepend(oDom)
                            } else {
                                let pArr = optionHTML.getElementsByTagName('p');
                                if (pArr.length > 0) {
                                    optionHTML.getElementsByTagName('p')[0].prepend(oDom)
                                }
                            }
                            optionHTML = domToStirng(optionHTML);
                            return total + optionHTML;
                        }, '');
                        return this.$options.filters.concatTIP(str);
                    } else {
                        return this.$options.filters.concatTIP(this.timuHtml);
                    }
                }
            },
            timuHtml: {
                set(val) {
                    let num = null;
                    if (this.data.questionCategory == 0) {
                        num = 0
                    } else {
                        num = 4
                    }
                    let arr = this.editArr.filter(item => item.resolveType == num)
                    if (arr.length > 0) {
                        arr[0].html = val
                    }
                },
                get() {
                    let oHtml = this.data.questionCategory == 0 ? this.html0 : this.html4;
                    return this.$options.filters.concatTIP(oHtml);
                }
            },
            //题干
            html0: {
                set(val) {
                    let arr = this.editArr.filter(item => item.resolveType == 1)
                    if (arr.length > 0) {
                        arr[0].html = val
                    }
                },
                get() {
                    if (this.editArr.length == 0) {
                        return ''
                    }
                    let _html=this.editArr.filter(item => item.resolveType == 0)[0].html;
                    if(_html===null||_html== 'null'){
                     _html=this.editArr.filter(item => item.resolveType == 4)[0].html;
                    }
                    return _html;
                }
            },
            //选项
            html1: {
                set() { },
                get() {
                    if (this.editArr.length == 0) {
                        return []
                    }
                    let data = this.editArr.filter(item => item.resolveType == 1).map(v => {
                        v.html = this.$options.filters.concatTIP(v.html);
                        return v;
                    });
                    return data;
                }
            },
            //答案
            html2: {
                set(val) {
                    let arr = this.editArr.filter(item => item.resolveType == 2)
                    if (arr.length > 0) {
                        arr[0].html = val
                    }
                },
                get() {
                    if (this.editArr.length == 0) {
                        return ''
                    }
                    let data = this.editArr.filter(item => item.resolveType == 2)[0].html
                    return this.$options.filters.concatTIP(data);
                }
            },
            //解析
            html3: {
                set(val) {
                    let arr = this.editArr.filter(item => item.resolveType == 3)
                    if (arr.length > 0) {
                        arr[0].html = val
                    }
                },
                get() {
                    if (this.editArr.length == 0) {
                        return ''
                    }
                    let data = this.editArr.filter(item => item.resolveType == 3)[0].html;
                    return this.$options.filters.concatTIP(data);
                }
            },
            //题干和答案
            html4: {
                set(val) {
                    let arr = this.editArr.filter(item => item.resolveType == 4)
                    if (arr.length > 0) {
                        arr[0].html = val
                    }
                },
                get() {
                    if (this.editArr.length == 0) {
                        return ''
                    }
                    return this.editArr.filter(item => item.resolveType == 4)[0].html;
                }
            },
            //完整试题
            html5: {
                set(val) {
                    let arr = this.editArr.filter(item => item.resolveType == 5)
                    if (arr.length > 0) {
                        arr[0].html = val
                    }
                },
                get() {
                    if (this.editArr.length == 0) {
                        return ''
                    }
                    return this.editArr.filter(item => item.resolveType == 5)[0].html;
                }
            },
        },
        mounted() {
            this.answerHeight = this.$refs.QDes.offsetHeight;
            if (!this.showDetails) {
                this.$refs.QDes.style.height = 0;
            }
        },
        watch: {
            showDetails(nval) {
                if (nval) {
                    this.$refs.QDes.style.height = this.answerHeight + 'px';
                } else {
                    this.$refs.QDes.style.height = 0;
                }
            }
        },
        methods: {
            showLoading(bool = false) {
                this.spinning = bool;
            },
            changeStep(num) {
                if (num == 2 && this.data.questionCategory == 0) {
                    try {
                        this.html1.forEach(item => {
                            if (!item.html) {
                                this.$message.error('您还有选项尚未完善');
                                throw Error()
                            }
                        })
                    } catch (err) {
                        return;
                    }
                }
                this.steps = num;
            },
            //增加选项
            addOption() {
                this.editArr.push({
                    html: '',
                    resolveType: 1,
                    isAnswer: false,
                    id: 'test' + String(this.addID)
                })
                this.addID = this.addID + 1;
                console.log(this.addID, 'this.addID')
            },
            //删除选项
            delOption(data, index) {
                this.editArr = this.editArr.filter(item => item.id != data.id)
            },
            toLetter(num) {
                return String.fromCharCode(num + 65)
            },
            init() {
                this.$refs.QDes.style.height = 0;
            },
            //查看,取消查看详情
            toggle() {
                let oHeight = this.$refs.QDes.style.height;
                this.showDetails = parseInt(oHeight) == 0 ? true : false
            },
            //编辑
            toEdit(num, clearAnswer = false) { //num 1(解析) 2(试题)
                this.editType = num;
                if (this.$store.state.questionEdit) {
                    this.$message.error('您还有题目正在编辑，请先完成编辑');
                    return;
                }
                this.$store.commit('changeQuestionEdit', true)
                this.spinning = true;
                this.type = 2;
                let data = {}, name = '';
                if (num == 1) {
                    data = {
                        resoleTaskQuestionId: this.data.id
                    }
                    name = 'QuestionResolveTaskGetInfo';
                } else {
                    data = {
                        id: this.data.id
                    }
                    name = 'QuestionGetInfo';
                }
                fnObj[name](data).then(res => {
                    console.log(res, '试题详情')
                    this.infoDetails = res;
                    this.editArr = JSON.parse(JSON.stringify(res.resolves));
                    console.log(this.editArr, 'this.editArr')
                    //更改题型如果是判断题就清空答案
                    console.log(this.data._questionCategory,'toEdit getquestionCategory')
                    if (this.data.questionCategory == 1) {
                        let arr = this.editArr.filter(item => item.resolveType == 2);
                        if (arr[0].html == null || arr[0].html == 'null') {
                            arr[0].html = '';
                        }
                        if (clearAnswer && arr.length > 0) {
                            arr[0].html = 'False';
                        }
                    }
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            //保存编辑
            saveEdit() {
                if (!this.questionHtml) {
                    this.$message.error('版式不能为空！')
                    return;
                }
                this.spinning = true;
                console.log(this.editArr, 'editArr')
                let stemHtml = '', answerHtml = '';
                if (this.data.questionCategory == 0) {
                    stemHtml = this.editArr.filter(item => item.resolveType == 0).length > 0 ? this.editArr.filter(item => item.resolveType == 0)[0].html : ''
                } else {
                    stemHtml = this.editArr.filter(item => item.resolveType == 4).length > 0 ? this.editArr.filter(item => item.resolveType == 4)[0].html : ''
                }

                if (this.data.questionCategory == 0) {
                    let answerArr = this.editArr.filter(item => item.resolveType == 1);
                    answerArr.forEach((v, index) => {
                        if (v.isAnswer) {
                            answerHtml += this.toLetter(index)
                        }
                    })
                    answerHtml = answerHtml.split('').join(',');
                } else {
                    let answerArr = this.editArr.filter(item => item.resolveType == 2);
                    answerHtml = answerArr[0].html;
                }
                let analysisHtml = this.editArr.filter(item => item.resolveType == 3).length > 0 ? this.editArr.filter(item => item.resolveType == 3)[0].html : ''
                let data = {
                    questionHtml: this.$options.filters.clearTIP(this.questionHtml),
                    stemHtml: this.$options.filters.clearTIP(stemHtml),
                    answerHtml: this.$options.filters.clearTIP(answerHtml),
                    analysisHtml: this.$options.filters.clearTIP(analysisHtml),
                    options: this.data.questionCategory == 0 ? this.editArr.filter(item => item.resolveType == 1).map(v => {
                        if (String(v.id).indexOf('test') > -1) {
                            v.id = null;
                        }
                        v.html = this.$options.filters.clearTIP(v.html)
                        return v;
                    }) : [],
                    questionCategory: this.data.questionCategory
                }
                console.log(data, 'data')
                let params = {};
                if (this.editType == 1) {
                    params = {
                        questionOriginId: this.data.questionOriginId
                    }
                    name = 'QuestionUpdateOrigin';
                } else {
                    params = {
                        id: this.data.id
                    }
                    name = 'QuestionUpdate';
                }
                fnObj[name](data, params).then(res => {
                    this.$message.success('修改成功！');
                    this.cancleEdit();
                    this.data.html = data.questionHtml;
                    this.data.answer = data.answerHtml;
                    this.data.analysis = data.analysisHtml;
                    this.addID = 0;
                    this.spinning = false;
                }).catch(err => {
                    this.spinning = false;
                })
            },
            clearData(){
                if(this.data.hasOwnProperty("_questionCategory")){
                    this.data.disciplineQuestionTypeName = this.data._disciplineQuestionTypeName;
                    this.data.disciplineQuestionTypeId = this.data._disciplineQuestionTypeId;
                    this.data.questionCategory = this.data._questionCategory;
                    delete this.data._disciplineQuestionTypeName
                    delete this.data._disciplineQuestionTypeId
                    delete this.data._questionCategory
                }
                this.cancleEdit();
            },
            //放弃编辑
            cancleEdit() {
                this.infoDetails = {};//试题详情
                this.editArr = [];//正在被编辑的
                this.steps = 1;
                this.type = 1;
                this.addID = 0;
                this.$store.commit('changeQuestionEdit', false);
            },
            //判断，单选切换答案
            singleChange(e) {
                console.log(e.target.value)
                console.log(this.html2, 'html2')
                let arr = this.editArr.filter(item => item.resolveType == 2)
                if (arr.length > 0) {
                    arr[0].html = String(e.target.value)
                }
            },
            // 多选切换答案
            multipleChange(value) {
                console.log(value, 'value')
                value.isAnswer = !value.isAnswer;
            },
        }
    }
</script>
<style scoped lang="less">
    .html-box {
        flex: 1;
        word-break: break-all;
    }

    .question-box {
        flex: 1;
        position: relative;
    }

    .question-des {
        margin-top: 8px;
    }

    .row-box {
        width: 100%;
        margin-bottom: 16px;
        box-sizing: border-box;
    }

    .green-btn {
        background-color: #03b615;
        border-radius: 3px;
        padding: 0 8px;
        color: #fff;
        width: 50px;
        height: 25px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 8px;
    }

    .gray-text {
        color: #7f7f7f;
    }

    .question-answer {
        overflow: hidden;
        transition: all 0.6s;
    }

    .blue-dot {
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background-color: #1890ff;
        color: #fff;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
    }

    .edit-top {
        border-bottom: 1px solid #1890ff;
    }

    .edit-answer {
        margin: 16px 0;
        display: flex;
        flex-direction: column;
    }

    .cards {
        width: 32px;
        height: 32px;
        border-radius: 50%;
        text-align: center;
        line-height: 32px;
        background-color: #f2f2f2;
        margin-right: 10px;
        margin-bottom: 10px;
        cursor: pointer;
        transition: 300ms;
        display: inline-block;
    }

    .cards-dots {
        margin: 0;
        margin-right: 10px;
    }

    .cards-small {
        width: 24px;
        height: 24px;
        line-height: 24px;
    }

    .qustion-li-delete {
        width: 50px;
        text-align: center;
    }
</style>