<template>
  <div>
    <el-card>
      <mx-condition :local-data="extraData" :query-params="queryParams" :require-fields="requireFields"
                    @query="handleQuery" use-alias-mapping></mx-condition>
    </el-card>
    <el-container>
      <left-tree-side>
        <span slot="title">{{ !isKnowledgeBranch ? '章节目录' : '知识点目录' }}</span>
        <el-tree ref="branchTree" highlight-current :expand-on-click-node="false" :data="branchTree"
                 :props="treeProps" node-key="id" @node-click="handleTreeNodeClick"></el-tree>
      </left-tree-side>
      <!-- 手动组卷 -->
      <el-main style="background: #fff">
        <div class="knowPoints">
          <div class="tit">
            <span>已选知识点（{{ tags.length }}）</span>
            <div class="clear">
              <img src="@/assets/images/icon_qingkong.png" alt=""/>
              <span>清空</span>
            </div>
          </div>
          <el-divider class="generating_divider"></el-divider>
          <!--  tags -->
          <div class="tags">
            <el-tag v-for="tag in tags" :key="tag.id" closable style="margin-right: 24px; margin-bottom: 24px"
                    @close="handleClose(tag)">
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
        <div class="que">
          <div class="tit">
            <span>题型/题量</span>
            <div class="clear">
              <img src="@/assets/images/icon_qingkong.png" alt=""/>
              <span>清空</span>
            </div>
          </div>
          <el-divider></el-divider>
          <!-- 计数器 -->
          <div class="computer">
            <div class="computer_item" v-for="(item, index) in queCount" :key="index">
              <div class="fx-column">
                <div class="fx-row fx-sta-cen mb5">
                  <span class="f14 f-333">{{ item.name }}</span>
                  <span class="f12 f-999">(可选{{ item.num }}道)</span>
                </div>
                <el-input-number controls-position="right" v-model="item.count" :min="0" :max="item.num"></el-input-number>
              </div>
            </div>
          </div>
        </div>
        <!-- 生成试卷 -->
        <div style="
            display: flex;
            justify-content: center;
            margin-top: 90px;
            margin-bottom: 90px;
          ">
          <span class="generateExam" @click="createdPaper">生成试卷</span>
        </div>
      </el-main>
    </el-container>
    <correct-question-dialog ref="correct"></correct-question-dialog>
  </div>
</template>

<script>

import PaperByHand from '@/views/questioncenter/components/generate-tabs/paper-by-hand'
import {
  countByChapter,
  countByKnowledge,
  getQuestionsByQTypeAndNum,
  knowByChapter,
  listBottoms
} from '@/api/webApi/webQue'

export default {
  extends: PaperByHand,
  name: 'paper-by-intelligent',
  data() {
    return {
      // override
      extendCollection: false,
      mathId: 'question_by_intelligent',
      enableBox: false,
      ignoreQType: true,
      // new
      tags: [],
      queCount: [],
      knowledgeIds: [],
      listBottoms: []
    }
  },
  methods: {
    loadQuestionCard() {
      // override do-nothing
    },
    queryQuestions() {
      // override core query
      if (this.isKnowledgeBranch) {
        this.getListBottoms()
      } else {
        this.getKnowByChapter()
      }
    },
    getKnowByChapter() {
      // 根据章节查找知识点
      if (!this.currentNode.chapterId) return // 可能是切换的中间状态
      knowByChapter({
        ...this.queryOutput,
        ...this.currentNode
      }).then((res) => {
        this.knowledgeIds = res.data.map(item => item.id)
        this.tags = res.data
        this.getCountByChapter()
      })
    },
    getListBottoms() {
      // 根据章节获取底层知识
      if (!this.currentNode.knowledgeId) return // 可能是切换的中间状态
      listBottoms({
        ...this.queryOutput,
        ...this.currentNode
      }).then((res) => {
        this.listBottoms = res.data.map(item => item.id)
        this.tags = res.data
        this.getCountByKnowledge()
      })
    },
    getCountByChapter() {
      // 根据章节获取题库类型和数量
      countByChapter({
        ...this.queryOutput,
        ...this.currentNode,
        knowledgeIds: this.knowledgeIds.toString()
      }).then((res) => {
        this.queCount = res.data
      })
    },
    getCountByKnowledge() {
      // 根据知识点获取题库类型和数量
      countByKnowledge({
        ...this.queryOutput,
        ...this.currentNode,
        knowledgeIds: this.listBottoms.toString()
      }).then((res) => {
        this.queCount = res.data
      })
    },
    handleClose(tag) {
      if (this.tags.length <= 1) {
        this.msgError('至少查询1个')
      }
      this.tags.remove(tag)
      if (this.isKnowledgeBranch) {
        this.listBottoms.remove(tag.id)
        this.getCountByKnowledge()
      } else {
        this.knowledgeIds.remove(tag.id)
        this.getCountByChapter()
      }
    },
    createdPaper() {
      let queCount = this.queCount
      let req = []
      let allQue = 0
      // TODO: hht 22.10.08 这里的参数构成逻辑还没有完全看明白，但目前没有报错，先保持原样
      queCount.forEach((item) => {
        if (item.count > 0) {
          allQue = allQue + item.count
          req.push({
            subjectid: this.queryOutput.subjectId,
            qtpye: item.name,
            diff: 1,
            number: item.count,
            chapterid: this.currentNode.chapterId,
            gradeid: this.queryOutput.gradeId,
            editionid: this.queryOutput.editionId,
            knowledgeIds: this.knowledgeIds
          })
        }
      })
      if (allQue > 100) {
        this.msgError('选题上限是100题哦')
        return
      } else if (allQue == 0) {
        this.msgError('你还未选择题目')
        return
      }
      getQuestionsByQTypeAndNum(req).then((res) => {
        localStorage.setItem(
          'paperData',
          JSON.stringify({
            paperTitle: null,
            subjectId: this.queryOutput.subjectId
          })
        )
        localStorage.setItem('questionList', JSON.stringify(res.data))
        this.$router.push({
          path: '/question-center/generatingPaperCenter/paper',
          query: this.extraData
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
