<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>
          <el-button v-waves class="filter-item" type="success" icon="el-icon-refresh" @click="goKeyReset">
            重置
          </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>-->

        <!--        </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 type="index" label="题号" width="50" align="center" />
        <el-table-column :formatter="formatterQuestiontype" prop="QUESTIONTYPE" label="题目类型" width="80" align="center" />
        <el-table-column prop="QUESTIONDRY" label="题干" />
        <el-table-column label="操作" align="left" width="190">
          <template slot-scope="{row}">
            <div v-if="IS_PUBLISH == '0'">
              <el-button v-show="row.QUESTION_ID" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row)">编辑</el-button>
              <el-button v-show="row.QUESTION_ID" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.QUESTION_ID)">删除</el-button>
            </div>
            <div v-if="IS_PUBLISH == '1'">
              <el-button v-show="row.QUESTION_ID" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row)">查看</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page-btn-group">
        <div v-if="IS_PUBLISH == '0'">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
          <el-button type="danger" icon="el-icon-delete" plain @click="batchDel">删除</el-button>
        </div>
        <div v-if="IS_PUBLISH == '1'"/>
        <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
      </div>
      <el-dialog v-if="IS_PUBLISH == '1'" :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'查看':'查看'" width="600px">
        <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 500px;" disabled>
          <el-form-item label="问卷类型" prop="QUESTIONTYPE">
            <el-select v-model="form.QUESTIONTYPE" placeholder="请选择">
              <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>
          <template v-if="form.QUESTIONTYPE !== '3'" >

            <el-form-item v-for="(item,index) in qList" ref="option" :key="index" :prop="'OPTIONDES'+(index+1)" :label="index+1">
              <el-input v-model="item.OPTIONDES" maxlength="255" placeholder="这里输入" style="width: 370px"/>
            </el-form-item>
          </template>
          <el-form-item v-if="form.QUESTIONTYPE !== '3'">
            <!--            <el-button type="success" icon="el-icon-circle-plus" plain @click="addTable()">增加选项</el-button>-->
          </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 v-if="IS_PUBLISH == '0'" :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="请选择">
              <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>
          <template v-if="form.QUESTIONTYPE !== '3'" >

            <el-form-item v-for="(item,index) in qList" ref="option" :key="index" :prop="'OPTIONDES'+(index+1)" :label="index+1">
              <el-input v-model="item.OPTIONDES" maxlength="255" placeholder="这里输入" style="width: 370px"/>
              <i v-if="index>1" class="el-icon-circle-close" plain @click="delTable(index)"/>
            </el-form-item>
          </template>
          <el-form-item v-if="form.QUESTIONTYPE !== '3'">
            <el-button type="success" icon="el-icon-circle-plus" plain @click="addTable()">增加选项</el-button>
          </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="">
                    <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: '', // 题干
        OPTIONDES: '', // 选项
        SURVEY_ID: this.$parent.SURVEY_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' }],
        OPTIONDES: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      dialogFormDaoru: false,
      daoruFrom: {
        FFILE: '',
        FFILEName: ''
      },
      qList: [
        { 'OPTIONDES': '' },
        { 'OPTIONDES': '' }
      ],
      IS_PUBLISH: ''
    }
  },

  created() {
    this.getList()
  },
  methods: {
    getRowKey(row) {
      return row.QUESTION_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.SURVEY_ID = this.$parent.SURVEY_ID
      this.getList()
    },
    // 重置
    goKeyReset() {
      this.KEYWORDS = ''
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/surveyquestion/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          SURVEY_ID: this.$parent.SURVEY_ID
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.IS_PUBLISH = this.$parent.IS_PUBLISH
        console.log(this.IS_PUBLISH)
        this.hasButton()
        this.pd = data.pd
        this.resetForm()
      }).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 ''
    },

    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      this.getDict()
      this.dialogFormEdit = true
      this.qList = [
        { 'OPTIONDES': '' },
        { 'OPTIONDES': '' }]
    },
    addTable() {
      var option = { 'OPTIONDES': '' }
      this.qList.push(option)
    },
    delTable(index) {
      this.qList.splice(index, 1)
    },
    // 修改
    handleEdit(row) {
      requestFN(
        '/surveyquestion/goEdit',
        {
          QUESTION_ID: row.QUESTION_ID
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.pd = Object.assign({}, data.pd)
          this.qList = data.itemList
          this.QUESTION_ID = this.pd.QUESTION_ID
        }
        this.dialogType = 'edit'
        this.form = Object.assign({}, row)
        this.form.QUESTIONNUMBER = Number(this.form.QUESTIONNUMBER)
        this.dialogFormEdit = true
      }).catch((e) => {

      })
    },

    clearAnswer() {
      this.form.ANSWER = ''
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.form.QUESTIONTYPE !== '3') {
            this.listLoading = true
            console.log(JSON.stringify(this.qList))
            requestFN(
              '/surveyquestion/' + this.dialogType,
              {
                OPTIONDES: JSON.stringify(this.qList),
                QUESTIONTYPE: this.form.QUESTIONTYPE,
                QUESTIONDRY: this.form.QUESTIONDRY,
                QUESTIONNUMBER: this.form.QUESTIONNUMBER,
                SURVEY_ID: this.form.SURVEY_ID,
                QUESTION_ID: this.form.QUESTION_ID
              },
              // this.form,
              this.SURVEY_ID = this.$parent.SURVEY_ID

            ).then((data) => {
              this.listLoading = false
              this.dialogFormEdit = false
              this.getList()
            }).catch((e) => {
              this.listLoading = false
            })
          } else {
            this.listLoading = true
            console.log(JSON.stringify(this.qList))
            requestFN(
              '/surveyquestion/' + this.dialogType,
              {
                OPTIONDES: this.form.OPTIONDES,
                QUESTIONTYPE: this.form.QUESTIONTYPE,
                QUESTIONDRY: this.form.QUESTIONDRY,
                QUESTIONNUMBER: this.form.QUESTIONNUMBER,
                SURVEY_ID: this.form.SURVEY_ID,
                QUESTION_ID: this.form.QUESTION_ID
              },
              // this.form,
              this.SURVEY_ID = this.$parent.SURVEY_ID

            ).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(
          '/surveyquestion/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(
          '/surveyquestion/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 = 'surveyquestion:add,surveyquestion:del,surveyquestion:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.surveyquestionfhadminadd		// 新增权限
        this.del = data.surveyquestionfhadmindel		// 删除权限
        this.edit = data.surveyquestionfhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict: function() {
    },
    resetForm() {
      this.form = {
        QUESTIONNUMBER: '', // 题号
        QUESTIONTYPE: '', // 试题类型（单选题、多选题、问答题）
        QUESTIONDRY: '', // 题干
        OPTIONDES: '',
        SURVEY_ID: this.$parent.SURVEY_ID// 课件ID
      }
    },
    goBack() {
      this.$parent.activeName = 'List'
      this.$parent.SURVEY_ID = ''
    },
    getExcelModel() {
      this.$confirm('确定要下载excel模板吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = false
        window.location.href = config.httpurl + 'surveyquestion/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('SURVEY_ID', this.$parent.SURVEY_ID)// 课件ID
      upload(
        '/surveyquestion/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) {
      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>
