<template>
    <div>
        <div class="Bank_m">
            <div style="text-align: right">
                <el-button type="primary" size="small" round @click="getInfo">测评设置</el-button>
            </div>

            <el-dialog title="测评设置" :visible.sync="SetEvaluation" width="30%" :close-on-click-modal="false">
                <div style="margin-bottom: 15px;">
                    <span class="radio">题目选择</span>
                    <el-radio v-model="info.evaluationType" label="1">随机</el-radio>
                    <el-radio v-model="info.evaluationType" label="0">自定义</el-radio>
                </div>

                <!-- 随机 -->
                <el-card shadow="hover" class="card_m" v-show="info.evaluationType==1">
                    <div class="input flex_around">
                        <span>测评题目总数</span>
                        <el-input placeholder="请输入题目数量" type="number" v-model="info.questionNum"></el-input>
                        <span>(总数{{info.totalQuestionNum}}题)</span>
                    </div>
                </el-card>
                <!-- 自定义 -->
                <el-card shadow="hover" class="card_m" v-show="info.evaluationType==0">
                    <div class="input">
                        <div class="check-wrap" :class="{checked: info.isSingleEnable}">
                            <el-checkbox v-model="info.isSingleEnable">单选题</el-checkbox>
                            <el-input placeholder="请输入题目数量" type="number" v-model="info.singleNum" :disabled="!info.isSingleEnable"></el-input>
                            <span>(总数{{info.totalSingleNum}}题)</span>
                        </div>
                        
                        <div class="check-wrap" :class="{checked: info.isMultipleEnable}">
                            <el-checkbox v-model="info.isMultipleEnable">多选题</el-checkbox>
                            <el-input placeholder="请输入题目数量" type="number" v-model="info.multipleNum" :disabled="!info.isMultipleEnable"></el-input>
                            <span>(总数{{info.totalMultipleNum}}题)</span>
                        </div>
                        
                        <div class="check-wrap" :class="{checked: info.isJudgmentEnable}">
                            <el-checkbox v-model="info.isJudgmentEnable">判断题</el-checkbox>
                            <el-input placeholder="请输入题目数量" type="number" v-model="info.judgmentNum" :disabled="!info.isJudgmentEnable"></el-input>
                            <span>(总数{{info.totalJudgmentNum}}题)</span>
                        </div>
                    </div>
                </el-card>

                <div class="jobNumber">
                    <div class="input">
                        <span style="margin:0px 15px 0px 35px">测评时长</span>
                        <el-input placeholder="请输入时间" type="number" v-model="info.duration"></el-input>
                        <span style="margin-left:15px">分钟</span>
                    </div>
                </div>
                <span slot="footer" class="dialog-footer">
                    <el-button @click="SetEvaluation = false">取 消</el-button>
                    <el-button type="primary" v-preventReClick @click="submitSetEva">确 定</el-button>
                </span>
            </el-dialog>
        </div>

        <el-row :gutter="20">
            <el-col :span="24">
                <el-card shadow="hover" class="mgb20">
                    <div class="flex-center mgb20">
                        <p class="hr_tag"></p>
                        <span>测评题库</span>
                    </div>
                    <div class="flex-between">
                        <div>
                            <span style="margin-right: 15px;">题目类型</span>
                            <el-radio-group v-model="subject" @change="getData">
                                <el-radio
                                    v-for="(item,index) in subjectList"
                                    :key="index"
                                    :label="item.id"
                                >{{item.name}}</el-radio>
                            </el-radio-group>
                        </div>
                        <div>
                            <el-input
                                placeholder="请输入题干"
                                prefix-icon="el-icon-search"
                                v-model="keyword"
                                clearable
                            ></el-input>
                        </div>
                    </div>
                </el-card>
            </el-col>

            <div>
                <el-dialog :title="topicsTitle" :visible.sync="NewTopics" width="30%" @close="closeTopics" :close-on-click-modal="false">
                    <el-form
                        :model="topicForm"
                        :rules="rules"
                        :disabled="isShowTopics"
                        ref="topicForm"
                        label-width="100px"
                        class="demo-topicForm"
                    >
                        <el-form-item label="题型" prop="questionType">
                            <el-radio-group v-model="topicForm.questionType" @change="questionTypeChange">
                                <el-radio label="单选题"></el-radio>
                                <el-radio label="多选题"></el-radio>
                                <el-radio label="判断题"></el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="题干" prop="questionStem">
                            <el-input type="textarea" v-model="topicForm.questionStem"></el-input>
                        </el-form-item>

                        <el-form-item label="选项" prop="optionA">
                            <div class="input flex_around bt">
                                <span>A</span>
                                <el-input placeholder="请输入题目" v-model="topicForm.optionA"></el-input>
                                <el-checkbox v-model="topicForm.aisTrue">设为正确答案</el-checkbox>
                            </div>
                            <div class="input flex_around bt">
                                <span>B</span>
                                <el-input placeholder="请输入题目" v-model="topicForm.optionB"></el-input>
                                <el-checkbox v-model="topicForm.bisTrue">设为正确答案</el-checkbox>
                            </div>
                            <template v-if="topicForm.questionType != '判断题'">
                                <div class="input flex_around bt">
                                    <span>C</span>
                                    <el-input placeholder="请输入题目" v-model="topicForm.optionC"></el-input>
                                    <el-checkbox v-model="topicForm.cisTrue">设为正确答案</el-checkbox>
                                </div>
                                <div class="input flex_around bt">
                                    <span>D</span>
                                    <el-input placeholder="请输入题目" v-model="topicForm.optionD"></el-input>
                                    <el-checkbox v-model="topicForm.disTrue">设为正确答案</el-checkbox>
                                </div>
                                <div class="input flex_around bt">
                                    <span>E</span>
                                    <el-input placeholder="请输入题目" v-model="topicForm.optionE"></el-input>
                                    <el-checkbox v-model="topicForm.eisTrue">设为正确答案</el-checkbox>
                                </div>
                                <div class="input flex_around">
                                    <span>F</span>
                                    <el-input placeholder="请输入题目" v-model="topicForm.optionF"></el-input>
                                    <el-checkbox v-model="topicForm.fisTrue">设为正确答案</el-checkbox>
                                </div>
                            </template>
                        </el-form-item>
                        <el-form-item label="答案解析" prop="answerAnalysis">
                            <el-input type="textarea" v-model="topicForm.answerAnalysis"></el-input>
                        </el-form-item>
                    </el-form>
                    <div slot="footer" class="dialog-footer" v-show="!isShowTopics">
                        <el-button type="primary" @click="saveTopics">确 定</el-button>
                        <el-button v-preventReClick @click="NewTopics = false">取 消</el-button>
                    </div>
                </el-dialog>

                <el-dialog title="批量上传" :visible.sync="BatchUpload" width="30%" @close="closeUpload" :close-on-click-modal="false">
                    <el-card shadow="hover" class="card_m" v-show="this.label=1">
                        <div class="Upload">
                            <div class="bt" @click="downloadTem">
                                <el-link :underline="false">
                                    1.请下载模板
                                    <i class="el-icon-download"></i>
                                </el-link>
                            </div>
                            <!-- <div class="bt">
                                <el-upload
                                    accept=".xls,.xlsx"
                                    :on-remove="handleRemove"
                                    :on-error="uploadError"
                                    :on-success="uploadSuccess"
                                    :before-remove="beforeRemove"
                                    :limit="1"
                                    :on-exceed="handleExceed"
                                    :action="this.api.upload"
                                    :file-list="uploadList"
                                    name="file"
                                > 
                                    <el-link :underline="false">
                                        2.请点击上传模板
                                        <i class="el-icon-upload"></i>
                                    </el-link>
                                </el-upload>
                            </div> -->
                            <div>
                                <el-upload
                                    accept=".xls,.xlsx"
                                    :on-remove="handleDataRemove"
                                    :on-error="uploadError"
                                    :on-success="uploadSuccess"
                                    :before-remove="beforeRemove"
                                    :limit="1"
                                    :on-exceed="handleExceed"
                                    :action="this.api.import"
                                    :file-list="uploadDataList"
                                    name="file"
                                > 
                                    <el-link :underline="false">
                                        2.请点击批量导入
                                        <i class="el-icon-upload"></i>
                                    </el-link>
                                </el-upload>
                                <el-link v-if="uploadFaild" type="primary" @click="showFaild">部分数据导入失败，查看失败原因</el-link>
                            </div>
                        </div>
                    </el-card>
                    <span slot="footer" class="dialog-footer">
                        <el-button @click="BatchUpload = false">取 消</el-button>
                        <el-button type="primary" v-preventReClick @click="uploadSure">确 定</el-button>
                    </span>
                </el-dialog>
            </div>

            <el-col :span="24">
                <el-card shadow="hover" class="mgb20">
                    <div class="flex-between mgb20">
                        <div class="flex-center">
                            <p class="hr_tag"></p>
                            <span>题目列表</span>
                        </div>
                        <div>
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-plus"
                                round
                                class="bt_one"
                                @click="addTopics"
                            >新增题目</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-top"
                                round
                                class="bt_one"
                                @click="showBatchUpload"
                            >批量上传</el-button>
                            <el-button
                                type="primary"
                                size="small"
                                icon="el-icon-delete"
                                round
                                class="bt_one"
                                @click="delAllData"
                            >批量删除</el-button>
                        </div>
                    </div>

                    <el-table
                        :data="orderData"
                        ref="table"
                        row-key="id"
                        class="table"
                        stripe
                        header-align="center"
                        @selection-change="handleSelectionChange"
                    >
                        <el-table-column
                            type="selection"
                            width="55"
                            align="center"
                            :reserve-selection="true"
                        ></el-table-column>
                        <el-table-column type="index" width="100" label="序号" align="center">
                            <template
                                slot-scope="scope"
                            >{{scope.$index + (pageNo - 1) * pageSize + 1}}</template>
                        </el-table-column>
                        <el-table-column prop="questionStem" label="题干" align="center"></el-table-column>
                        <el-table-column prop="questionTypeName" label="题型" align="center"></el-table-column>
                        <el-table-column prop="modifyTime" label="时间" align="center"></el-table-column>
                        <el-table-column label="操作" align="center">
                            <template slot-scope="scope">
                                <template v-if="scope.row.isEnable">
                                    <el-button type="text" @click="showQues(scope.row)">查看</el-button>
                                </template>
                                <template v-else>
                                    <el-button type="text" @click="editQues(scope.row)">修改</el-button>
                                </template>
                                <el-switch
                                    v-model="scope.row.isEnable"
                                    :active-text="scope.row.isEnable ? '关闭' : '启用'"
                                    :active-value="1"
                                    :inactive-value="0"
                                    style="margin: 0 10px 0 5px"
                                    @change="switchQues($event,scope.row,scope.$index)"
                                ></el-switch>
                                <el-button type="text" @click="delData(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <div class="pagination">
                        <el-pagination
                            background
                            @current-change="handleCurrentChange"
                            :current-page="pageNo"
                            :page-size="pageSize"
                            layout="total,prev, pager, next"
                            :total="dataTotal"
                        ></el-pagination>
                    </div>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import bus from '../common/bus';
