<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"

    >
      <!-- <el-form-item label="课件类别" prop="courseType">
        <el-select
          v-model="queryParams.courseType"
          placeholder="请选择课程类型"
          clearable
          size="small"
        >
          <el-option
            v-for="course in courseOptions"
            :key="course.planId"
            :label="course.planName"
            :value="course.planId"
          />
        </el-select>
      </el-form-item> -->

       <el-form-item
          label="归属部门"
          prop="deptId"
          ref="treeItem"
        >
          <Treeselect
            class="tree"
            v-model="queryParams.deptId"
            :options="deptOptions"
            :show-count="true"
            placeholder="请选择归属部门"
            style="width:200px"
          />
        </el-form-item>
      <el-form-item label="题库名称" prop="courseName">
        <el-input
          v-model="queryParams.bankName"
          placeholder="题库名称"
          clearable
          size="small"
        />
      </el-form-item>
      <!-- <el-form-item label="发布时间" prop="releaseTime">
        <el-date-picker
          v-model="queryParams.releaseTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          placeholder="选择日期时间"
          default-time="12:00:00"
        >
        </el-date-picker>
      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="search"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetClick"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:book:add']"
          >新增</el-button
        >
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="bankList">
      <el-table-column label="序号" width='50' align="center" prop="bankNum"/>

      <el-table-column label="题库名称" align="center" prop="bankName">
      </el-table-column>
      <el-table-column
        label="归属部门"
        align="center"
        prop="courseType"
      >
        <template v-slot="scope">
          <div>
            {{ selectList(deptOptions, scope.row.deptId)||'-' }}
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="附件" align="center" prop="enclosure">
        <template v-slot="{ row: { enclosure } }">
          <a
            v-if="enclosure && enclosure.indexOf('.txt') >= 0"
            @click="downloadText(enclosure)"
            class="down-load"
            >下载附件</a
          >
          <a v-else :href="enclosure" class="down-load">下载附件</a>
        </template>
      </el-table-column> -->
      <!-- <el-table-column label="视频" align="center" prop="video">
        <template v-slot="{ row: { courseName, video } }">
          <a @click="downLoadVideo(video, courseName)" class="down-load"
            >下载视频</a
          >
        </template>
      </el-table-column>
      <el-table-column
        label="发布时间"
        align="center"
        prop="releaseTime"
        :formatter="formatter"
      /> -->
      <el-table-column
        label="考试题数量"
        align="center"
        prop="topicNum"
        width="180"
      >
        <template v-slot="{ row: { numberQuestions, bankId } }">
          <div @click="checkQuestion(bankId)" class="timuNum">
            <div v-if="numberQuestions > 0">{{ `已录入${numberQuestions}题` }}</div>
            <div v-else>未录入</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-slot="{ row: { bankId } }">
          <!-- <div>{{status}}</div> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="changeBank(bankId)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deletBank(bankId)"
            >删除</el-button
          >
          <!-- <el-button
            v-if="status == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="issueLesson(bankId)"
            >发布</el-button
          > -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <Dia
      ref="Dia"
      :componentsNum.sync="componentsNum"
      :bankId.sync="bankId"
      :visible.sync="dilogFlag"
    />

    <el-dialog> </el-dialog>
  </div>
</template>

<script>
// import {
//   getLessons,
//   getLessonById,
//   issue,
//   deleteLesson,
// } from "@/api/educationPlanExam/lessonsProgram.js";
import { listBank,delBank } from "@/api/educationPlanExam/questionBank";
// 部门列表
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
// 获取课程类型
// import { getPlanList } from "@/api/educationPlanExam/trainingProgram";
// import { mapGetters, mapMutations } from "vuex";

import Dia from "./components/Dia";

