<template>
    <div class="educationQuestions">
        <div class="header_search">
            <el-input v-model="searchTitle" style="width: 156px;margin-right: 15px" size="medium" placeholder="请输入标题"></el-input>
            <el-button type="primary" size="small" @click="loadData">查询</el-button>
            <el-button v-if="pageType=='company'" type="primary" icon="el-icon-plus" size="small" @click="showAdd" >新增</el-button>
        </div>
        <div class="educationQuestions_table">
            <vue-scroll style="height: 100%">
            <el-table class="tables"
                :data="tableData"
                ref="refTable"
                style="width: 100%"
                height="100%"
                @cell-click="expandChange">
                <el-table-column type="expand" width="0">
                    <template slot-scope="props">
                        <div class="answers">
                            <el-checkbox class="answers_item" :value="data.correctType == 1" v-for="(data,index2) in props.row.optionlist" :key="index2">{{indexList[index2]}}、{{data.optionName}}</el-checkbox>
                        </div>
                        <div class="answers_analysis">
                            <span>试题解析：</span>
                            <p>{{props.row.questionAnalysis}}</p>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                label="试题名称"
                prop="questionName">
                </el-table-column>
                <el-table-column
                label="试题类型"
                width="120px"
                prop="type">
                    <template slot-scope="scope">
                        {{scope.row.questionType == 1 ? "单选":"多选"}}
                    </template>
                </el-table-column>
                <el-table-column
                label="答题次数"
                width="120px"
                prop="answerNum">
                    <template slot-scope="scope">
                        {{scope.row.count.answerNum}}
                    </template>
                </el-table-column>
                <el-table-column
                label="答错次数"
                width="120px"
                prop="errorNum">
                <template slot-scope="scope">
                        {{scope.row.count.errorNum}}
                    </template>
                </el-table-column>
         
                <el-table-column
                label="错误率"
                width="120px"
                prop="errorRate">
                    <template slot-scope="scope">
                        {{scope.row.count.errorRatio}}%
                    </template>
                </el-table-column>
                <el-table-column width="200px" label="操作" align="center" v-if="pageType=='company'">
                    <template slot-scope="scope">
                        <div class="list_actions">
                            <el-button
                                class="edit_btn"
                                size="mini"
                                type="text"
                                icon="el-icon-edit-outline"
                            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                            <el-button
                                class="delete_btn"
                                size="mini"
                                type="text"
                                icon="el-icon-delete"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            </vue-scroll>
        </div>
        <div class="list-pagination">
            <div class="pagination-sizes">
                <span>每页显示</span>
                    <el-select size="mini" v-model="pageSize" @change="changePageSize" placeholder="请选择">
                        <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item"
                        :value="item">
                        </el-option>
                    </el-select>
                <span>项</span>
            </div>
            <div class="pagination-total">
                共{{total}}项
            </div>
            <div class="pagination-box">
                <span class="title">首页</span>
                <el-button size="mini" @click="chageCurrentPage('pre')">上页</el-button>
                <el-pagination
                    :current-page="currentPage"
                    layout="pager"
                    @size-change="changePageSize"
                    @current-change="changCurrent"
                    :page-sizes="options"
                    :page-size="pageSize"
                    :total="total">
                </el-pagination>
                <el-button size="mini" @click="chageCurrentPage('next')">下页</el-button>
                <el-button size="mini" @click="chageCurrentPage('end')">尾页</el-button>
            </div>
            
        </div>

        <formDialog :title="dialogTitle" v-if="showDialog" @closeDialog="close">
            <div slot="content" class="dialog-content">
                <vue-scroll style="height: 580px; margin-bottom: 40px">
                    <el-form class="add_form" ref="add_form" :rules="rules" size="medium" label-width="120px" label-position="right" :model="addFormData">
                        <el-form-item label="试题类型" prop="questionType">
                            <!-- <el-input style="width: 292px" v-model="addFormData.type" disabled></el-input> -->
                            <el-select v-model="addFormData.questionType" style="width: 100%;" placeholder="请选择">
                                <el-option
                                v-for="item in selectOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="试题名称" prop="questionName">
                            <el-input type="textarea" resize="none" :rows="3" v-model="addFormData.questionName" placeholder="请输入试题名称"></el-input>
                        </el-form-item>
                        <el-form-item :label="'试题选项及答案:'"> </el-form-item>
                        <el-form-item
                            :label="'A、'"
                            prop="lsit"
                            v-for="(item, index) in addFormData.optionList"
                            :key="index"
                        >
                            <template slot="label">
                            <p>
                                <el-checkbox :value="item.correctType" v-model="item.correctType"
                                >{{ indexList[index] }}、</el-checkbox
                                >
                            </p>
                            </template>
                            <el-input
                            v-model="item.optionName"
                            placeholder="请输入"
                            ></el-input>
                            <i class="el-icon-remove" @click="removeOptions(index)"></i>
                        </el-form-item>
                        <el-form-item :label="''">
                            <el-button type="primary" plain size="medium" @click="addOptions">新增选项</el-button>
                        </el-form-item>
                        <el-form-item label="试题解析" prop="questionAnalysis">
                            <el-input type="textarea" resize="none" :rows="3" v-model="addFormData.questionAnalysis" placeholder="请输入试题解析"></el-input>
                        </el-form-item>
                    </el-form>
                </vue-scroll>
                <div class="btn_box">
                    <el-button class="cancel_btn" size="small" icon="el-icon-circle-close" @click="close">取消</el-button>
                    <el-button size="small" icon="el-icon-circle-check" type="primary" @click="submitData">确认</el-button>
                </div>
            </div>
        </formDialog>
    </div>
