<template>
  <div class="bbsl-common-page">
    <div class="bbsl-table-search">
      <el-form v-model="queryParam" :inline="true">
        <el-form-item label="考试题目：">
          <el-input
            v-model="querys[0].value"
            clearable
            placeholder="请输入考试题目"
          ></el-input>
        </el-form-item>
        <!-- <el-form-item label="课目：">
					<el-select clearable v-model="querys[1].value" filterable placeholder="请选择课目">
						<el-option v-for="item in subjectsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item> -->
        <el-form-item label="题型：">
          <el-select
            v-model="querys[2].value"
            clearable
            placeholder="请选择题型"
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="试题难度：">
          <el-select
            v-model="querys[3].value"
            clearable
            placeholder="请选择试题难度"
          >
            <el-option
              v-for="item in difficultyList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" type="primary" @click="handleSearch"
            >搜索
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="fullheight">
      <el-col :span="6" class="fullheight">
        <div class="common-tree-container">
          <div class="container-head">
            <el-input
              v-model="filterText"
              clearable
              placeholder="输入关键字进行过滤"
            >
            </el-input>
            <img
              v-if="expandAll"
              src="@/assets/img/quanjusuoxiao2.png"
              @click="expandHandle"
            />
            <img v-else src="@/assets/img/quanping.png" @click="expandHandle" />
            <i class="el-icon-refresh" @click="getSubjects"></i>
          </div>
          <el-tree
            ref="tree"
            :current-node-key="currentKey"
            :data="treeData"
            :expand-on-click-node="expandAll"
            :filter-node-method="filterNode"
            :props="defaultProps"
            class="filter-tree"
            highlight-current
            node-key="id"
            @node-click="handleNodeClick"
          >
          </el-tree>
          <!-- <div class="title">
						<el-input placeholder="请输入关键字搜索" v-model="search">
							<i slot="suffix" class="el-input__icon el-icon-search" clearable
								style="color:#CCCCCC;cursor:pointer;" ></i>
						</el-input>
					</div> -->
          <!-- <el-tree ref="tree" highlight-current :data="treeData" :props="defaultProps" node-key="id" :filter-node-method="filterNode"
						:expand-on-click-node="false" :current-node-key="currentKey" default-expand-all
						@node-click="handleNodeClick">
					</el-tree> -->
        </div>
      </el-col>
      <el-col :span="18" class="fullheight">
        <div ref="contentPanel" class="bbsl-table-content">
          <div ref="btnPanel" class="bbsl-btn-content">
            <div style="display: flex;">
              <el-button icon="el-icon-plus" type="success" @click="handleAdd"
                >新增
              </el-button>
              <el-popconfirm
                title="确定删除选中数据吗？"
                @confirm="handleDelete"
              >
                <el-button
                  slot="reference"
                  :disabled="!multipleSelection.length"
                  icon="el-icon-delete"
                  style="margin:0 10px"
                  type="danger"
                  >删除
                </el-button>
              </el-popconfirm>

              <el-upload
                v-if="type == 3"
                ref="upload"
                :auto-upload="false"
                :file-list="fileList"
                :http-request="upLoadFile"
                :on-change="e => handleChange(e, fileList)"
                :show-file-list="false"
                accept="."
                action="no"
                class="avatar-uploader"
              >
                <el-button
                  icon="el-icon-download"
                  style="margin-right: 10px;"
                  type="primary"
                  >导入
                </el-button>
              </el-upload>
              <el-button
                v-else
                icon="el-icon-download"
                type="primary"
                @click="importData"
                >导入
              </el-button>
              <el-button
                icon="el-icon-upload2"
                type="warning"
                @click="exportFile"
                >导出
              </el-button>
              <el-button icon="el-icon-document" type="info">
                <a
                  :href="this.portal + '/exam/questions/info/downModel'"
                  target="_blank"
                  >下载模板</a
                >
              </el-button>
            </div>
          </div>
          <el-table
            ref="multipleSelection"
            v-loading="loading"
            :data="tableData"
            :max-height="tableMaxHeight"
            :style="{width: '100%'}"
            size="mini"
            @row-dblclick="handleDbClick"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="考试题目" min-width="200" prop="question">
              <template slot-scope="scope">
                <span v-html="scope.row.question"></span>
              </template>
            </el-table-column>
            <el-table-column label="课目" prop="subjectName"></el-table-column>
            <el-table-column label="题型" prop="typeName"></el-table-column>
            <!-- <el-table-column prop="markTypeName" label="评卷方式"></el-table-column> -->
            <el-table-column
              label="试题难度"
              prop="difficultyName"
            ></el-table-column>
            <el-table-column
              label="创建时间"
              min-width="120"
              prop="createTime"
              show-overflow-tooltip
            >
            </el-table-column>
          </el-table>
          <el-pagination
            ref="paginationPanel"
            :current-page="queryParam.pageBean.page"
            :page-size="queryParam.pageBean.pageSize"
            :page-sizes="[20, 30, 40, 50]"
            :total="total"
            align="right"
            background
            class="bbsl-pagination"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-col>
    </el-row>

    <questionListMenuDialog ref="formModal" @loadData="loadData">
    </questionListMenuDialog>
  </div>
