<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<template>
  <div class="v-page classify_page">
    <SearchTreeMenu ref="treeMenuRef" title="试题分类列表" :tree-data="question_classify_list" @current-change="change"
      @onCreate="toCreateClassify" @onDelete="toDeleteclassify" @onEdit="toEditClassify" v-loading="classify_loading" />
    <div class="v-ctx" v-loading="questions_list_loading">
      <FormLayout
        ref="formLayoutRef"
        :items="formItems"
        :model="form"
        :rules="rules"
        label-width="70px"
        label-position="right"
        :inline="true"
      >
      <template v-slot:title>
        <!-- <el-input placeholder="请输入查询内容" v-model="form.title" class="input-with-select" clearable>
          <el-button slot="append" @click="pagingFindList">查询</el-button>
        </el-input> -->
        <QueryInput v-model="form.title" @query="pagingFindList"></QueryInput>
      </template>
      <template v-slot:type>
        <el-select v-model="form.type"  placeholder="题型" style="width:100px" clearable @change="pagingFindList">
          <el-option v-for="item in paramsOptions.questionType" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </template>
      <template v-slot:difficultyLevel>
        <el-select v-model="form.difficultyLevel"  placeholder="难度" style="width:100px" clearable @change="pagingFindList">
          <el-option v-for="item in paramsOptions.difficultyLevel" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </template>
      <template v-slot:btns>
        <el-button type="danger" @click="deleteQuestions" round >删除选中</el-button>
        <el-button round @click="importExcel">导入</el-button>
        <el-button round @click="exportAllQuestions">导出</el-button>
        <el-button type="primary" @click="addQuestionHandler" round>添加试题</el-button>
        <!--  icon="el-icon-plus" -->
      </template>

      </FormLayout>
      <TableLayout :column="column" :data="table_data" :pageInfo="page_info"
        @current-change="(e) => pagingChange({ currentPage: e })" @size-change="(e) => pagingChange({ pageSize: e })"
        selection  @selection-change="handleSelectionChange">
        <template v-slot:action="props">
          <!-- <el-button type="text" icon="el-icon-edit">{{ props.row.type }}</el-button> -->
          <el-button type="text" icon="i-j-ksap-bianji2" @click="editQuestion(props.row)">编辑</el-button>
            <el-button  type="text" icon="i-j-fbks-yulan" @click="currentQuestion = props.row;previewQuestionShow=true">预览</el-button>
          <el-button type="text" icon="i-j-ksap-shanchu" @click="deleteQuestions($event,props.row)" style="color:#f04343 !important">删除</el-button>
        </template>
        <template v-slot:student="props">
        <!--  icon="el-icon-plus" -->
          <el-switch
          v-if="props.row.creatorId === $store.user.id"
            v-model="props.row.student"
            :active-value="1"
            :inactive-value="0"
            @change="changeItemStatus($event,props.row)"
            >
          </el-switch>
      </template>
      </TableLayout>
    </div>
    <DialogLayout :visible="previewQuestionShow" title="预览" :actionBarOption="{noCencel:true,noConfirm:true}" :shadowBar="false" @onCancel="previewQuestionShow=false" width="500px">
      <div>
        <QuestionItem :questionInfo="currentQuestion" :mode="6"></QuestionItem>
      </div>
    </DialogLayout>
  </div>
</template>