export default {
    data() {
        return {
            topicForm: {
                answer: '',
                questionType : '单选题',
                questionStem : '',
                optionA:'',
                optionB:'',
                optionC:'',
                optionD:'',
                optionE:'',
                optionF:'',
                aisTrue: false,
                bisTrue: false,
                cisTrue: false,
                disTrue: false,
                eisTrue: false,
                fisTrue: false,
                answerAnalysis: ''
            },
            rules: {
                questionType: [{ required: true, message: '请选择题型', trigger: 'change' }],
                questionStem: [{ required: true, message: '请填写题干', trigger: 'blur' }],
                // optionA: [{ required: true, message: '请选择正确选项', trigger: 'change' }],
                // optionB: [{ required: true, message: '请选择正确选项', trigger: 'change' }]
            },
            value: true,
            subject: '', //题目类型
            keyword: '',
            orderData: [],
            subjectList: [
                {
                    id: '',
                    name: '不限'
                },
                {
                    id: 1,
                    name: '单选题'
                },
                {
                    id: 2,
                    name: '多选题'
                },
                {
                    id: 3,
                    name: '判断题'
                }
            ],
            dataTotal: 0, // 总条数，根据接口获取数据长度(注意：这里不能为空)
            pageNo: 1,
            pageSize: 10,
            currentPage: 1,
            SetEvaluation: false,
            radio: '1', //题目选择
            topicsNumber: '', //题目数量
            topicsTime: '', //测评时长
            random: true,
            custom: false,
            info: {},
            NewTopics: false, //新增题目
            Customs: ['1', '2', '3'],
            BatchUpload: false, //批量上传
            questionType: ['','单选题','多选题','判断题'],
            multipleSelection: [],
            isShowTopics: false,
            topicsTitle: '',
            uploadList: [],
            uploadDataList: [],
            searchTimer: null,
            uploadFaild: false,
            token: ''
        };
    },
    mounted() {
        this.getData()
    },
    watch: {
        keyword: function(val) {
            clearTimeout(this.searchTimer)
            this.searchTimer = setTimeout(() => {
                this.getData()
            },500)
        }
    },
    methods: {
        getData() {
            this.$get(this.api.list, {
                page: this.pageNo,
                size: this.pageSize,
                questionStem: this.encodeString(this.keyword),
                questionType: this.subject
            })
            .then(res => {
                this.dataTotal = res.page.totalCount; //总条数
                this.pageNo = res.page.currPage; //当前页数
                this.orderData = res.page.list;
                this.$refs.table.clearSelection()
            })
            .catch(err => {})
        },
        resetForm() {
            this.topicForm = {
                answer: '',
                questionType : '',
                questionStem : '',
                optionA:'',
                optionB:'',
                optionC:'',
                optionD:'',
                optionE:'',
                optionF:'',
                aisTrue: false,
                bisTrue: false,
                cisTrue: false,
                disTrue: false,
                eisTrue: false,
                fisTrue: false,
                answerAnalysis: ''
            }
            this.$nextTick(() => {
                this.$refs.topicForm.clearValidate()
            })
        },
        handleCurrentChange(val) {
            this.pageNo = val
            this.getData()
        },
        addTopics() {
            this.topicForm.id = ''
            this.topicsTitle = '新增题目'
            this.NewTopics = true
        },
        getDetail(id) {
            this.$get(this.api.infoId + id).then(res => {
                this.topicForm = res.questions
                this.topicForm.id = id
                this.topicForm.questionType = this.questionType[this.topicForm.questionType]
                this.NewTopics = true
            }).catch(res => {});
        },
        editQues(row) {
            this.topicsTitle = '编辑题目'
            this.getDetail(row.id)
        },
        showQues(row) {
            this.topicsTitle = '查看题目'
            this.isShowTopics = true
            this.getDetail(row.id)
        },
        closeTopics() {
            this.isShowTopics = false
            this.resetForm()
        },
        switchQues(val,row,index) {
            this.$put(this.api.isenable, [row.id])
            .then(res => {
                if(res.status == 400){
                    this.$message.error(res.errmessage)
                    row.isEnable = row.isEnable == 1 ? 0 : 1
                }
            })
            .catch(err => {});
        },
        delData(row) {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
            .then(() => {
                this.$post(this.api.delete,[row.id]).then(res => {
                    this.$message.success('删除成功');
                    this.getData()
                }).catch(res => {});
            })
            .catch(() => {});
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        delAllData() {
            if(this.multipleSelection.length != ''){
                let newArr = this.multipleSelection
                let delList = newArr.map(item => {
                    return item.id
                })

                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                .then(() => {
                    let data = delList
                    this.$post(this.api.delete,data).then(res => {
                        this.$refs.table.clearSelection()
                        this.$message.success('删除成功');
                        this.getData()
                    }).catch(res => {});
                })
                .catch(() => {});
            }else{
                this.$message.error('请先选择题目 ！');
            }
        },
        downloadTem() {
            location.href = 'http://www.liuwanr.cn/template/试题导入模板.xlsx'
        },
        getInfo() {
            this.$get(this.api.info).then(res => {
                this.info = res.data
                this.info.evaluationType = this.info.evaluationType.toString()
                this.info.isSingleEnable = Boolean(this.info.isSingleEnable)
                this.info.isMultipleEnable = Boolean(this.info.isMultipleEnable)
                this.info.isJudgmentEnable = Boolean(this.info.isJudgmentEnable)
                this.SetEvaluation = true
            }).catch(res => {});
        },
        questionTypeChange() {
            for(let i in this.topicForm){
                if(i.includes('isTrue')) this.topicForm[i] = false
            }
        },
        submitSetEva() {
            let info = this.info
            if(info.evaluationType == 0){
                let allEmpty = true
                if(!info.isSingleEnable && !info.isMultipleEnable && !info.isJudgmentEnable) return this.$message.warning('请至少选择一种题型')
                if(info.isSingleEnable == 1 && info.singleNum != 0) allEmpty = false
                if(info.isMultipleEnable == 1 && info.multipleNum != 0) allEmpty = false
                if(info.isJudgmentEnable == 1 && info.judgmentNum != 0) allEmpty = false
                if(allEmpty) return this.$message.warning('请至少选中一种类型，并数量大于0')
                if(info.isSingleEnable == 1 && info.singleNum > info.totalSingleNum) return this.$message.warning('单选题大于总数，请重新输入')
                if(info.isMultipleEnable == 1 && info.multipleNum > info.totalMultipleNum) return this.$message.warning('多选题大于总数，请重新输入')
                if(info.isJudgmentEnable == 1 && info.judgmentNum > info.totalJudgmentNum) return this.$message.warning('判断题大于总数，请重新输入')
            }else{
                if(info.questionNum === '') return this.$message.warning('请输入测评题目总数')
                if(info.questionNum == 0) return this.$message.warning('测评题目总数不得为0')
            }

            if(info.duration === '') return this.$message.warning('请输入测评时长')
            if(info.duration == 0) return this.$message.warning('测评时长不得为0')
            this.info.isSingleEnable = Number(this.info.isSingleEnable)
            this.info.isMultipleEnable = Number(this.info.isMultipleEnable)
            this.info.isJudgmentEnable = Number(this.info.isJudgmentEnable)
            this.$put(this.api.update,this.info).then(res => {
                if(res.errmessage == 'success'){
                    this.$message.success('提交成功！');
                    this.SetEvaluation = false
                }else{
                    this.$message.error(res.message);
                }
            }).catch(res => {});
        },
        saveTopics() {
            this.$refs.topicForm.validate((valid) => {
                if (valid) { 
                    let topicForm = this.topicForm
                    let optionCount = 0
                    let answer = ''
                    let isInvalidAnswer = false
                    for(let n in topicForm) {
                        if(n.includes('option')) {
                            topicForm[n] != '' && ++optionCount
                        }
                        if(n.includes('isTrue') && topicForm[n]) {
                            let curOpt = n.replace('isTrue','')
                            answer += curOpt
                            if(!topicForm[`option${curOpt.toUpperCase()}`].length) isInvalidAnswer = true
                        }
                    }
                    if(optionCount < 2) return this.$message.warning('请至少添加两个选项！');
                    if(!answer) return this.$message.warning('请设置正确答案！');
                    if(topicForm.questionType != '多选题' && answer.length > 1) return this.$message.warning('单选题、判断题只能设置一个正确答案！');
                    if(isInvalidAnswer) return this.$message.warning('正确答案选项为空，请重新设置！');
                    this.topicForm.questionType = this.questionType.indexOf(this.topicForm.questionType)
                    this.topicForm.answer = answer.toUpperCase()

                    if(this.topicForm.id) {
                        this.$put(this.api.questionsUpdate,this.topicForm).then(res => {
                            if(res.errmessage == 'success') {
                                this.$message.success('提交成功！');
                                this.NewTopics = false
                                this.getData()
                            }else{
                                this.$message.error(res.message);
                            }
                        }).catch(res => {});
                    }else{
                        this.$post(this.api.save,this.topicForm).then(res => {
                            if(res.errmessage == 'success') {
                                this.$message.success('提交成功！');
                                this.NewTopics = false
                                this.getData()
                            }else{
                                this.$message.error(res.message);
                            }
                        }).catch(res => {});
                    }
                }else{
                    return false;
                }
            })
        },
        showBatchUpload() {
            this.BatchUpload = true
        },
        handleExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，如需更换，请删除上一个文件再重新选择！` 
            );
        },
        uploadSuccess(res, file, fileList) {
            this.uploadFaild = false
            if(res.data.token){
                this.token = res.data.token
                this.uploadFaild = true
            }
        },
        showFaild(){
            location.href = `${this.api.export_failure}?token=${this.token}`
        },
        uploadError(err, file, fileList) {
            this.$message({
                message: "上传出错，请重试！",
                type: "error",
                center: true
            });
        },
        beforeRemove(file, fileList) {
            return this.$confirm(`确定移除 ${file.name}？`);
        },
        handleRemove(file, fileList) {
            this.uploadList = fileList
        },
        handleDataRemove(file, fileList) {
            this.uploadList = fileList
        },
        uploadSure(){
            this.BatchUpload = false
            this.pageNo = 1
            this.keyword = ''
            this.getData()
        },
        closeUpload() {
            this.uploadList = []
            this.uploadDataList = []
        }
    }
};
</script>

<style lang="scss" scoped>
::v-deep .el-checkbox-group{
    font-size: 2px;
}
.Upload {
    text-align: center;
}
.bt {
    margin-bottom: 15px;
}
.bt_one {
    margin-left: 10px;
}
.Bank_m {
    margin-bottom: 20px;
}
.Bank img {
    width: 15px;
    height: 15px;
    margin-right: 10px;
}
.Bank span {
    font-size: 16px;
}
.jobNumber {
    margin: 10px 0;
}
.flex_around {
    display: flex;
    justify-content: space-around;
    align-items: center;
}
.card_m {
    margin: 10px 0 20px 0;
}
.input ::v-deep .el-input {
    width: 50%;
}
.radio {
    margin: 0 15px 0 30px;
    font-weight: 600;
}
.mag {
    margin-right: 20px;
}
.check-wrap{
    display: flex;
    align-items: center;
    margin-bottom: 15px;
}
.check-wrap .el-input{
    margin: 0 15px;
}
.check-wrap.checked{
    color: #9076FF;
}
</style>

