<!-- eslint-disable vue/no-deprecated-v-bind-sync -->
<template>
  <div class="v-page classify_page">
    <SearchTreeMenu
      ref="treeMenuRef"
      title="试卷分类列表"
      :tree-data="paper_classify_list"
      @current-change="change"
      @onCreate="toCreateClassify"
      @onDelete="toDeleteclassify"
      v-loading="classify_loading"
      @onEdit="toEditClassify"
    />
    <div class="v-ctx" v-loading="paper_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:btns>
          <el-button type="danger" @click="deletePapers" round
          >删除选中</el-button
          >
          <!-- <el-button type="primary"  round @click="$message('开发中')">批量下载</el-button> -->
          <el-button type="primary" round plain @click="batchMoveToClassify"
            >移动到分类</el-button
          >
          <el-button type="primary" @click="addPaperHandler" 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="i-j-ksap-bianji2"
            @click="editPaper(props.row)"
            v-if="
              props.row.share === 1 ||
              $store.user.baseRole === 1 ||
              $store.user.id === props.row.creatorId
            "
            >编辑</el-button
          >
          <el-button
            type="text"
            icon="i-j-ksap-fuzhi"
            @click="copyPaper(props.row)"
            >复制</el-button
          >

          <el-button
            type="text"
            icon="i-j-fbks-yulan"
            @click="previewPaper(props.row)"
            >预览</el-button
          >
          <el-button
            type="text"
            icon="el-icon-printer"
            class="print-icon"
            @click="
              $router.push(
                '/print-paper/' + props.row.id
              )
            "
            >打印</el-button
          >
          <!-- <el-button  type="text" icon="el-icon-download" >下载</el-button> -->
          <el-button
            type="text"
            icon="i-j-ksap-shanchu"
            @click="deletePapers($event, props.row)"
            style="color: #f04343 !important"
            v-if="
              props.row.share === 1 ||
              $store.user.baseRole === 1 ||
              $store.user.id === props.row.creatorId
            "
            >删除</el-button
          >
        </template>
        <template v-slot:isOpen="props">
          <el-switch
            v-model="props.row.status"
            :active-value="1"
            :inactive-value="0"
            style="margin-left: 10px"
            @change="changeItemStatus($event, props.row)"
          >
          </el-switch>
        </template>
      </TableLayout>
    </div>
    <DialogLayout
      title="选择分类"
      width="280px"
      :visible="select_classify_dialog_is_show"
      @onCancel="
        (_) => {
          current_selected_classify_id = null;
          select_classify_dialog_is_show = false;
        }
      "
      @onConfirm="onMoveConfirm"
    >
      <PaperClassifySelector
        v-model="current_selected_classify_id"
        :mountedLoad="true"
      ></PaperClassifySelector>
    </DialogLayout>
    <DialogLayout
      title="预览"
      width="600px"
      :visible="preview_paper_dialog_show"
      @onCancel="preview_paper_dialog_show = false"
      :actionBarOption="{ confirmTxt: '打印' }"
      @onConfirm="printx"
    >
      <ExercisePerviewPaper
        :questions="preview_current_questions_list"
        :title="current_select_paper?.title"
        :mode="2"
        ref="printRef"
      ></ExercisePerviewPaper>
    </DialogLayout>
  </div>
</template>

<script>
import {
  SearchTreeMenu,
  TableLayout,
  FormLayout,
  DialogLayout
} from '@/components/layout'

