<template>
  <a-card :bordered='false'>

    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='searchQuery'>
        <a-row :gutter='24'>
          <a-col :lg='7' :md='8' :sm='24' :xl='6'>
            <a-form-item label='题目'>
              <j-input v-model='queryParam.question' placeholder='请输入题目'></j-input>
            </a-form-item>
          </a-col>
          <!--          <a-col :lg='7' :md='8' :sm='24' :xl='6'>-->
          <!--            <a-form-item label='题型'>-->
          <!--              <j-dict-select-tag v-model='queryParam.optionType' dictCode='option_type' placeholder='请选择题型' />-->
          <!--            </a-form-item>-->
          <!--          </a-col>-->
          <a-col :lg='7' :md='8' :sm='24' :xl='6'>
            <a-form-item label='类别'>
              <j-dict-select-tag v-model='queryParam.type' dictCode='topic_type' placeholder='请选择类别' />
            </a-form-item>
          </a-col>
          <a-col :lg='11' :md='10' :sm='24' :xl='10'>
            <a-form-item label='创建日期'>
              <j-date v-model='queryParam.createTime_begin' :show-time='true' class='query-group-cust'
                      date-format='YYYY-MM-DD HH:mm:ss' placeholder='请选择开始时间'></j-date>
              <span class='query-group-split-cust'></span>
              <j-date v-model='queryParam.createTime_end' :show-time='true' class='query-group-cust'
                      date-format='YYYY-MM-DD HH:mm:ss' placeholder='请选择结束时间'></j-date>
            </a-form-item>
          </a-col>
          <!--          <a-col :lg='7' :md='8' :sm='24' :xl='6'>-->
          <!--            <span class='table-page-search-submitButtons' style='float: left;overflow: hidden;'>-->
          <!--             -->
          <!--              <a style='margin-left: 8px' @click='handleToggleSearch'>-->
          <!--                {{ toggleSearchStatus ? '收起' : '展开' }}-->
          <!--                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />-->
          <!--              </a>-->
          <!--            </span>-->
          <!--          </a-col>-->
        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class='table-operator'>

      <a-button icon='search' type='primary' @click='searchQuery'>查询</a-button>
      <a-button icon='reload' type='primary' @click='searchReset'>重置</a-button>
      <a-button icon='plus' type='primary' @click='handleAdd'>新增</a-button>
      <!--            <a-button icon='download' type='primary' @click="handleExportXls('题库')">导出</a-button>-->
      <a-upload :action='importExcelUrl' :headers='tokenHeader' :multiple='false' :showUploadList='false' name='file'
                @change='handleImportExcel'>
        <a-button icon='import' type='primary'>导入</a-button>
      </a-upload>
      <a-dropdown>
        <a-menu slot='overlay'>
          <a-menu-item key='1' type='primary' @click="handleImportModel('网络答题模板',0)">
            <a-icon type='download' />
            网络答题模板
          </a-menu-item>
          <a-menu-item key='2' type='primary' @click="handleImportModel('测评问卷模板',1)">
            <a-icon type='download' />
            测评问卷模板
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px' type='primary'>
          下载模板
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
      <a-dropdown v-if='selectedRowKeys.length > 0'>
        <a-menu slot='overlay'>
          <a-menu-item key='1' @click='batchDel'>
            <a-icon type='delete' />
            删除
          </a-menu-item>
        </a-menu>
        <a-button style='margin-left: 8px'> 批量操作
          <a-icon type='down' />
        </a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i>
        <span>已选择</span>
        <a style='font-weight: 600'>
          {{ selectedRowKeys.length }}
        </a>
        <span>项</span>
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        :columns='columns'
        :dataSource='dataSource'
        :loading='loading'
        :pagination='ipagination'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        bordered
        rowKey='id'
        size='middle'
        @change='handleTableChange'>
        <!-- 字符串超长截取省略号显示 -->
        <span slot='question' slot-scope='text'>
          <j-ellipsis :length='60' :value='text' />
        </span>
        <span slot='action' slot-scope='text, record'>
          <a @click='handleEdit(record)'>编辑</a>
          <a-divider type='vertical' />
          <a-popconfirm title='确定删除吗?' @confirm='() => handleDelete(record.id)'>
            <a>删除</a>
          </a-popconfirm>
        </span>

      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <jeecg-order-modal-for-j-editable-table ref='modalForm' @ok='modalFormOk' />
    <j-modal
      :maskClosable='false'
      :title='model.title'
      :visible.sync='model.visible'
      :width='800'
      @cancel='handleCancel'
      @ok='handleOk'
    >
      <template>
        <div class='scroll_area'>
          <p class='description'>
            <a-form-model ref='form' :label-col='labelCol' :model='model' :rules='validatorRules'
                          :wrapper-col='wrapperCol'>
              <a-row :gutter='0' class='form-row'>
                <a-col :lg='12'>
                  <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='类别' prop='type'>
                    <j-dict-select-tag v-model='model.type' v-decorator="[ 'type', {'initialValue':0}]"
                                       dictCode='topic_type'
                                       placeholder='请选择类别' type='list' />
                  </a-form-model-item>
                </a-col>
                <a-col :lg='12'>
                  <a-form-model-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='题型' prop='optionType'>
                    <j-dict-select-tag v-model='model.optionType' v-decorator="[ 'optionType', {'initialValue':0}]"
                                       dictCode='option_type' placeholder='请选择题型' type='radio' />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </p>
          <a-row v-for='(question,i) in questions' :key='i'>
            <a-col :class="{ 'warning_tips': question.showTips}" :span='24'>
              <p class='title'>{{ i + 1 }}. {{ question.question }}</p>
              <a-row v-for='(option,j) in question.options' :key='j'>
                <a-col :span='24'>
                  <p class='option'>{{ option.number_dictText }}. {{ option.options }}</p>
                </a-col>
              </a-row>
              <div v-if='model.type==2' class='sub_info'>
                <span>答案：{{ question.answer_dictText }}</span>
                <span>积分：{{ question.score }}</span>
              </div>
            </a-col>
          </a-row>
        </div>
      </template>
    </j-modal>
  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JeecgOrderModalForJEditableTable from './modules/QuestionModal'