</template>

<script>
import formDialog from './../workstation/compontents/formDialog.vue'
import {wirelessQuestionAddApi,wirelessQuestionDeleteApi,
wirelessQuestionEditApi,wirelessQuestionListApi} from "@/assets/js/api/wirelessEducation"
export default {
    props:['libraryId'],
    components:{
        formDialog
    },
    data(){
        return{
            searchTitle: "",
            tableData: [],
            indexList: [
                "A",
                "B",
                "C",
                "D",
                "E",
                "F",
                "G",
                "H",
                "I",
                "J",
                "K",
                "L",
                "N",
                "M",
                "O",
                "P",
                "Q",
                "R",
                "S",
                "T",
                "U",
                "V",
                "W",
                "X",
                "Y",
                "Z",
            ],
            currentPage: 1,
            options: [10,20,30],
            pageSize: 10,
            total: 0,
            showDialog: false,
            dialogTitle: "新增试题",
            selectOptions:[{
                value: 1,
                label: "单选"
            },{
                value: 2,
                label: "多选"
            }],
            addFormData:{
                questionType: 1,
                questionName: "",
                questionAnalysis: "",
                questionScore:"",
                optionList: [
                    {
                        optionName: "",
                        correctType:false,
                    },
                    {
                        optionName: "",
                        correctType:false,
                    },
                    {
                        optionName: "",
                        correctType:false,
                    },
                    {
                        optionName: "",
                        correctType:false,
                    }
                ]
            },
            rules: {
                questionType: [
                { required: true, message: "请选择试题类型", trigger: "change" },
                ],
                questionName: [
                { required: true, message: "请输入试题名称", trigger: "blur" }
                ],
                
            },
            searchSn:'',
            isAdd:true,
            pageType:'project'
        }
    },
    mounted(){
        if(this.$route.path.indexOf('/project/')==-1){
            this.searchSn=this.$store.state.userInfo.headquartersSn
            this.pageType='company'
        }else{
            this.searchSn=this.$store.state.projectSn
            this.pageType='project'
        }
        
        this.loadData()
    },
    methods:{
        //获取试题列表
        loadData(){
            let json = {
                sn:this.searchSn,libraryId:this.libraryId,
                pageNo:this.currentPage,pageSize:this.pageSize,
                questionName:this.searchTitle,
                type:2
            }
            wirelessQuestionListApi(json).then((res) => {
                this.tableData=res.result.records
                this.total=res.result.total
            });
        },
        //保存试题信息
        submitData(){
            
            this.$refs["add_form"].validate((valid) => {
                if (valid) {
                var data = JSON.parse(JSON.stringify(this.addFormData))
            var optionList=data.optionList
            if(optionList.length<2){
                this.$message.error('请添加至少两个选项')
                return;
            }
            var correctNum = 0
            optionList.forEach((element,index) => {
                if(element.optionName==''){
                this.$message.error('请输入选项内容')
                return;
                }
                if(element.correctType===true||element.correctType===1){
                data.optionList[index].correctType=1
                correctNum++
                }else{
                data.optionList[index].correctType=2
                }
            });
            console.log(data)
            if(data.questionType==1&&correctNum==0){
                this.$message.error('请选中正确选项')
                return;
            }
            if(data.questionType==1&&correctNum>1){
                this.$message.error('正确选项只能是1个')
                return;
            }
            if(data.questionType==2&&correctNum<2){
                this.$message.error('正确选项必须大于1个')
                return;
            }
                if (this.isAdd) {
                    data.type=2
                data.libraryId=this.libraryId
                data.sn=this.searchSn
                    wirelessQuestionAddApi(data).then((res) => {
                        this.showDialog = false;
                        this.loadData();
                        this.$message.success(
                            this.$t("message.personnelPosition.add_success")
                        ); //编辑成功！
                    });
                } else {
                    // json.id=this.itemId
                    wirelessQuestionEditApi(data).then((res) => {
                        this.showDialog = false;
                        this.loadData();
                        this.$message.success(
                            this.$t("message.personnelPosition.edit_success")
                        ); //编辑成功！
                    });
                }
                } else {
                console.log("error submit!!");
                return false;
                }
            });
        },
        expandChange(row,column,event,cell){
            console.log(row,column,cell)
            if(column.label !== "操作"){
                this.$refs.refTable.toggleRowExpansion(row)
            }
            
        },
        handleEdit(index, row) {
            console.log(index, row);
            this.showDialog = true
            this.dialogTitle = "编辑试题"
            this.isAdd=false
            this.$nextTick(()=>{
                this.addFormData=JSON.parse(JSON.stringify(row))
                
                var optionList=this.addFormData.optionlist
                this.addFormData.optionList=optionList
                // this.questionIndex=index
                optionList.forEach((element,index2) => {
                if(element.correctType==1){
                    this.addFormData.optionList[index2].correctType=true
                }else{
                    this.addFormData.optionList[index2].correctType=false
                }
                });
            })
        },
        handleDelete(index, row) {
            // console.log(index, row);
             this.$confirm('确定删除“'+row.questionName+'”吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.deleteFn(row.questionId)
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });          
            });
        },
        deleteFn(id){
            wirelessQuestionDeleteApi({id:id}).then((res) => {
                this.loadData()
                this.$message.success('删除成功！');
            });
        },
        changCurrent(val){
            this.currentPage = val
        },
        changePageSize(val){
            this.pageSize = val
            if(this.currentPage > Math.ceil(this.total/this.pageSize)){
                this.currentPage = Math.ceil(this.total/this.pageSize)
            }
        },
         chageCurrentPage(val){
            if (val == 'pre'){
                if(this.currentPage == 1){
                    return
                } else {
                    --this.currentPage;
                }
            } else if(val == 'next'){
                if(this.currentPage < Math.ceil(this.total/this.pageSize)){
                    ++this.currentPage;
                    // console.log(this.currentPage)
                } else{
                    return;
                }
            } else if(val == 'end'){
                this.currentPage = Math.ceil(this.total/this.pageSize)
            }
        },
        resetForm(){
            this.addFormData = {
                questionType: 1,
                questionName: "",
                questionAnalysis: "",
                questionScore:"",
                optionList: [
                    {
                        optionName: "",
                        correctType:false,
                    },
                    {
                        optionName: "",
                        correctType:false,
                    },
                    {
                        optionName: "",
                        correctType:false,
                    },
                    {
                        optionName: "",
                        correctType:false,
                    }
                ]
            }
        },
        close(){
            this.showDialog = false
            this.resetForm();
        },
        showAdd(){
            this.showDialog = true
            this.isAdd=true
            this.dialogTitle = "新增试题"
        },
        removeOptions(index){
            if(this.addFormData.optionList.length < 3){
                this.$message.error("至少保留两个选项")
            } else {
                this.addFormData.optionList.splice(index, 1)
            }
        },
        addOptions(){
            this.addFormData.optionList.push({
                optionName: "",
                correctType:false,
            })
        }
    }
}
</script>

