<template>
  <div>
    <div class="app-container">
      <div class="filter-container">
        <el-input v-model="KEYWORDS" placeholder="搜索" class="filter-item" style="width: 150px;"/>
        <div class="filter-group">
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="getQuery">
            搜索
          </el-button>
        </div>
        <div class="filter-flot">
          <el-button v-waves class="filter-item" type="info" icon="el-icon-bottom-right" size="mini" plain @click="dialogFormDaoru = true">
            导入
          </el-button>
          <!-- <el-button v-waves size="mini" plain type="info" icon="el-icon-bottom-right" @click="dialogFormDaoru = true">
            导入
          </el-button> -->
        </div>
      </div>
      <el-table
        v-loading="listLoading"
        ref="multipleTable"
        :data="varList"
        :row-key="getRowKey"
        :header-cell-style="{
          'font-weight': 'bold',
          'color': '#000'
        }"
        tooltip-effect="dark"
        border
        fit
        highlight-current-row
      >
        <el-table-column
          :reserve-selection="true"
          type="selection"
          width="55"
          align="center"/>
        <el-table-column prop="QUESTIONNUMBER" label="题号" width="60" align="center" />
        <el-table-column :formatter="formatterQuestiontype" prop="QUESTIONTYPE" label="试题类型" width="80" align="center" />
        <el-table-column prop="QUESTIONDRY" label="题干" />
        <!--      <el-table-column prop="OPTIONA" label="选项A" />-->
        <!--      <el-table-column prop="OPTIONB" label="选项B" />-->
        <!--      <el-table-column prop="OPTIONC" label="选项C" />-->
        <!--      <el-table-column prop="OPTIOND" label="选项D" />-->
        <el-table-column prop="ANSWER" label="答案" width="55" align="center" >
          <template slot-scope="{row}">
            <template v-if="row.QUESTIONTYPE=='3'" >
              <div v-if="row.ANSWER =='A'">正确</div>
              <div v-if="row.ANSWER =='B'">错误</div>
            </template>
            <template v-else>
              <div >{{ row.ANSWER }}</div>
            </template>

          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="190">
          <template slot-scope="{row}">
            <!-- 学习记录、课考记录、阶考记录有值时不允许编辑 （修改成删除一致的逻辑）
                 学习记录、课考记录、阶考记录有值，课考试卷、阶考试卷有关联时不能删除 -->
            <el-button v-show="edit && row.STUDYCOUNT == 0 && row.COURSEEXAMRECORDCOUNT == 0 && row.STAGEEXAMRECORDCOUNT == 0 && row.COURSEEXAMCOUNT == 0 && row.STAGEEXAMCOUNT == 0" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row)">编辑</el-button>
            <el-button v-show="del && row.STUDYCOUNT == 0 && row.COURSEEXAMRECORDCOUNT == 0 && row.STAGEEXAMRECORDCOUNT == 0 && row.COURSEEXAMCOUNT == 0 && row.STAGEEXAMCOUNT == 0" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.QUESTION_ID)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-btn-group">
        <div>
          <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="batchDel">删除</el-button>
        </div>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>

      <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="600px">
        <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 500px;">
          <!--          <el-form-item label="题号" prop="QUESTIONNUMBER">-->
          <!--            <el-input id="QUESTIONNUMBER" ref="QUESTIONNUMBER" v-model.number="form.QUESTIONNUMBER" maxlength="11" placeholder="这里输入题号..." title="题号"/>-->
          <!--          </el-form-item>-->
          <el-form-item label="试题类型" prop="QUESTIONTYPE">
            <el-select v-model="form.QUESTIONTYPE" placeholder="请选择" @change="clearAnswer">
              <el-option v-for="item in questiontypeOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
          <el-form-item label="题干" prop="QUESTIONDRY">
            <el-input id="QUESTIONDRY" ref="QUESTIONDRY" v-model="form.QUESTIONDRY" type="textarea" maxlength="255" placeholder="这里输入题干..." title="题干"/>
          </el-form-item>
          <el-form-item v-if="form.QUESTIONTYPE !== '3'" label="选项A" prop="OPTIONA">
            <el-input id="OPTIONA" ref="OPTIONA" v-model="form.OPTIONA" maxlength="255" placeholder="这里输入选项A..." title="选项A"/>
          </el-form-item>
          <el-form-item v-if="form.QUESTIONTYPE !== '3'" label="选项B" prop="OPTIONB">
            <el-input id="OPTIONB" ref="OPTIONB" v-model="form.OPTIONB" maxlength="255" placeholder="这里输入选项B..." title="选项B"/>
          </el-form-item>
          <el-form-item v-if="form.QUESTIONTYPE !== '3'" label="选项C" prop="OPTIONC">
            <el-input id="OPTIONC" ref="OPTIONC" v-model="form.OPTIONC" maxlength="255" placeholder="这里输入选项C..." title="选项C"/>
          </el-form-item>
          <el-form-item v-if="form.QUESTIONTYPE !== '3'" label="选项D" prop="OPTIOND">
            <el-input id="OPTIOND" ref="OPTIOND" v-model="form.OPTIOND" maxlength="255" placeholder="这里输入选项D..." title="选项D"/>
          </el-form-item>
          <el-form-item label="答案" prop="ANSWER">
            <el-select v-model="form.ANSWER" placeholder="请选择">
              <el-option v-for="item in answerOptions" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        <!--        <el-form-item label="课件类型(1:视频课件、2:资料课件)" prop="COURSEWARETYPE">-->
        <!--          <el-input id="COURSEWARETYPE" ref="COURSEWARETYPE" v-model="form.COURSEWARETYPE" maxlength="255" placeholder="这里输入课件类型(1:视频课件、2:资料课件)..." title="课件类型(1:视频课件、2:资料课件)"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="课件ID" prop="COURSEWAREID">-->
        <!--          <el-input id="COURSEWAREID" ref="COURSEWAREID" v-model="form.COURSEWAREID" maxlength="255" placeholder="这里输入课件ID..." title="课件ID"/>-->
        <!--        </el-form-item>-->
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormEdit = false">取 消</el-button>
          <el-button type="primary" @click="confirm">确 定</el-button>
        </div>
      </el-dialog>
      <el-dialog :visible.sync="dialogFormDaoru" title="导入" width="800px">
        <template>
          <div class="app-container">
            <el-form ref="form" :model="daoruFrom" label-width="110px" class="in-uploader">
              <el-form-item label="上传附件" prop="FIELDS">
                <div class="uploader">
                  <el-input v-model="daoruFrom.FFILEName" :disabled="true" />
                  <el-upload :before-upload="beforeFileUpload" class="avatar-uploader" action="" accept=".xls">
                    <el-button type="primary" icon="el-icon-upload" style="margin-left:10px">上传附件</el-button>
                  </el-upload>
                  <el-button v-waves type="success" icon="el-icon-right" style="margin-left:10px;width:150px" @click="getExcelModel">
                    导出模板
                  </el-button>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </template>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormDaoru = false">取 消</el-button>
          <el-button type="primary" @click="goUpload">确 定</el-button>
        </div>
      </el-dialog>
    </div>
    <div class="ui-height" />
    <div class="ui-foot">
      <el-button plain type="info" @click="goBack">返 回</el-button>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import { upload } from '@/utils/upload'