import JEllipsis from '@/components/jeecg/JEllipsis'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { Modal } from 'ant-design-vue'
import store from '@/store'
import { filterDictText, initDictOptions } from '@comp/dict/JDictSelectUtil'
import { downFile, httpAction } from '@api/manage'

const columns = [
  {
    title: '#',
    dataIndex: '',
    key: 'rowIndex',
    width: 60,
    align: 'center',
    customRender: function(t, r, index) {
      return parseInt(index) + 1
    }
  },
  {
    title: '题目',
    align: 'center',
    dataIndex: 'question',
    key: 'question',
    scopedSlots: { customRender: 'question' }
  },
  {
    title: '题型',
    align: 'center',
    dataIndex: 'optionType_dictText'
  },
  {
    title: '类别',
    align: 'center',
    dataIndex: 'type_dictText'
  },
  {
    title: '答案',
    align: 'center',
    dataIndex: 'answer_dictText'
  },
  // {
  //   title: '题目解析',
  //   align: 'center',
  //   dataIndex: 'topicAnalysis'
  // },
  {
    title: '创建日期',
    align: 'center',
    dataIndex: 'createTime'
  },
  // {
  //   title: '更新人',
  //   align: 'center',
  //   dataIndex: 'updateBy'
  // },
  // {
  //   title: '更新日期',
  //   align: 'center',
  //   sorter: true,
  //   dataIndex: 'updateTime'
  // },
  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 147,
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  name: 'QuestionList',
  mixins: [JeecgListMixin],
  components: {
    JeecgOrderModalForJEditableTable,
    JEllipsis
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 19 }
      },
      description: '题库管理页面',
      // 表头
      columns: columns,
      url: {
        list: '/publish/question/list',
        delete: '/publish/question/delete',
        deleteBatch: '/publish/question/deleteBatch',
        exportXlsUrl: '/publish/question/exportXls1',
        importExcelUrl: 'publish/question/importExcel',
        saveBatch: 'publish/question/saveBatch'
      },
      dictOptions: {},
      superFieldList: [],
      model: {
        title: '预览',
        visible: false,
        optionType: 0
      },
      questions: [],
      answerDictOptions: [],
      validatorRules: {
        optionType: [
          { required: true, message: '请选择题型！' }
        ],
        type: [
          { required: true, message: '请选择类别！' }
        ]
      },
      dictCode: 'topic_type'
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    initDictConfig() {
      //初始化字典 - 性别
      initDictOptions('answer_number').then((res) => {
        if (res.success) {
          this.answerDictOptions = res.result
        }
      })
    },
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'question', text: '问题', dictCode: '' })
      fieldList.push({ type: 'int', value: 'optionType', text: '选项类型', dictCode: 'option_type' })
      fieldList.push({ type: 'int', value: 'type', text: '类型', dictCode: 'topic_type' })
      fieldList.push({ type: 'string', value: 'answer', text: '答案代号', dictCode: 'answer_number' })
      fieldList.push({ type: 'Text', value: 'topicAnalysis', text: '题目解析', dictCode: '' })
      this.superFieldList = fieldList
    },
    handleAdd: function() {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.disableSubmit = false
      this.$refs.modalForm.model = {}
    },
    handleImportModel: function(name, type) {
      if (!name || typeof name != 'string') {
        name = '导出文件'
      }
      let param = { 'fileName': name, 'type': type }
      console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        console.log(data)
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        console.log(window.navigator.msSaveBlob)
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), name + '.xlsx')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          console.log(url)
          let link = document.createElement('a')
          console.log(link)
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', name + '.xlsx')
          console.log(link)
          document.body.appendChild(link)
          link.click()
          console.log(link)
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    handleImportExcel: function(info) {
      console.log(info)
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.$message.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = window._CONFIG['domianURL'] + fileUrl
            this.$warning({
              title: message,
              content: (<div>
                  <span>{msg}</span><br />
                  <span>具体详情请 <a href={href} target='_blank' download={fileName}>点击下载</a> </span>
                </div>
              )
            })
          } else {
            var questions = info.file.response.result
            if (null != questions && questions.length > 0) {
              for (const q of questions) {
                if (null != q.score && undefined != q.score) {
                  this.model.type = 2
                  this.dictCode = 'topic_type'
                } else {
                  this.dictCode = 'Inspection_type'
                }
                if (null != q.answer && undefined != q.answer && '' != q.answer) {
                  q.answer_dictText = filterDictText(this.answerDictOptions, q.answer)
                }
                if (null != q.options && q.options.length > 0) {
                  for (const option of q.options) {
                    option.number_dictText = filterDictText(this.answerDictOptions, option.number)
                  }
                }
              }
            }
            this.questions = questions
            this.model.title = '预览'
            this.model.visible = true
            this.model.optionType = '0'
            // this.$message.success(info.file.response.message || `${info.file.name} 文件上传成功`)
          }
          // this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        if (info.file.response.status === 500) {
          let data = info.file.response
          const token = Vue.ls.get(ACCESS_TOKEN)
          if (token && data.message.includes('Token失效')) {
            Modal.error({
              title: '登录已过期',
              content: '很抱歉，登录已过期，请重新登录',
              okText: '重新登录',
              mask: false,
              onOk: () => {
                store.dispatch('Logout').then(() => {
                  Vue.ls.remove(ACCESS_TOKEN)
                  window.location.reload()
                })
              }
            })
          }
        } else {
          this.$message.error(`文件上传失败: ${info.file.msg} `)
        }
      }
    },
    handleOk() {
      console.log(1111111)
      const that = this
      console.log(that.model)
      console.log(that.questions)
      var questions = that.questions
      var showTips = false
      for (const q of questions) {
        if (that.model.type == 2) {
          if (null == q.answer || undefined == q.answer || null == q.score || undefined == q.score) {
            showTips = true
            q.showTips = true
          }
        } else if (null == q.options || undefined == q.options || q.options.length == 0) {
          showTips = true
          q.showTips = true
        } else {
          q.showTips = false
        }
      }
      console.log(showTips)
      // 触发表单验证
      this.$refs.form.validate(valid => {
        if (valid && !showTips) {
          var model = that.model
          const datas = []
          for (const q of questions) {
            q.type = model.type
            q.optionType = model.optionType
          }
          console.log(showTips)
          console.log(questions)
          var param = { questions: questions }
          let url = this.url.saveBatch, method = 'post'
          httpAction(url, param, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
              that.close()
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          console.log(33444)
          that.model.visible = true
          that.questions = questions
        }

      })
    },
    handleCancel() {
      this.close()
    },
    close() {
      this.model.visible = false
      this.model = {}
      this.loadData(1)
      this.type = 0
    }
  }
}
</script>
<style scoped>