export default {
  name: "questionBank",
  components: {
    Dia,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // courseOptions: [],
      bankList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        // 所属部门
        deptId: null,
        // 题库名称
        bankName: null,
        releaseTime: "",
        numberQuestions:0
      },
      // 表单参数
      form: {},
      // 表单校验

      dilogFlag: false,
      componentsNum: 1,
      // 点击的id，如果是新增为空
      bankId: null,

      // 题库id
      deptId: null,
      // 归属部门列表
      deptOptions: [],
    };
  },
  computed: {
    // ...mapGetters(["courseOptions"]),
  },
  created() {
    // this.getPlanList();
    this.getTreeselect();
    this.getList();
  },

  methods: {
    // ...mapMutations({ setOptions: "SET_COURSE_OPTIONS" }),
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.deptOptions = response.data;
        // console.log("123", this.deptOptions);
        // console.log(this.selectList(this.deptOptions, 175));
      });
    },
    // 递归查值的方法
    selectList(list, id) {
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        if (item.id == id) {
          return item.label;
        } else {
          if (Array.isArray(item.children)) {
            let a = this.selectList(item.children, id);
            if (a) {
              return a;
            }
          }
        }
      }
    },
    // 获取课程类别，也就是计划名称
    // getPlanList() {
    //   getPlanList().then((res) => {
    //     const courseOptions = res.data.map((item) => {
    //       return {
    //         planId: item.planId,
    //         planName: item.planName,
    //       };
    //     });
    //     // this.$store.commit("SET_COURSE_OPTIONS");
    //     this.setOptions(courseOptions);
    //   });
    // },

    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listBank(this.queryParams)
        .then((res) => {
          console.log(res);
          this.bankList = res.rows.map((item, index) => {
            return {
              bankNum:
                index +
                1 +
                (this.queryParams.pageNum - 1) * this.queryParams.pageSize,
              ...item,
            };
          });
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    search() {
      // console.log(this.queryParams);
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$refs.Dia.title = "新增题库";
      this.componentsNum = 1;
      this.bankId = null;
      this.dilogFlag = true;
    },
    changeBank(bankId) {
      this.$refs.Dia.title = "修改题库";
      this.componentsNum = 1;
      this.bankId = bankId;
      this.dilogFlag = true;
    },

    // 直接查看考题
    checkQuestion(bankId) {
      // 要查看考题的id
      this.bankId = bankId;
      // 2代表列表组件
      this.componentsNum = 2;
      this.dilogFlag = true;
    },
    // 重置
    resetClick() {
      this.reset();
      this.getList();
    },
    // 复位
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        courseType: null,
        courseName: null,
        releaseTime: "",
      };
    },
    deletBank(bankId) {
      this.$confirm("请确定删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return delBank(bankId);
        })
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }
          this.getList();
        })
        .catch(() => {});
    },
    // 发布
    // issueLesson(bankId) {
    //   this.$confirm("请确定发布", {
    //     confirmButtonText: "确定",
    //     cancelButtonText: "取消",
    //     type: "warning",
    //   })
    //     .then(() => {
    //       // 判断是否录入答题合格数
    //       return getLessonById(bankId);
    //     })
    //     .then((res) => {
    //       if (res.data.qualifiedNum > 0) {
    //         return true;
    //       }
    //     })
    //     .then((res) => {
    //       if (res) {
    //         // 成功就发布
    //         return issue({ bankId });
    //       } else {
    //         this.$message({
    //           message: "请先录入答题合格数",
    //           type: "warning",
    //         });
    //       }
    //     })
    //     .then((res) => {
    //       if (res.code == 200) {
    //         this.$message({
    //           message: "发布成功",
    //           type: "success",
    //         });
    //         this.getList();
    //       }
    //     })
    //     .catch(() => {});
    // },
    formatter(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index);
      if (!cellValue) return "-";
      else return cellValue;
    },
    // downloadText(url) {
    //   // url = url.replace(/\\/g, "/");
    //   const xhr = new XMLHttpRequest();
    //   xhr.open("GET", url, true);
    //   xhr.responseType = "blob";
    //   //xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
    //   xhr.onload = function () {
    //     if (xhr.readyState === 4 && xhr.status === 200) {
    //       let blob = this.response;
    //       console.log(blob);
    //       // 转换一个blob链接
    //       // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串)，
    //       // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
    //       let downLoadUrl = window.URL.createObjectURL(
    //         new Blob([blob], {
    //           type: "txt",
    //         })
    //       );
    //       // 视频的type是video/mp4，图片是image/jpeg
    //       // 01.创建a标签
    //       let a = document.createElement("a");
    //       // 02.给a标签的属性download设定名称
    //       a.download = name;
    //       // 03.设置下载的文件名
    //       a.href = downLoadUrl;
    //       // 04.对a标签做一个隐藏处理
    //       a.style.display = "none";
    //       // 05.向文档中添加a标签
    //       document.body.appendChild(a);
    //       // 06.启动点击事件
    //       a.click();
    //       // 07.下载完毕删除此标签
    //       a.remove();
    //     }
    //   };

    //   xhr.send();
    // },
    // downLoadVideo(url, name) {
    //   var xhr = new XMLHttpRequest();
    //   xhr.open("GET", url, true);
    //   xhr.responseType = "arraybuffer"; // 返回类型blob
    //   xhr.onload = function () {
    //     if (xhr.readyState === 4 && xhr.status === 200) {
    //       let blob = this.response;
    //       console.log(blob);
    //       // 转换一个blob链接
    //       // 注: URL.createObjectURL() 静态方法会创建一个 DOMString(DOMString 是一个UTF-16字符串)，
    //       // 其中包含一个表示参数中给出的对象的URL。这个URL的生命周期和创建它的窗口中的document绑定
    //       let downLoadUrl = window.URL.createObjectURL(
    //         new Blob([blob], {
    //           type: "video/mp4",
    //         })
    //       );
    //       // 视频的type是video/mp4，图片是image/jpeg
    //       // 01.创建a标签
    //       let a = document.createElement("a");
    //       // 02.给a标签的属性download设定名称
    //       a.download = name;
    //       // 03.设置下载的文件名
    //       a.href = downLoadUrl;
    //       // 04.对a标签做一个隐藏处理
    //       a.style.display = "none";
    //       // 05.向文档中添加a标签
    //       document.body.appendChild(a);
    //       // 06.启动点击事件
    //       a.click();
    //       // 07.下载完毕删除此标签
    //       a.remove();
    //     }
    //   };
    //   xhr.send();
    // },
  },
};
</script>
<style lang="scss" scoped>
.down-load {
  color: #0bab0c;
}
.timuNum {
  color: #1d84ff;
  cursor: pointer;
}
::v-deep .el-select {
  width: 100%;
}
::v-deep .el-dialog {
  margin-top: 15vh !important;
}
</style>