<script>
import { SearchTreeMenu, TableLayout, FormLayout, DialogLayout } from '@/components/layout'
import QuestionItem from './components/QuestionItem.vue'
import QueryInput from '@/components/widget/QueryInput.vue'
import { findAllQuestionsClassifyApi, createQuestionsClassifyApi, deleteQuestionsClassifyApi, pagingFindQuestionsApi, getAllQueryParamsOptionsApi, deleteSomeQuestionsApi, editQuestionsClassifyApi, exportQuestionsApi, studentCanUseApi } from '@/api/assessment-evaluation/questions'
import * as XLSX from 'xlsx'
export default {
  components: {
    SearchTreeMenu, TableLayout, FormLayout, QuestionItem, QueryInput, DialogLayout
  },

  data: () => ({
    previewQuestionShow: false,
    currentQuestion: null,
    question_classify_list: [],
    classify_default: [],
    table_data: [],
    page_info: { currentPage: 1, pageSize: 10, total: 0 },
    current_classify_id: null,
    // 试题分类树是否加载中
    classify_loading: false,
    questions_list_loading: false,
    form: { title: '', type: null, difficultyLevel: null },
    rules: [],
    formItems: [],
    paramsOptions: {},
    // 表格当前选中项
    tableSelectionsList: []
  }),

  created () {
    this.formItems = [
      { prop: 'title' },
      { prop: 'type' },
      { prop: 'difficultyLevel' },
      { prop: 'btns', model: { class: 'gy-btns' } }
      // {
      //   prop: 'desc',
      //   label: '角色描述',
      //   model: { tag: 'el-input', type: 'textarea' }
      // }
    ]
    this.rules = {
      // name: { required: true, message: '请输入角色名称', trigger: 'blur' }
    }
    this.column = [
      { prop: 'title', label: '题目', width: 200, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'classify', label: '试题分类', align: 'center', 'show-overflow-tooltip': true },
      { prop: 'type', label: '试题类型', width: 100, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'difficultyLevel', label: '试题难度', width: 100, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'createTime', label: '创建时间', width: 100, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'creator', label: '创建人', align: 'center', 'show-overflow-tooltip': true },
      { prop: 'action', label: '操作', width: 200, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'student', label: '学员可选', width: 80, align: 'center', 'show-overflow-tooltip': true }
    ]

    this.findAllQuestionsClassify()
  },
  activated () {
    this.pagingFindList()
    this.findAllQueryParams()
  },
  methods: {
    changeItemStatus (e, row) {
      this.changeQuestionStudentUse(row, e)
    },
    changeQuestionStudentUse (row, studentCanUse) {
      const form = {
        id: row.id,
        student: studentCanUse
      }
      studentCanUseApi(form).then((res) => {
        if (res.code !== 0) {
          paperItem.student = studentCanUse === 1 ? 0 : 1
          this.$message.error('修改失败')
        }
      })
    },
    // 导出所有试题
    exportAllQuestions () {
      let classifyId = this.current_classify_id
      if (this.current_classify_id === 'system' || !this.current_classify_id) {
        classifyId = ''
      }
      const classifyItem = this.classify_default.find(item => item.id === classifyId)
      exportQuestionsApi(classifyId).then(res => {
        const { data } = res
        const sheetDatas = data.reduce((prev, item, ind) => {
          let hasSheet = prev.find(p => p.sheetName === item['类型'])
          if (hasSheet) {
            delete item['类型']
            hasSheet.data.push(item)
          } else {
            hasSheet = { sheetName: item['类型'], data: [] }
            delete item['类型']
            hasSheet.data.push(item)
            prev.push(hasSheet)
          }
          return prev
        }, [])

        const sheets = []
        sheetDatas.forEach((sheetItem) => {
          const data = sheetItem.data
          const ws = XLSX.utils.json_to_sheet(data)
          ws['!cols'] = [{ wch: 60 }, { wch: 10 }, { wch: 30 }, { wch: 40 }, { wch: 40 }, { wch: 40 }]
          sheets.push({
            name: sheetItem.sheetName,
            ws
          })
        })
        const wb = XLSX.utils.book_new()
        sheets.forEach(wsItem => {
          XLSX.utils.book_append_sheet(wb, wsItem.ws, wsItem.name)
        })
        // XLSX.writeFile(wb, `试题导入模板${(new Date()).format('yyyy-MM-dd hh-mm-ss')}.xlsx`)
        // const ws = XLSX.utils.json_to_sheet(data)
        // ws['!cols'] = [{ wch: 60 }, { wch: 10 }, { wch: 10 }, { wch: 30 }, { wch: 40 }, { wch: 40 }, { wch: 40 }]
        // const wb = XLSX.utils.book_new()
        // XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')
        let fileName = ''
        if (classifyItem) {
          fileName += classifyItem.name + ' - '
          this.$message(`您当前选中的【${classifyItem.name}】分类，已导出该分类下的试题`)
        }
        fileName += (new Date()).format('yyyy-MM-dd hh-mm-ss')
        XLSX.writeFile(wb, fileName + '.xlsx')
      })
    },
    // 编辑分类
    toEditClassify (item) {
      if (item.id === 'system') return this.$message('根分类不能修改')
      this.$prompt('请输入新分类名：', '编辑', {
        inputPattern: /.{1,}/,
        inputErrorMessage: '请输入分类名'
      }).then(({ value }) => {
        this.classify_loading = true
        editQuestionsClassifyApi({ ...item, name: value }).then(res => { this.$message.success('修改成功'); this.findAllQuestionsClassify() }).finally(_ => {
          this.classify_loading = false
        })
      }).catch(() => {})
    },
    // 导入按钮handler
    importExcel () {
      this.$router.push({
        path: '/assessment-evaluation/question-bank-manage/add-modify-question',
        query: {
          activeTag: -1
        }
      })
    },
    // 跳转到编辑
    editQuestion (row) {
      this.$router.push({ path: '/assessment-evaluation/question-bank-manage/add-modify-question/' + row.id })
    },
    addQuestionHandler () {
      this.$router.push({ path: '/assessment-evaluation/question-bank-manage/add-modify-question' })
      // this.$router.push({ path: '/assessment-evaluation/online-test' })
    },
    // 列表选中
    handleSelectionChange (e) {
      this.tableSelectionsList = e
    },
    /*
      分页变化
    */
    pagingChange (event) {
      if ((typeof event.currentPage !== 'number') && (typeof event.pageSize !== 'number')) return

      this.page_info = { ...this.page_info, ...event }

      this.pagingFindList()
    },
    /*
     初始化分页信息
    */
    initPageInfo () {
      this.page_info = { currentPage: 1, pageSize: this.page_info.pageSize, total: 0 }
    },
    /*
      分页获取列表
    */
    pagingFindList (e) {
      if (e instanceof PointerEvent) {
        this.initPageInfo()
      }
      let classifyId = this.current_classify_id
      if (classifyId === 'system') classifyId = null
      this.questions_list_loading = true
      pagingFindQuestionsApi({ ...this.page_info, classifyId, ...this.form }).then(res => {
        const { currentPage, pageSize, total } = res.data
        this.table_data = res.data.data
        // eslint-disable-next-line eqeqeq
        if (this.table_data.length === 0 && this.page_info.currentPage != 1) {
          this.initPageInfo()
          this.pagingFindList()
        }
        this.page_info = { currentPage, pageSize, total }
      }).finally(_ => {
        this.questions_list_loading = false
      })
    },
    /*
      获取所有筛选条件选项（包含试题类型和难易程度）
    */
    async findAllQueryParams () {
      const { data } = await getAllQueryParamsOptionsApi()

      this.paramsOptions = data
    },
    /*
      获取所有试题分类
    */
    async findAllQuestionsClassify () {
      const { data } = await findAllQuestionsClassifyApi()
      const list = [
        { id: 'system', name: '试题分类', disabled: true, children: [] }
      ]
      this.classify_default = data
      this.questionClassifyMap = {}
      this.questionClassifyMap = data.toTree()

      list[0].children = this.questionClassifyMap.tree
      this.question_classify_list = list
    },

    async change (classify) {
      this.current_classify_id = classify.id
      this.pagingFindList()
    },
    /*
      创建分类
    */
    toCreateClassify (node) {
      node?.id === 'system' && (node = null)
      this.$prompt('请输入分类名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(async ({ value }) => {
        const data = {
          name: value,
          pid: node == null ? 0 : node.id,
          level: node == null ? 1 : node.level + 1
        }
        await createQuestionsClassifyApi(data)
        this.findAllQuestionsClassify()
      }).catch(_ => { })
      // this.$refs.treeMenuRef.setCurrentKey(node)
      // this.active_classify = { name: '', desc: '', base: null, features: [] }
    },
    // 批量删除、单个删除
    deleteQuestions (e, questionItem) {
      if (this.tableSelectionsList.length === 0 && (questionItem == null)) {
        this.$message.error('请先选择要删除的项目')
      } else {
        let delList = this.tableSelectionsList
        if (questionItem) {
          delList = [questionItem]
        }
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // eslint-disable-next-line prefer-promise-reject-errors
        }).then(res => {
          this.questions_list_loading = true
          deleteSomeQuestionsApi(delList.map(_ => _.id)).then(res => {
            this.pagingFindList()
            this.questions_list_loading = false
          })
        })
      }
    },
    /*
    删除分类
     */
    toDeleteclassify (classify) {
      if (classify.id === 'system') return
      new Promise((resolve, reject) => {
        this.$confirm('此操作将永久删除此分类，及其子级分类，请确认后删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // eslint-disable-next-line prefer-promise-reject-errors
        }).then(res => resolve()).catch(_ => reject())
      }).then(_ => {
        this.classify_loading = true
        deleteQuestionsClassifyApi(classify.id).finally(() => {
          this.findAllQuestionsClassify()
          this.$refs.treeMenuRef.setCurrentKey()
          this.classify_loading = false
        })
      }).catch(_ => { })
    }

  }
}
</script>

<style lang="scss" >
.classify_page .form_layout {
  margin-top: 16px;

  .suf {
    line-height: 1 !important;
  }

  .el-form-item:last-child {
    float: right;
  }
}
</style>