export default {
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      config: config,
      KEYWORDS: '',
      varList: [],
      pd: [],
      questiontypeOptions: [{
        value: '1',
        label: '单选题'
      }, {
        value: '2',
        label: '多选题'
      }, {
        value: '3',
        label: '判断题'
      }],
      answerOptions: [],
      form: {
        QUESTIONNUMBER: '', // 题号
        QUESTIONTYPE: '', // 试题类型（单选题、多选题、判断题）
        QUESTIONDRY: '', // 题干
        OPTIONA: '', // 选项A
        OPTIONB: '', // 选项B
        OPTIONC: '', // 选项C
        OPTIOND: '', // 选项D
        ANSWER: '', // 答案
        COURSEWARETYPE: this.$parent.COURSEWARETYPE, // 课件类型(1:视频课件、2:资料课件)
        COURSEWAREID: this.$parent.COURSEWAREID// 课件ID
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogType: 'add',
      rules: {
        // QUESTIONNUMBER: [
        //   { required: true, message: '题号不能为空' },
        //   { type: 'number', message: '题号必须为数字' },
        //   { validator: hasQuestionNumber, trigger: 'blur' }],
        QUESTIONTYPE: [{ required: true, message: '试题类型（单选题、多选题、判断题）不能为空', trigger: 'blur' }],
        QUESTIONDRY: [{ required: true, message: '题干不能为空', trigger: 'blur' }],
        OPTIONA: [{ required: true, message: '选项A不能为空', trigger: 'blur' }],
        OPTIONB: [{ required: true, message: '选项B不能为空', trigger: 'blur' }],
        OPTIONC: [{ required: true, message: '选项C不能为空', trigger: 'blur' }],
        OPTIOND: [{ required: true, message: '选项D不能为空', trigger: 'blur' }],
        ANSWER: [{ required: true, message: '答案不能为空', trigger: 'blur' }],
        COURSEWARETYPE: [{ required: true, message: '课件类型(1:视频课件、2:资料课件)不能为空', trigger: 'blur' }],
        COURSEWAREID: [{ required: true, message: '课件ID不能为空', trigger: 'blur' }]
      },
      dialogFormDaoru: false,
      daoruFrom: {
        FFILE: '',
        FFILEName: ''
      }
    }
  },
  watch: {
    'form.QUESTIONTYPE': {
      handler() {
        if (this.form.QUESTIONTYPE === '3') {
          this.rules.OPTIONC = [{ required: false, message: '选项C不能为空', trigger: 'blur' }]
          this.rules.OPTIOND = [{ required: false, message: '选项D不能为空', trigger: 'blur' }]
        } else {
          this.rules.OPTIONC = [{ required: true, message: '选项C不能为空', trigger: 'blur' }]
          this.rules.OPTIOND = [{ required: true, message: '选项D不能为空', trigger: 'blur' }]
        }
        this.getAnswerList()
      }
    }
  },
  created() {
    this.getList(this.ROLE_ID)
  },
  methods: {
    getRowKey(row) {
      return row.QUESTION_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/question/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          COURSEWARETYPE: this.$parent.COURSEWARETYPE, // 课件类型(1:视频课件、2:资料课件)
          COURSEWAREID: this.$parent.COURSEWAREID// 课件ID
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 格式化试题类型名称
    formatterQuestiontype(row, column) {
      for (let i = 0; i < this.questiontypeOptions.length; i++) {
        const option = this.questiontypeOptions[i]
        if (option.value === row.QUESTIONTYPE) {
          return option.label
        }
      }
      return ''
    },
    getAnswerList() {
      if (this.form.QUESTIONTYPE === '1') { // 单选题
        this.answerOptions = [
          { value: 'A', label: 'A' },
          { value: 'B', label: 'B' },
          { value: 'C', label: 'C' },
          { value: 'D', label: 'D' }]
      } else if (this.form.QUESTIONTYPE === '2') { // 多选题、
        this.answerOptions = [
          { value: 'AB', label: 'AB' },
          { value: 'AC', label: 'AC' },
          { value: 'AD', label: 'AD' },
          { value: 'BC', label: 'BC' },
          { value: 'BD', label: 'BD' },
          { value: 'CD', label: 'CD' },
          { value: 'ABC', label: 'ABC' },
          { value: 'ABD', label: 'ABD' },
          { value: 'ACD', label: 'ACD' },
          { value: 'BCD', label: 'BCD' },
          { value: 'ABCD', label: 'ABCD' }]
      } else if (this.form.QUESTIONTYPE === '3') { // 判断题
        this.answerOptions = [
          { value: 'A', label: '正确' },
          { value: 'B', label: '错误' }]
      } else {
        this.answerOptions = []
      }
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      this.getDict()
      this.getAnswerList()
      this.dialogFormEdit = true
    },
    // 修改
    handleEdit(row) {
      this.dialogType = 'edit'
      this.form = Object.assign({}, row)
      this.form.QUESTIONNUMBER = Number(this.form.QUESTIONNUMBER)
      this.getAnswerList()
      this.dialogFormEdit = true
    },
    clearAnswer() {
      this.form.ANSWER = ''
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.QUESTIONTYPE == '3') {
            this.form.OPTIONA = '正确'
            this.form.OPTIONB = '错误'
          }
          var arr = []
          if (this.form.QUESTIONTYPE == '3') {
            arr = ['#' + this.form.OPTIONA + '#', '#' + this.form.OPTIONB + '#']
          } else {
            arr = ['#' + this.form.OPTIONA + '#', '#' + this.form.OPTIONB + '#', '#' + this.form.OPTIONC + '#', '#' + this.form.OPTIOND + '#']
          }
          // 将数组中的元素放在一个字符串中，用逗号分隔
          var s = arr.join(',') + ','
          for (var i = 0; i < arr.length - 1; i++) {
            if (s.replace(arr[i] + ',', '').indexOf(arr[i]) > -1) {
              this.$message.warning('试题答案重复:' + arr[i].split('#').join(''))
              return false
            }
          }
          this.listLoading = true
          requestFN(
            '/question/' + this.dialogType,
            this.form
          ).then((data) => {
            this.listLoading = false
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            this.listLoading = false
          })
        } else {
          return false
        }
      })
    },

    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/question/delete',
          {
            QUESTION_ID: id
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.QUESTION_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/question/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      var keys = 'courseware:add,courseware:del,courseware:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.coursewarefhadminadd		// 新增权限
        this.del = data.coursewarefhadmindel		// 删除权限
        this.edit = data.coursewarefhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict: function() {
    },
    resetForm() {
      this.form = {
        QUESTIONNUMBER: '', // 题号
        QUESTIONTYPE: '', // 试题类型（单选题、多选题、判断题）
        QUESTIONDRY: '', // 题干
        OPTIONA: '', // 选项A
        OPTIONB: '', // 选项B
        OPTIONC: '', // 选项C
        OPTIOND: '', // 选项D
        ANSWER: '', // 答案
        COURSEWARETYPE: this.$parent.COURSEWARETYPE, // 课件类型(1:视频课件、2:资料课件)
        COURSEWAREID: this.$parent.COURSEWAREID// 课件ID
      }
    },
    goBack() {
      this.$parent.activeName = 'List'
    },
    getExcelModel() {
      this.$confirm('确定要下载excel模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + 'question/downExcel'
      }).catch(() => {
        this.listLoading = false
      })
      this.listLoading = false
    },
    goUpload() {
      if (!this.daoruFrom.FFILE) {
        this.$message.warning('课件习题附件不能为空，请上传')
        return false
      }
      const formData = new FormData()
      Object.keys(this.daoruFrom).map(key => {
        formData.append(key, this.daoruFrom[key])
      })
      formData.append('COURSEWARETYPE', this.$parent.COURSEWARETYPE)// 课件类型(1:视频课件、2:资料课件)
      formData.append('COURSEWAREID', this.$parent.COURSEWAREID)// 课件ID
      upload(
        '/question/readExcel',
        formData
      ).then((data) => {
        this.$message({
          dangerouslyUseHTMLString: true,
          message: data.resultStr,
          type: data.result,
          showClose: true,
          duration: 10 * 1000
        })
        this.dialogFormDaoru = false
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    beforeFileUpload(file) {
      const types = ['xls']
      // const isfile = types.includes(file.type)
      const fileSuffix = file.name.slice(file.name.lastIndexOf('.') + 1)
      const isfile = types.includes(fileSuffix.toLowerCase())
      if (!isfile) {
        this.$message.error('上传附件只能是 xls 格式!')
        return false
      } else {
        this.daoruFrom.FFILE = file
        this.daoruFrom.FFILEName = file.name
        this.$forceUpdate()
        return false
      }
    }
  }
}

</script>

<style lang="sass" scoped>
.table-qrcode
  text-align: center
  padding-top: 20px
  width: 100%
.filter-container
  position: relative
  .filter-flot
    position: absolute
    right: 0
    top: 0
.uploader
  width: 570px
  display: flex
  align-items: center
.el-form-item__content
  line-height: 1
</style>
<style lang="scss" scoped>
>>> .el-dialog__body {
  padding: 30px 20px 10px 40px;
}
</style>
