<template>
  <div style="text-align: center;padding: 10px;">
    <div style="margin-top: 10px;margin-bottom: 10px;display: flex;justify-content: space-between;">
      <div style="display: inline-block;font-size: 14px;">
        <span>单位</span>
        <el-select v-model="companyId" placeholder="请选择单位" clearable size="mini" style="margin-left: 10px;">
          <el-option v-for="it in companyList" :key="it.id" :label="it.name" :value="it.id" />
        </el-select>
      </div>
      <div style="display: inline-block;">
        <el-button
          v-loading="loading"
          size="mini"
          type="primary"
          @click="doSave"
        >保存</el-button>
        <el-button
          size="mini"
          type="danger"
          @click="doCancel"
        >取消</el-button>
      </div>
    </div>
    <el-table
      :data="tableData"
      border
      style="width: 100%"
    >
      <el-table-column
        prop="topic"
        label="题目"
      />
      <el-table-column prop="type" label="类型" width="100">
        <template slot-scope="scope">
          <el-tag
            type="primary"
            disable-transitions
          >{{ $ConstSelect.translate(scope.row.type, 'QuestionTypeList') }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="answer"
        label="答案"
      >
        <template slot-scope="scope">
          <el-tag v-for="(answer, index) in answerTags(scope.row)" :key="index" type="primary" style="margin-right: 10px;">{{ answer }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            @click="edit(scope.$index, scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="doDelete(scope.$index, scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :current-page.sync="currentPage"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :page-sizes="[10, 20, 30, 50]"
      :total="totalNum"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { UrlConfig } from '@/scripts/ConstDic';
import { importQuestionBand } from '@/api/race';
import { getCompanyList } from '@/api/company';
export default {
    data() {
        return {
            currentPage: 1,
            tableData: [],
            pageSize: 10,
            companyId: '',
            companyList: [],
            loading: false
        };
    },
    computed: {
        userId() {
            return this.$store.state.user.id;
        },
        totalNum() {
            return this.$store.state.race.preTheoryData.length;
        }
    },
    mounted() {
        this.handlePreDataPaging();
        this.loading = false;
        getCompanyList().then(resp => {
            this.companyList = resp.data;
        });
    },
    methods: {
        edit(index, row) {
            const number = (this.currentPage - 1) * this.pageSize + index;
            this.$router.push({path: `${UrlConfig.bank.questionUpdate}/${number}`, query:{ draft: true }});
        },
        handlePreDataPaging() {
            const preData = this.$store.state.race.preTheoryData;
            const list = [];
            preData.forEach((item, index) => {
                if (index >= this.pageSize * (this.currentPage - 1) && index < this.pageSize * this.currentPage) {
                    list.push(item);
                }
            });
            this.tableData = list;
        },
        doDelete(index, row) {
            this.$confirm('删除试题，是否继续？', '提 示', {
                confirmButtonText: '确 定',
                cancelButtonText: '取 消',
                type: 'warning'
            }).then(() => {
                this.$store.state.race.preTheoryData.splice(index, 1);
                this.handlePreDataPaging();
            }).catch( () => { });
        },
        answerTags(row) {
            const answer = [];
            row.optionList.forEach((el, i) => {
                switch (row.type) {
                case 'select':
                    if (el.correct) {
                        answer.push(this.$asc2chart(i + 65));
                    }
                    break;
                case 'judge':
                    if (el.correct) {
                        answer.push(el.content);
                    }
                    break;
                case 'multi':
                    if (el.correct) {
                        answer.push(this.$asc2chart(i + 65));
                    }
                    break;
                case 'fill':
                    answer.push(el.content);
                    break;
                case 'answer':
                    answer.push(el.content);
                    break;
                }
            });
            return answer;
        },
        reloadTable() {
            this.queryList.reload();
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.handlePreDataPaging();
        },
        handleCurrentChange(val) {
            this.currentPage = val;
            this.handlePreDataPaging();
        },
        doSave() {
            this.loading = true;
            let selectNum = 0;
            let judgeNum = 0;
            let multiNum = 0;
            let fillNum = 0;
            let answerNum = 0;
            this.$store.state.race.preTheoryData.forEach(item => {
                switch (item.type) {
                case 'select':
                    selectNum++;
                    break;
                case 'judge':
                    judgeNum++;
                    break;
                case 'multi':
                    multiNum++;
                    break;
                case 'fill':
                    fillNum++;
                    break;
                case 'answer':
                    answerNum++;
                    break;
                }
            });
            importQuestionBand(this.$store.state.race.preTheoryData, this.companyId).then(resp => {
                this.$store.dispatch('race/setPreTheoryData', []);
                // this.$message.success('导入题库成功!');

                this.$alert(`<strong>本次导入：</strong><br><strong>${judgeNum}道判断题;</strong><br><strong>${selectNum}道选择题;</strong><br><strong>${multiNum}道多选题;</strong><br>`, '导入题库成功!', {
                    dangerouslyUseHTMLString: true,
                    type: 'success',
                    center: true
                });
                this.$router.go(-1);
                this.loading = false;
            }).catch(()=>{
                this.$message.error('导入题库失败！');
                this.loading = false;
            });
        },
        doCancel() {
            this.$store.dispatch('race/setPreTheoryData', []);
            this.$router.go(-1);
        }
    }
};
</script>