</template>

<script>
import dictUtils from '@/components/dict/DictSelectUtils.js'
import {TableMixin} from '@/mixins/tableMixin'
import questionListMenuDialog from './components/questionListMenuDialog.vue'
import questionListMenu from '@/api/examination/questionListMenu.js'

export default {
  mixins: [TableMixin],
  name: 'questionListMenu',
  components: {
    questionListMenuDialog
  },
  data() {
    return {
      url: {
        delete: '/exam/questions/info/'
      },
      querys: [
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'question',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'LIKE',
          parentGroup: '',
          property: 'ps.full_id_',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'type',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'difficulty',
          relation: 'AND',
          value: ''
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'q.IS_DELE_',
          relation: 'AND',
          value: '0'
        },
        {
          group: 'main',
          operation: 'EQUAL',
          parentGroup: '',
          property: 'IS_DELE_',
          relation: 'AND',
          value: '0'
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      tableData: [],
      multipleSelection: [],
      typeList: [],
      markTypeList: [],
      difficultyList: [],
      fileList: [],
      search: '',
      treeData: [],
      currentKey: null,
      subjectId: [],
      subjectList: [],
      type: '',
      filterText: '',
      expandAll: false
    }
  },
  created() {
    this.getSubjects()
    this.difficultyList = dictUtils.getDictItemsFromCache('stnd')
    this.typeList = dictUtils.getDictItemsFromCache('sttx')
    console.log(this.typeList)
    this.markTypeList = dictUtils.getDictItemsFromCache('pjfs')
  },
  mounted() {},
  watch: {
    currentKey: {
      handler(value) {
        if (value) {
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.currentKey)
          })
        }
      },
      immediate: true,
      valType: false
    },
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    expandHandle() {
      console.log(this.$refs.tree.store)
      this.expandAll = !this.expandAll
      this.expandNodes(this.$refs.tree.store.root)
    },
    // 遍历树形数据，设置每一项的expanded属性，实现展开收起
    expandNodes(node) {
      node.expanded = this.expandAll
      for (let i = 0; i < node.childNodes.length; i++) {
        node.childNodes[i].expanded = this.expandAll
        if (node.childNodes[i].childNodes.length > 0) {
          this.expandNodes(node.childNodes[i])
        }
      }
    },
    // filterNode(value, data) {
    //   // console.log(data);
    //   if (!value) return true
    //   return data.name.indexOf(value) !== -1
    // },
    importData() {
      this.$message({
        message: '请选择课目',
        type: 'warning'
      })
    },
    // 获取list
    loadData(page) {
      if (page) {
        this.queryParam.pageBean.page = page
      }
      this.loading = true
      this.tableData = []
      this.queryParam.querys = []
      this.queryParam.sorter = [
        {
          direction: 'DESC',
          property: 'createTime'
        }
      ]
      if (this.querys[0].value) {
        this.queryParam.querys.push(this.querys[0])
      }
      if (this.querys[1].value) {
        this.queryParam.querys.push(this.querys[1])
      }
      if (this.querys[2].value) {
        this.queryParam.querys.push(this.querys[2])
      }
      if (this.querys[3].value) {
        this.queryParam.querys.push(this.querys[3])
      }
      if (this.querys[4].value) {
        this.queryParam.querys.push(this.querys[4])
      }

      questionListMenu.getQuestions(this.queryParam, res => {
        this.total = res.total
        this.tableData = res.rows
        this.tableData.forEach(item => {
          if (this.typeList) {
            this.typeList.forEach(tt => {
              if (item.type == tt.value) {
                item['typeName'] = tt.name
              }
            })
          }
          if (this.difficultyList) {
            this.difficultyList.forEach(dd => {
              if (item.difficulty == dd.value) {
                item['difficultyName'] = dd.name
              }
            })
          }
          if (this.markTypeList) {
            this.markTypeList.forEach(mm => {
              if (item.markType == mm.value) {
                item['markTypeName'] = mm.name
              }
            })
          }
        })
        this.$set(this.tableData)
        this.loading = false
      })
    },
    // 打开搜索更多
    openMore() {
      this.showMore = !this.showMore
    },
    //获取课目
    getSubjects() {
      this.currentKey = null
      questionListMenu.getSubjects({}, res => {
        if (res.value) {
          this.treeData = res.value
          this.currentKey = this.treeData[0].id
        }
      })
    },
    handleAdd() {
      if (this.type == 3) {
        this.$refs.formModal.add(this.subjectId, this.subjectList)
      } else {
        this.$message.warning('请先选择课目')
      }
    },
    // 导入
    handleAvatarSuccess() {},
    beforeAvatarUpload() {},
    tableRowClassName({row, rowIndex}) {
      if (rowIndex % 2 == 0) {
        return 'warning-row'
      } else {
        return ''
      }
    },
    //导入
    handleChange(file, fileList) {
      console.log(1)
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
      if (
        file.raw.name.split('.')[1] == 'xlsx' ||
        file.raw.name.split('.')[1] == 'xls' ||
        file.raw.name.split('.')[1] == 'xlsm'
      ) {
        this.upLoadFile(file.raw)
      } else {
        this.$message.warning('请上传xls,xlsx,xlsm格式文件！')
        fileList.splice(0)
      }
    },
    //自定义上传方法（覆盖默认上传行为）
    upLoadFile(file) {
      let formData = new FormData()
      formData.append('file', file)
      formData.append('subjectId', this.querys[1].value)
      // subjectId:this.querys[1].value,
      questionListMenu.importExcel(formData, res => {
        if (res.state) {
          this.$notify({
            type: 'success',
            message: '导入成功',
            duration: 2000
          })
          this.loadData(1)()
        } else {
          this.$notify({
            type: 'error',
            message: res.message,
            duration: 2000,
            offset: 80
          })
          this.loadData(1)
        }
      })
    },
    exportFile() {
      let params = JSON.parse(JSON.stringify(this.queryParam))
      params.querys = []
      if (this.querys[0].value) {
        params.querys.push(this.querys[0])
      }
      if (this.querys[1].value) {
        params.querys.push(this.querys[1])
      }
      if (this.querys[2].value) {
        params.querys.push(this.querys[2])
      }
      if (this.querys[3].value) {
        params.querys.push(this.querys[3])
      }
      if (this.querys[5].value) {
        params.querys.push(this.querys[5])
      }
      questionListMenu.export(
        {
          querys: params.querys,
          pageBean: {
            pageSize: -1
          }
        },
        res => {
          if (res) {
          }
        }
      )
    },
    filterNode(value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },

    // 点击树查看数据
    handleNodeClick(data) {
      this.subjectId = []
      this.subjectList = []
      this.type = data.type
      this.querys[1].value = data.id
      this.subjectId.push(data.id)
      this.subjectList.push(data)
      this.loadData(1)
    }
  }
}
</script>

<style lang="scss" scoped>
a {
  text-decoration: none;
  color: #ffffff;
}

.common-tree-container {
  height: calc(100% - 70px);
  margin-top: 0.52083vw;
  padding: 1.04167vw 1.04167vw;
  background-color: #fff;
  position: relative;
  box-sizing: border-box;
  overflow-y: auto;
  border-radius: 20px;
  box-shadow: 0px 0px 0.625vw 0 rgba(92, 102, 83, 0.2);
}

.title {
  width: 100%;
  margin-bottom: 10px;

  i {
    color: #1289fe;
    font-size: 25px;
  }

  span {
    font-size: 25px;
  }
}

::v-deep .el-tree {
  height: 90%;
  overflow-y: auto;
  border: none;
}

::v-deep .el-tree-node__content {
  padding: 5px 0;
}

::v-deep .ql-editor {
  min-height: 100px;
}

.container-head {
  display: flex;
  align-items: center;

  img {
    width: 28px;
    height: 28px;
    margin: auto 5px;
    cursor: pointer;
  }

  i {
    font-size: 28px;
    font-weight: 600;
    cursor: pointer;
  }
}
</style>
