<template>
    <div class="app-container">
        <div style="margin-top:10px">
            <el-cascader v-model="questioncatC" :options="questioncatData" clearable style="width: 200px"
                :props="{ checkStrictly: true, emitPath: false }" @change="handleFilter"></el-cascader>
            <el-select v-model="listQuery.type" placeholder="题型" clearable style="width: 120px" class="filter-item"
                @change="handleFilter">
                <el-option v-for="item in typeOptions" :key="item.key" :label="item.label" :value="item.value" />
            </el-select>
            <el-input v-model="listQuery.search" placeholder="输入题干进行搜索" style="width: 200px;" class="filter-item"
                @keyup.enter.native="handleSearch" />
            <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button class="filter-item" type="primary" icon="el-icon-refresh-left" @click="resetFilter">刷新重置
            </el-button>
            <div style="margin-top:10px">
                <el-button type="primary" slot="reference" @click="handleAdd()">新增</el-button>
                <el-button @click="handleEnabled">启用</el-button>
                <el-popover placement="top" width="160" v-if="checkPermission(['question_import'])"
                    v-model="popovervisible">
                    <p>导入题目前,请下载模板并按格式录入.</p>
                    <div style="text-align: left; margin: 0;">
                        <el-link href="/media/muban/question.xlsx" target="_blank" @click="popovervisible = false"
                            type="primary">下载模板</el-link>
                        <el-upload :action="upUrl" :on-success="handleUploadSuccess" accept=".xlsx" :headers="upHeaders"
                            :show-file-list="false">
                            <el-button size="small" type="primary" @click="popovervisible = false">上传导入</el-button>
                        </el-upload>
                    </div>

                    <el-button slot="reference">Excel导入</el-button>
                </el-popover>
                <el-button type="primary" icon="el-icon-download" @click="exportQuestion">导出Excel</el-button>
            </div>
        </div>
        <el-table :data="tableData" style="width: 100%;margin-top:10px;" border stripe fit v-loading="listLoading"
            highlight-current-row max-height="600" @sort-change="changeSort" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="题干" sortable="custom" prop="name" width="400px">
                <template slot-scope="scope">{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column label="所属题库">
                <template slot-scope="scope">{{ scope.row.questioncat_name }}</template>
            </el-table-column>
            <el-table-column label="题型">
                <template slot-scope="scope">{{ scope.row.type }}</template>
            </el-table-column>
            <el-table-column label="是否启用">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.enabled" type="success">是</el-tag>
                    <el-tag v-else type="danger">否</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="真题年份">
                <template slot-scope="scope">
                    <span v-if="scope.row.year">{{ scope.row.year }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建日期" sortable='custom' prop="create_time">
                <template slot-scope="scope">
                    <span>{{ scope.row.create_time }}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="small" @click="handleDetail(scope)" icon="el-icon-more"></el-button>
                    <el-button type="primary" size="small" @click="handleEdit(scope)" icon="el-icon-edit"
                        :disabled="!checkPermission(['question_edit'])"></el-button>
                    <el-button type="danger" size="small" @click="handleDelete(scope)" icon="el-icon-delete"
                        :disabled="!checkPermission(['question_delete'])"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit"
            @pagination="getList" />
        <el-dialog title="题目详情" :visible.sync="dialogVisible" width="30%">
            <div>{{ question.type }}</div>
            <div>{{ question.name }}</div>
            <ul id="repeat">
                <li v-for="(value, key) in question.options" v-bind:key="key">
                    {{ key }}:
                    <span>{{ value }}</span>
                </li>
            </ul>
            <div>正确答案{{ question.right }}</div>
            <div>{{ question.resolution }}</div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
  
<script>
//   import {
//     getQuestioncatAll,
//     getQuestionList,
//     deleteQuestion,
//     importQuestion,
//     exportQuestion,
//     enableQuestions
//   } from "@/api/question";
import { genTree, deepClone } from "@/utils";
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination";
import { upUrl, upHeaders } from "@/api/file";
import { getToken } from "@/utils/auth";

const defaultObj = {
    id: "",
    name: ""
};
const listQuery = {
    page: 1,
    limit: 20,
    search: ''
};
export default {
    components: { Pagination },
    data() {
        return {
            popovervisible: false,
            upUrl: upUrl(),
            upHeaders: upHeaders(),
            questioncat: {
                id: "",
                name: ""
            },
            total: 0,
            listQuery: listQuery,
            tableData: [],
            questioncatData: [],
            listLoading: false,
            dialogVisible: false,
            dialogType: "new",
            rule1: {
                name: [{ required: true, message: "请输入名称", trigger: "blur" }]
            },
            typeOptions: [
                { key: 1, label: "单选", value: "单选" },
                { key: 2, label: "多选", value: "多选" },
                { key: 3, label: "判断", value: "判断" }
            ],
            question: {},
            questioncatC: [],
            selects: [],
        };
    },
    computed: {},
    created() {
        //   this.getList();
        //   this.getQuestioncatAll();
    },
    methods: {
        checkPermission,
        handleUploadSuccess(res, file) {
            if (res.code == 200) {
                const loading = this.$loading({ text: "正在导入中..." })
                importQuestion(res.data).then(response => {
                    loading.close()
                    if (response.code == 200) {
                        this.$message({
                            message: '导入成功',
                            type: 'success'
                        });
                        this.getList(listQuery)
                    } else if (response.code == 206) {
                        this.$message({
                            message: '部分未成功' + response.data,
                            type: 'success'
                        });
                    } else {
                        this.$message.error(response.msg);
                    }

                });
            } else {
                this.$message.error("Excel上传失败!");
            }
        },
        getList() {
            this.listLoading = true;
            getQuestionList(this.listQuery).then(response => {
                this.tableData = response.data.results;
                this.total = response.data.count;
                this.listLoading = false;
            });
        },
        getQuestioncatAll() {
            getQuestioncatAll().then(response => {
                this.questioncatData = genTree(response.data);
            });
        },
        handleFilter() {
            if (this.questioncatC.length) {
                this.listQuery.questioncat = this.questioncatC[this.questioncatC.length - 1]
            } else {
                this.listQuery.questioncat = ''
            }
            this.listQuery.page = 1;
            this.getList();
        },
        resetFilter() {
            this.listQuery = listQuery
            this.getList();
        },
        handleSearch() {
            this.listQuery.page = 1
            this.getList();
        },
        handleAdd() {
            this.$router.push({ path: "/exam/questionCreate" })
        },
        handleDetail(scope) {
            this.dialogVisible = true
            this.question = scope.row
        },
        handleEdit(scope) {
            this.$router.push({ path: "/exam/questionUpdate", query: { id: scope.row.id } })
        },
        handleDelete(scope) {
            this.$confirm("确认删除该题目吗?将丢失数据!", "警告", {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                type: "error"
            })
                .then(async () => {
                    await deleteQuestion(scope.row.id);
                    this.getList();
                    this.$message({
                        type: "success",
                        message: "成功删除!"
                    });
                })
                .catch(err => {
                    // console.error(err);
                });
        },
        exportQuestion() {
            const loading = this.$loading({
                text: '正在准备..'
            });
            exportQuestion(this.listQuery).then(response => {
                loading.close()
                window.open(response.data.path, "_blank");
            }).catch(e => { loading.close() });
        },
        changeSort(val) {
            if (val.order == "ascending") {
                this.listQuery.ordering = val.prop;
            } else {
                this.listQuery.ordering = "-" + val.prop;
            }

            this.getList();
        },
        handleSelectionChange(val) {
            let selects = [];
            for (var i = 0; i < val.length; i++) {
                selects.push(val[i].id);
            }
            this.selects = selects;
        },
        handleEnabled() {
            if (this.selects.length) {
                enableQuestions({ ids: this.selects }).then(res => {
                    this.$message.success("成功");
                    this.getList();
                })
            } else {
                this.$message.warning("请先选择题目");
            }
        },
    }
};
</script>
  