import {
  findAllPaperClassifyApi,
  createPaperClassifyApi,
  deletePaperClassifyApi,
  pagingFindPaperApi,
  deleteSomePapersApi,
  patchPaperApi,
  copyPaperInfoByIdApi,
  batchMovePaperClassify,
  editPaperClassifyApi,
  checkQuoteApi
} from '@/api/assessment-evaluation/paper'
import { getQuestionsByPaperApi } from '@/api/assessment-evaluation/exam'
import QueryInput from '@/components/widget/QueryInput.vue'
import PaperClassifySelector from './add-modify-paper/components/PaperClassifySelector.vue'
// import QuestionListPreview from '@/views/assessment-evaluation/examination-paper-manage/add-modify-paper/components/QuestionListPreview.vue'
import ExercisePerviewPaper from '@/views/statistic/components/ExercisePerviewPaper.vue'
export default {
  components: {
    SearchTreeMenu,
    TableLayout,
    FormLayout,
    QueryInput,
    DialogLayout,
    PaperClassifySelector,
    ExercisePerviewPaper
  },
  data: () => ({
    paper_classify_list: [],
    table_data: [],
    page_info: { currentPage: 1, pageSize: 10, total: 0 },
    current_classify_id: null,
    // 试题分类树是否加载中
    classify_loading: false,
    paper_list_loading: false,
    form: { title: '' },
    // 表格当前选中项
    table_selections_list: [],
    current_selected_classify_id: null,
    select_classify_dialog_is_show: false,
    preview_current_questions_list: [],
    // 预览弹窗是否显示
    preview_paper_dialog_show: false,
    // 当前选中的试卷
    current_select_paper: null
  }),

  created () {
    this.formItems = [
      { prop: 'title' },
      { prop: 'btns', model: { class: 'gy-btns' } }
    ]
    this.rules = {
      // name: { required: true, message: '请输入角色名称', trigger: 'blur' }
    }
    this.column = [
      {
        prop: 'title',
        label: '试卷名',
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'classify',
        label: '试卷分类',
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'totalScore',
        label: '总分',
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'questionCount',
        label: '试题总数',
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'creator',
        label: '创建人',
        align: 'center',
        'show-overflow-tooltip': true
      },
      {
        prop: 'createTime',
        label: '创建时间',
        width: 150,
        align: 'center',
        'show-overflow-tooltip': true
      },
      { prop: 'action', label: '操作', width: 290, align: 'center' },
      {
        prop: 'isOpen',
        label: '是否开启',
        width: 80,
        align: 'center',
        'show-overflow-tooltip': true
      }
    ]

    this.findAllQuestionsClassify()
  },
  activated () {
    this.pagingFindList()
  },
  methods: {
    /**
     * 调用打印,可导出pdf
     */
    printx () {
      if (window.printElement) {
        window.printElement.remove()
      }
      window.printElement = document.createElement('iframe')
      window.printElement.style = 'display:none;'
      window.printElement.onload = () => {
        const printBody = window.printElement.contentWindow.document.body
        printBody.appendChild(document.head.cloneNode(1))
        printBody.style = '-webkit-print-color-adjust:exact;background:#fff;'
        printBody.appendChild(this.$refs.printRef.$el.cloneNode(1))
        window.printElement.contentWindow.print()
      }
      document.body.appendChild(window.printElement)
    },
    /**
     * 预览试卷,获取试题和试卷相关信息
     */
    previewPaper (row) {
      this.current_select_paper = row
      this.page_is_loading = true
      getQuestionsByPaperApi(row.id)
        .then((res) => {
          this.preview_current_questions_list = res.data
          this.preview_paper_dialog_show = true
        })
        .finally((_) => {
          this.page_is_loading = false
        })
    },
    /**
     * 修改分类
     */
    toEditClassify (item) {
      if (item.id === 'system') return this.$message.error('根分类不能修改')
      this.$prompt('请输入新分类名：', '编辑', {
        inputPattern: /.{1,}/,
        inputErrorMessage: '请输入分类名'
      })
        .then(({ value }) => {
          this.classify_loading = true
          editPaperClassifyApi({ ...item, name: value })
            .then((res) => {
              this.$message.success('修改成功')
              this.findAllQuestionsClassify()
            })
            .finally((_) => {
              this.classify_loading = false
            })
        })
        .catch(() => {})
    },
    /**
     * 确定移动到分类
     */
    onMoveConfirm () {
      const ids = this.table_selections_list.map((item) => item.id)
      const classifyId = this.current_selected_classify_id
      this.paper_list_loading = true
      batchMovePaperClassify({ ids, classifyId })
        .then((res) => {
          this.pagingFindList()
          this.select_classify_dialog_is_show = false
        })
        .finally((_) => {
          this.paper_list_loading = false
        })
    },
    /**
     * 批量移动到分类
     */
    batchMoveToClassify () {
      if (this.table_selections_list.length === 0) {
        return this.$message.error('请先选择要移动的试卷')
      }
      this.select_classify_dialog_is_show = true
    },
    /**
     * 复制试卷
     */
    copyPaper (row) {
      this.$prompt(`复制试卷【${row.title}】并重命名为：`, '重命名', {
        inputPattern: /.{1,}/,
        inputErrorMessage: '请填写新试卷名'
      })
        .then(({ value }) => {
          this.paper_list_loading = true
          copyPaperInfoByIdApi({ id: row.id, title: value })
            .then((res) => {
              this.pagingFindList()
            })
            .finally((_) => {
              this.paper_list_loading = false
            })
        })
        .catch((_) => {})
    },
    /**
     * 修改试卷是否开启
     */
    changeItemStatus (status, paperItem) {
      const form = {
        id: paperItem.id,
        status
      }
      patchPaperApi(form).then((res) => {
        if (res.code !== 0) {
          paperItem.status = status === 1 ? 0 : 1
          this.$message.error('修改失败')
        }
      })
    },
    /**
     * 编辑试卷
     */
    async editPaper (row) {
      const { data } = await checkQuoteApi(row.id)
      if (data.length > 0) {
        const text = data.map((item) => item.title)
        this.$confirm(
          `当前试卷有考试（${text.join('，')}）已经引用, 您确定要修改内容吗?`,
          '警告',
          { type: 'warning' }
        )
          .then((_) => {
            this.$router.push({
              path:
                '/assessment-evaluation/examination-paper-manage/add-modify-paper/' +
                row.id
            })
          })
          .catch((_) => {})
      } else {
        this.$router.push({
          path:
            '/assessment-evaluation/examination-paper-manage/add-modify-paper/' +
            row.id
        })
      }
    },
    /**
     * 点击添加试卷的回调
     */
    addPaperHandler () {
      this.$router.push({
        path: '/assessment-evaluation/examination-paper-manage/add-modify-paper'
      })
    },
    handleSelectionChange (e) {
      this.table_selections_list = 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.paper_list_loading = true
      pagingFindPaperApi({ ...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.paper_list_loading = false
        })
    },
    async findAllQuestionsClassify () {
      const { data } = await findAllPaperClassifyApi()
      const list = [
        { id: 'system', name: '试卷分类', disabled: true, children: [] }
      ]
      this.questionClassifyMap = {}
      this.questionClassifyMap = data.toTree()

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

    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 createPaperClassifyApi(data)
          this.findAllQuestionsClassify()
        })
        .catch((_) => {})
      // this.$refs.treeMenuRef.setCurrentKey(node)
      // this.active_classify = { name: '', desc: '', base: null, features: [] }
    },
    // 批量删除、单个删除
    deletePapers (e, questionItem) {
      if (this.table_selections_list.length === 0 && questionItem == null) {
        this.$message.error('请先选择要删除的项目')
      } else {
        let delList = this.table_selections_list
        if (questionItem) {
          delList = [questionItem]
        }
        this.$confirm('确认删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // eslint-disable-next-line prefer-promise-reject-errors
        })
          .then((res) => {
            this.paper_list_loading = true
            deleteSomePapersApi(delList.map((_) => _.id)).then((res) => {
              this.pagingFindList()
              this.paper_list_loading = false
            })
          })
          .catch((_) => {})
      }
    },
    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
          deletePaperClassifyApi(classify.id).finally(() => {
            this.findAllQuestionsClassify()
            this.$refs.treeMenuRef.setCurrentKey()
            this.classify_loading = false
          })
        })
        .catch((_) => {})
    }
  }
}
</script>

<style lang="scss" >
.print-icon span {
  margin: 0 !important;
}
.classify_page .form_layout {
  margin-top: 16px;

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

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