<!-- 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" @onEdit="toEditClassify"
      @onCreate="toCreateClassify" @onDelete="toDeleteclassify" v-loading="classify_loading" />
    <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" @click="addPaperHandler" round >发布考试</el-button>
        <!-- icon="el-icon-s-promotion" -->
      </template>
      </FormLayout>
      <!-- class="gy-el-table" -->
      <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:examStartTime="props">
          <div>
            <p>开始时间：{{props.row.examStartTime}}</p>
            <p>结束时间：{{props.row.examEndTime}}</p>
          </div>
        </template>
        <template v-slot:passPercent="props">
            <p>{{Math.round(props.row.passPercent * props.row.totalScore /100)}}</p>
        </template>
        <template v-slot:status="props">
          <div :style="{'background-color':['#208ac6','#01c883','#999999'][props.row.status]}" class="exam-status">
            {{['待开考','考试中','已结束'][props.row.status]}}
          </div>
        </template>
        <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" :disabled="props.row.status==1" @click="editExam(props.row)" v-if="props.row.status==0">编辑</el-button>
          <el-button  type="text" icon="i-j-ksap-fuzhi" :disabled="props.row.status==1"  @click="editExam(props.row,'copy')" v-if="props.row.status==0">复制</el-button>
          <el-button  type="text" icon="i-j-ksap-fuzhi" :disabled="props.row.status==1"  @click="editExam(props.row,'again')" v-if="props.row.status==2">复制再考</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">删除</el-button>
        </template>
      </TableLayout>
    </div>

  </div>
</template>

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

import { findAllExamClassifyApi, createExamClassifyApi, deleteExamClassifyApi, editExamClassifyApi, pagingExamListApi, batchDeleteExamApi } from '@/api/assessment-evaluation/exam'
import QueryInput from '@/components/widget/QueryInput.vue'
export default {
  components: {
    SearchTreeMenu, TableLayout, FormLayout, QueryInput
  },

  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: '' },
    // 表格当前选中项
    tableSelectionsList: []

  }),

  created () {
    this.formItems = [
      { prop: 'title' },
      { prop: 'btns', model: { class: 'gy-btns' } }
    ]
    this.rules = {
      // name: { required: true, message: '请输入角色名称', trigger: 'blur' }
    }
    this.column = [
      { prop: 'title', label: '考试名称', 'min-width': 130, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'classify', label: '考试分类', 'min-width': 130, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'totalScore', label: '总分', width: 80, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'passPercent', label: '及格分', width: 80, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'creator', label: '创建人', align: 'center', 'show-overflow-tooltip': true },
      { prop: 'examStartTime', label: '考试时间', width: 250, align: 'center', 'show-overflow-tooltip': true },
      { prop: 'status', label: '状态', width: 80, align: 'center', 'show-overflow-tooltip': true },
      {
        prop: 'action',
        label: '操作',
        //  width: 350,
        width: 250,
        align: 'center',
        'show-overflow-tooltip': true
      }
    ]

    this.findAllQuestionsClassify()
  },
  activated () {
    this.pagingFindList()
  },
  methods: {
    /**
     * 修改考试分类点击回调
     */
    toEditClassify (item) {
      if (item.id === 'system') return this.$message.error('根分类不能修改')
      this.$prompt('请输入新分类名：', '编辑', {
        inputPattern: /.{1,}/,
        inputErrorMessage: '请输入分类名'
      }).then(({ value }) => {
        this.classify_loading = true
        editExamClassifyApi({ ...item, name: value }).then(res => { this.$message.success('修改成功'); this.findAllQuestionsClassify() }).finally(_ => {
          this.classify_loading = false
        })
      }).catch(() => {})
    },
    /**
     * 编辑考试
     */
    editExam (row, type) {
      let path = '/assessment-evaluation/exam-arrangement/add-modify-exam/' + row.id
      if (type) {
        path += '/' + type
      }
      this.$router.push({ path })
    },
    /**
     * 新建考试
     */
    addPaperHandler () {
      this.$router.push({ path: '/assessment-evaluation/exam-arrangement/add-modify-exam' })
    },
    /**
     * 批量选中项
     */
    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.paper_list_loading = true
      pagingExamListApi({ ...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 findAllExamClassifyApi()
      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 createExamClassifyApi(data)
        this.findAllQuestionsClassify()
      }).catch(_ => { })
      // this.$refs.treeMenuRef.setCurrentKey(node)
      // this.active_classify = { name: '', desc: '', base: null, features: [] }
    },
    /**
     * 批量删除、单个删除
     */
    deletePapers (e, questionItem) {
      if (this.tableSelectionsList.length === 0 && (questionItem == null)) {
        this.$message.error('请先选择要删除的项目')
      } else {
        let delList = this.tableSelectionsList
        if (questionItem) {
          delList = [questionItem]
        }
        const hasStarted = delList.filter(item => +item.status !== 1)
        const tipsText = hasStarted.length !== delList.length ? '选中项中包含已开考的考试，确认删除吗？' : '确认删除吗?'
        this.$confirm(tipsText, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
          // eslint-disable-next-line prefer-promise-reject-errors
        }).then(res => {
          // if (hasStarted.length !== delList.length) {
          //   delList = hasStarted
          // }
          this.paper_list_loading = true
          batchDeleteExamApi(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
        deleteExamClassifyApi(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>
<style lang="scss"  scoped>

.exam-status {
  width: 60px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  background: #ccc;
  border-radius: 20px;
}
</style>