<style lang="less" scoped>
    .educationQuestions{
        height: 100%;
        width: 100%;
        .header_search{
            padding: 19px 15px 26px 15px;
        }
        .demo-table-expand{
            padding: 10px;
        }
        /deep/.el-table__expand-icon{
            display: none;
        }
        /deep/.el-table__row{
            cursor: pointer;
        }
        .educationQuestions_table{
            height: 75%;
            // height: 560px;
            .answers{
                display: flex;
                flex-wrap: wrap;
                justify-content: flex-start;
                margin: 10px 15px 0;
                .answers_item{
                    width: 25%;
                    margin: 0;
                    margin-bottom: 16px;
                }
            }
            .answers_analysis{
                width: 75%;
                margin: 0px 15px 10px;
                span{
                    display: block;
                    margin-bottom: 8px;
                }
                p{
                    color: #9198A8;
                    line-height: 20px;
                    text-indent: 2em;
                }
            }
            .list_actions{
                .edit_btn{
                    color: #919BB1;
                    margin-right: 20px;
                    /deep/.el-icon-edit-outline{
                        color: #66B1C4;
                        margin-right: 4px;
                    }
                }
                .delete_btn{
                    color: #A35060;
                    /deep/.el-icon-delete{
                        margin-right: 4px;
                    }
                }
            }
        }
        .list-pagination{
            width: 90%;
            margin: 0 auto;
            display: flex;
            align-items: center;
            font-size: 14px;
            justify-content: flex-end;
            color: #B4B8BF;
            padding: 40px 0;
            .pagination-sizes{
                margin-right: 16px;
                /deep/ .el-input--mini .el-input__inner{
                    height: 18px;
                    width: 40px;
                    line-height: 18px;
                    padding: 0 0 0 4px;
                    font-size: 12px;
                    background: none;
                    color: #fff;
                    border-radius: 0;
                    border: 1px solid #142E59;
                }
                /deep/ .el-input--mini .el-input__icon{
                    line-height: 18px;
                    font-size: 12px;
                }
                /deep/ .el-input__suffix{
                    right: 0;
                }
                span{
                    margin: 0 6px;
                    line-height: 18px;
                }
            }
            .pagination-total{
                margin-right: 22px;
                line-height: 18px;
            }
            .pagination-box{
                display: flex;
                align-items: center;
                .title{
                    margin-right: 6px;
                }
                /deep/.el-pagination{
                    margin: 0;
                    padding: 0;
                    color: #fff;
                }
                /deep/ .el-pager li{
                    padding: 0;
                    background: none;
                    height: 20px;
                    line-height: 20px;
                    border-radius: 0;
                    border: 1px solid #142E59;
                }
                /deep/ .el-pager li.active {
                    color: #fff;
                    cursor: default;
                    background: #142E59;
                    border: 0;
                }
                /deep/.el-pager li:hover{
                    color: #fff;
                }
                /deep/ .el-pager .more::before{
                    line-height: 20px;
                    color: #fff;
                }
                /deep/ .el-button--mini{
                    margin: 0;
                    height: 20px;
                    padding: 0 6px;
                    border: 1px solid #142E59;
                    background: none;
                    color: #B4B8BF;
                    font-size: 12px;
                    border-radius: 0;
                }

            }
        }
        .dialog-content{
            width: 678px;
            padding-top: 44px;
            padding-bottom: 46px;
            .add_form{
                width: 440px;
                margin: 0 auto;
                /deep/ .is-disabled .el-input__inner{
                    background: #152443;
                    color: #7B8497;
                }
                /deep/.el-icon-remove{
                    font-size: 20px;
                    color: #ff3d3d;
                    position: absolute;
                    right: -30px;
                    top: 7px;
                    cursor: pointer;
                }
            }
            .btn_box{
                display: flex;
                margin: 0 auto;
                justify-content: center;
                .cancel_btn{
                    margin-right: 80px;
                    color: #fff;
                    background: transparent;
                }
            }
        }
    }
</style>