.ant-card-body .table-operator {
  margin-bottom: 18px;
}

.ant-table-tbody .ant-table-row td {
  padding-top: 15px;
  padding-bottom: 15px;
}

.anty-row-operator button {
  margin: 0 5px
}

.ant-btn-danger {
  background-color: #ffffff
}

.ant-modal-cust-warp {
  height: 100%
}

.ant-modal-cust-warp .ant-modal-body {
  height: calc(100% - 110px) !important;
  overflow-y: auto
}

.ant-modal-cust-warp .ant-modal-content {
  height: 90% !important;
  overflow-y: hidden
}

.scroll_area {
  max-height: 600px;
  padding-right: 10px;
  overflow-y: auto;
}

.description {
  margin-bottom: 10px;
  line-height: 2;
}

.title {
  margin: 5px 0;
  padding: 6px 10px;
  background-color: #f8f8f8;
  border-radius: 4px;
  color: #333;
  line-height: 1.5;
}

.option {
  margin: 0;
  padding-left: 20px;
  line-height: 2;
}

.warning_tips {
  color: #F56C6C;
}

.warning_tips .title {
  color: #F56C6C;
}

.sub_info {
  display: flex;
  justify-content: space-between;
  line-height: 2;
  margin-top: 5px;
  margin-left: 20px;
  border-top: 1px dashed #dedede;
}

</style>