<template>
    <div class="sz_body" v-loading="loading">
        <div @click="exportExcel" v-show="false">{{ lang.ssExport }}</div>
        <div style="font-size: 18px;margin-bottom: 20px;">{{ lang.ssScoringCount }}：<span class="color">{{ num }}</span>{{ lang.ssPerson }} {{ lang.ssTotalAverageScore }}：<span
                class="color">{{ num ? score ? (score / num).toFixed(1) : 0 : 0 }}</span></div>
        <div class="test_box" v-for="(item, index) in testList" :key="index">
            <div class="testTitle">{{ item.title }}</div>
            <template v-if="item.type == '1'">
                <div class="testContent" 
                    v-for="(item2, index2) in item.array"
                    :key="index + '-' + index2">
                    <div class="testContent_title">{{ index2 + 1 }}、{{ item2.title }}</div>
                    <div class="testContent_input">
                        <!-- <el-input v-model="item2.uscore" class="c_input" @change="numberPan(index, index2, item2.score)"
                            placeholder="请输入评分" /> -->
                        <span>{{ lang.ssAverageScore }}：</span>
                        <span class="color">{{ num ? item2.uscore ? (item2.uscore / num).toFixed(2) : 0 : 0 }}</span>
                    </div>
                </div>
            </template>
            
            <div v-if="item.type == '2'">
                <div class="test_ping" v-for="(answer, index2) in item.answerArray" :key="index + '-' + index2">
                    <span style="    min-width: fit-content;">{{ index2 + 1 }}.</span>
                    <span>{{ answer }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import { myMixin } from "@/mixins/mixin.js"

export default {
    mixins: [ myMixin ],
    props: {
        courseid: {
            type: String,
            default: ''
        },
        title: {
            type: String,
            default: ''
        },
    },
    data() {
        return {
            userid:"",
            testList: [
                {
                    title: this.lang.ssTeachingObjectives,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingObjectivesDesc,
                            score: 5,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssTeachingContent,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingContentDesc,
                            score: 5,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssTeachingProcess,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingProcessStructure,
                            score: 10,
                            uscore: 0,
                        },
                        {
                            title: this.lang.ssTeachingProcessLearning,
                            score: 10,
                            uscore: 0,
                        },
                        {
                            title: this.lang.ssTeachingProcessManagement,
                            score: 10,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssTeachingMethods,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingMethodsDesc,
                            score: 20,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssTeachingTools,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingToolsDesc,
                            score: 15,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssTeachingEvaluation,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingEvaluationDesc,
                            score: 10,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssInnovation,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssInnovationDesc,
                            score: 10,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssTeachingEffect,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssTeachingEffectDesc,
                            score: 5,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssBonusPoints,
                    type: '1',
                    array: [
                        {
                            title: this.lang.ssBonusPointsDesc,
                            score: 10,
                            uscore: 0,
                        }
                    ],
                },
                {
                    title: this.lang.ssComments,
                    type: '2',
                    answer: '',
                    answerArray: [],

                },
            ],
            num: 0,
            score: 0,
            loading: false,
            testArray: []
        }
    },
    mounted() {
        this.getList();
    },
    methods: {
        exportExcel() {
            try {


                var res = this.testArray;
                //如果value的json字段的key值和想要的headers值不一致时，可做如下更改
                //将和下面的Object.fromEntries结合，将json字段的key值改变为要求的excel的header值
                var array = [];
                for (var i = 0; i < res.length; i++) {
                    var _json = {};
                    _json[this.lang.ssSerialNumber] = i+1;
                    _json[this.lang.ssName] = res[i].username;
                    _json[this.lang.ssTeachingObjectives] = res[i]['test00'];
                    _json[this.lang.ssTeachingContent] = res[i]['test10'];
                    _json[this.lang.ssTeachingProcess + "-1" + this.lang.ssCourseStructure] = res[i]['test20'];
                    _json[this.lang.ssTeachingProcess + "-2" + this.lang.ssActivityDesign] = res[i]['test21'];
                    _json[this.lang.ssTeachingProcess + "-3" + this.lang.ssOrderManagement] = res[i]['test22'];
                    _json[this.lang.ssTeachingMethods] = res[i]['test30'];
                    _json[this.lang.ssTeachingTools] = res[i]['test40'];
                    _json[this.lang.ssTeachingEvaluation] = res[i]['test50'];
                    _json[this.lang.ssInnovation] = res[i]['test60'];
                    _json[this.lang.ssTeachingEffect] = res[i]['test70'];
                    _json[this.lang.ssBonusPoints] = res[i]['test80'];
                    _json[this.lang.ssTotalScore] = res[i]['sum'];
                    _json[this.lang.ssComments] = res[i]['ping'];
                    array.push(_json);
                }

                var XLSX = require("xlsx");
                const workbook = XLSX.utils.book_new(); //创建一个新的工作簿对象
                let ws = XLSX.utils.json_to_sheet(array); //将json对象数组转化成工作表
                // ws["!cols"] = [
                //     //设置每一列的宽度
                //     { wch: 50 },
                //     { wch: 50 },
                //     { wch: 50 },
                // ];
                XLSX.utils.book_append_sheet(workbook, ws, "sheet1"); //把sheet添加到workbook里，第三个参数是sheet名
                XLSX.writeFile(workbook, this.title+".xlsx");
                // const wopts = { bookType: "xlsx", bookSST: false, type: "array" };//写入的样式bookType:输出的文件类型，type：输出的数据类型，bookSST: 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
                // const wbout = XLSX.write(workbook, wopts);// 浏览器端和node共有的API,实际上node可以直接使用xlsx.writeFile来写入文件,但是浏览器没有该API
                // FileSaver.saveAs(new Blob([wbout], { type: "application/octet-stream" }), `${title} demo.xlsx`);//保存文件
                this.$message({
                    message: this.lang.ssExportSuccess,
                    type: "success",
                });

            } catch (e) {
                console.log(e, e.stack);
            }
        },
        numberPan(index, index2, score) {
            let _score = this.testList[index].array[index2].uscore
            if (/[^\d]/.test(_score) || _score < 0) {
                this.$message.error(this.lang.ssEnterPositiveInteger)
                this.testList[index].array[index2].uscore = 0
            }
            if (parseInt(_score) > parseInt(score)) {
                this.$message.error(this.lang.ssCannotEnterScoreAbove)
                this.testList[index].array[index2].uscore = score
            }
            this.$forceUpdate();
        },
        confirm() {
            let params = [
                {
                    cid: this.courseid,
                    uid: this.userid,
                    json: JSON.stringify(this.testList),
                },
            ];
            this.ajax
                .post(this.$store.state.api + "opCourseScore", params)
                .then((res) => {
                    console.log(res.data);
                    this.$message({
                        message: this.lang.ssAddSuccess,
                        type: "success",
                    });
                    this.getList();
                    this.$forceUpdate();
                })
                .catch((err) => {
                    console.error(err);
                });
        },
        getList() {
            let params =
            {
                cid: this.courseid,
            };
            this.loading = true
            this.ajax
                .get(this.$store.state.api + "getCourseScore", params)
                .then((res) => {
                    console.log(res.data);
                    if (res.data[0].length > 0) {
                        // this.testList = JSON.parse(res.data[0][0].json)
                        let data = res.data[0]
                        this.num = data.length
                        let sum = 0
                        for (var i = 0; i < data.length; i++) {
                            let item = data[i]
                            let _json = JSON.parse(item.json)
                            for (var j = 0; j < this.testList.length; j++) {
                                let test = this.testList[j]
                                if (test.type == '2') {
                                    if (_json[j].answer) {
                                        test.answerArray.push(_json[j].answer)
                                    }
                                } else {
                                    for (var k = 0; k < test.array.length; k++) {
                                        let _item = test.array[k]
                                        _item.uscore += _item.score / 5 * parseInt(_json[j].array[k].uscore)
                                        _item.num++
                                        sum += _item.score / 5 * parseInt(_json[j].array[k].uscore)
                                    }
                                }
                            }
                        }
                        this.score = sum
                        let testArray = []
                        for (var i = 0; i < data.length; i++) {
                            let item = data[i]
                            let _json = JSON.parse(item.json)
                            let _sum = 0
                            for (var j = 0; j < this.testList.length; j++) {
                                let test = this.testList[j]
                                if (test.type == '2') {
                                    if (_json[j].answer) {
                                        item['ping'] = _json[j].answer
                                    }else { 
                                        item['ping'] = ''
                                    }
                                } else {
                                    for (var k = 0; k < test.array.length; k++) {
                                        let _item = test.array[k]
                                        item['test'+j+k] =  _item.score / 5 * parseInt(_json[j].array[k].uscore)
                                        _sum += _item.score / 5 * parseInt(_json[j].array[k].uscore)
                                    }
                                }
                            }
                            item['sum'] = _sum
                            testArray.push(item)
                        }
                        this.testArray = testArray
                    }
                    this.loading = false
                    this.$forceUpdate();
                })
                .catch((err) => {
                    this.loading = false
                    console.error(err);
                });
        }
    },
}
</script>

<style scoped>
.sz_body {
    width: 100%;
    height: 100%;
    overflow: auto;
}

.test_box {
    margin-bottom: 20px;
}

.testTitle {
    font-size: 16px;
    font-weight: 600;
}

.testContent {}

.testContent_title {
    margin-top: 10px;
}

.testContent_input {
    margin-top: 5px;
}

.test_ping {
    margin-top: 5px;
    display: flex;
    word-break: break-all;
}

.color {
    color: #3681fc;
}
</style>