<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="培训部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" style="width: 220px;" :options="deptOptions" :show-count="true" placeholder="请选择培训部门" />
      </el-form-item>
      <el-form-item label="主讲人" prop="courseName">
        <el-input
          v-model="queryParams.zhujiang"
          placeholder="请输入主讲人"
          clearable
          size="small"
        />
      </el-form-item>
      <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="courseName">
        <el-input
          v-model="queryParams.courseName"
          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="lessonsList">
      <el-table-column label="培训部门" align="center" prop="deptName" width="120"/>
      <el-table-column label="课程标题" align="center" prop="courseName" />
      <el-table-column label="主讲人" align="center" prop="zhujiang" width="100"/>
      <!-- <el-table-column label="课程类别" align="center" prop="planName">
        <template v-slot="scope">
          <div>
            {{
              courseOptions.filter(
                (item) => item.planId == scope.row.courseType
              )[0].planName
            }}
          </div>
        </template>
      </el-table-column> -->
      <el-table-column label="培训计划" align="center" prop="courseType">
        <template v-slot="scope">
          <div>
            {{
              scope.row.courseType &&
              courseOptions.filter(
                (item) => item.planId == scope.row.courseType
              )[0] &&
              courseOptions.filter(
                (item) => item.planId == scope.row.courseType
              )[0].planName
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="课程状态" align="center" prop="status" width="100">
        <template v-slot="scope">
          <div>{{ ["未发布", "已发布"][scope.row.status] }}</div>
        </template>
      </el-table-column>
      <el-table-column label="附件" align="center" prop="enclosure" width="100">
        <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"-->
      <!--&gt;下载视频</a-->
      <!--&gt;-->
      <!--</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: { topicNum, courseId, status } }">
          <span>
            <span
              class="timuNum"
              @click="checkQuestion(courseId, status)"
              v-if="topicNum > 0"
            >
              {{ status == 0 ? `已录入${topicNum}题` : "查看" }}
            </span>
            <span v-else-if="status === 1 && topicNum == 0"> - </span>
            <span
              class="timuNum"
              @click="checkQuestion(courseId, status)"
              v-else
              >未录入</span
            >
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template
          v-slot="{ row: { courseName, courseType, status, courseId } }"
        >
          <!-- <div>{{status}}</div> -->
          <el-button
            v-if="status == 0"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="changeLesson(courseId)"
            >修改</el-button
          >
          <el-button
            v-if="status == 1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="checkLesson(courseId)"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deletLesson(courseId)"
            >删除</el-button
          >
          <el-button
            v-if="status == 0"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="issueDilog(courseId, courseName, courseType)"
            >发布</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"
      :courseId.sync="courseId"
      :checkLock.sync="checkLock"
      :visible.sync="dilogFlag"
    />
    <el-dialog
      class="lessons-program"
      title="培训考试发布详情"
      :visible.sync="issueVisible"
      width="60%"
    >
      <span class="dialogName"
        >培训名称: <span class="a">{{ dilogName }}</span>
      </span>
      <span class="dialogName"
        >培训计划: <span class="a">{{ dilogType }}</span></span
      >
      <div class="detail flex">
        <div class="detail-item">
          单选题<span>{{ bottomFrom.singleChoiceScore }}</span
          >分/题,共<span>{{ danxs }}</span
          >题，计<span class="textC">{{
            danxs * bottomFrom.singleChoiceScore
          }}</span
          >分
        </div>
        <div class="detail-item">
          多选题<span>{{ bottomFrom.multipleChoiceScore }}</span
          >分/题,共<span>{{ duoxs }}</span> 题，计<span class="textC">{{
            duoxs * bottomFrom.multipleChoiceScore
          }}</span
          >分
        </div>

        <div class="detail-item">
          判断题<span>{{ bottomFrom.judgmentScore }}</span
          >/题,共<span>{{ pds }}</span> 题，计<span class="textC">{{
            pds * bottomFrom.judgmentScore
          }}</span
          >分
        </div>
      </div>

      <div class="detail">
        <div class="detail-item">
          共<span>{{ danxs + duoxs + pds }}</span
          >道题，总共计<span class="textC">{{
            danxs * bottomFrom.singleChoiceScore +
            duoxs * bottomFrom.multipleChoiceScore +
            pds * bottomFrom.judgmentScore
          }}</span
          >分
        </div>
      </div>
      <div class="detail">
        <div class="detail-item">
          合格分数为<span class="textC">{{ bottomFrom.qualifiedNum }}</span
          >分
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="issueVisible = false">取 消</el-button>
        <el-button type="primary" @click="issueLesson(issueCourseId)"
          >确认发布</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getQuestion,
  getLessons,
  getLessonById,
  issue,
  deleteLesson,
} from "@/api/train/lessonsProgram.js";

// 获取培训计划
import { getPlanList } from "@/api/train/trainingProgram";
import { mapGetters, mapMutations } from "vuex";
import { treeselect } from "@/api/system/dept";
import Dia from "./components/Dia";
import Treeselect from "@riophae/vue-treeselect";

export default {
  name: "Book",
  components: {
    Dia,
    Treeselect
  },
  data() {
    return {
      // 遮罩层
      loading: false,
      // 总条数
      total: 0,
      // courseOptions: [],
      lessonsList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseType: null,
        courseName: null,
        releaseTime: "",
      },

      // 表单参数
      form: {},
      // 表单校验
      dilogFlag: false,
      // 发布弹框
      issueVisible: false,
      dilogName: "",
      dilogType: null,
      bottomFrom: {
        singleChoiceScore: 0,
        multipleChoiceScore: 0,
        judgmentScore: 0,
        qualifiedNum: 0,
      },
      issueCourseId: null,
      questionList: [],
      componentsNum: 1,
      // 点击的id，如果是新增为空
      courseId: null,
      // false为编辑，true为查看，查看不允许编辑的时候
      checkLock: false,
      // 部门树选项
      deptOptions: [],
    };
  },
  computed: {
    ...mapGetters(["courseOptions"]),
    danxs() {
      return this.questionList.filter((item) => item.topicType === 1).length || 0;
    },
    duoxs() {
      return this.questionList.filter((item) => item.topicType === 2).length || 0;
    },
    pds() {
      return this.questionList.filter((item) => item.topicType === 3).length || 0;
    },
  },
  created() {
    this.getPlanList();
    this.getList();
    this.getTreeselect();
  },

  methods: {
    ...mapMutations({ setOptions: "SET_COURSE_OPTIONS" }),
    // 获取课程类别，也就是计划名称
    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);
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        console.log('部门树返回值')
        this.deptOptions = response.data;
      });
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      getLessons(this.queryParams)
        .then((res) => {
          console.log(res);
          this.lessonsList = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    search() {
      // console.log(this.queryParams);
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.checkLock = false;
      this.$refs.Dia.title = "新增培训课程";
      this.componentsNum = 1;
      this.courseId = null;
      this.dilogFlag = true;
    },

    changeLesson(courseId) {
      this.checkLock = false;
      this.$refs.Dia.title = "修改培训课程";
      this.componentsNum = 1;
      this.courseId = courseId;
      this.dilogFlag = true;
    },
    checkLesson(courseId) {
      this.checkLock = true;
      this.$refs.Dia.title = "查看培训课程";
      this.componentsNum = 1;
      this.courseId = courseId;
      this.dilogFlag = true;
    },

    // 直接查看考题
    checkQuestion(courseId, status) {
      // 要查看考题的id
      if (status == 1) {
        this.checkLock = true;
      }
      this.courseId = courseId;
      console.log(this.courseId);
      // 2代表列表组件
      this.componentsNum = 2;
      this.dilogFlag = true;
    },
    // 重置
    resetClick() {
      this.reset();
      this.getList();
    },
    // 复位
    reset() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        courseType: null,
        courseName: null,
        releaseTime: "",
      };
    },
    deletLesson(courseId) {
      this.$confirm("请确定删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return deleteLesson(courseId);
        })
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
          }
          this.getList();
        })
        .catch(() => {});
    },
    // 发布弹框
    issueDilog(courseId, name, type) {
      getQuestion({ courseId })
        .then((res) => {
          this.questionList = res.rows.map((item) => {
            return {
              topicType: item.topicType,
              topicId: item.topicId,
              topicTitle: item.topicTitle,
            };
          });
        })
        .then((res) => {
          return getLessonById(courseId);
        })
        .then((res) => {
          this.bottomFrom = {
            singleChoiceScore: res.data.singleChoiceScore || 0,
            multipleChoiceScore: res.data.multipleChoiceScore || 0,
            judgmentScore: res.data.judgmentScore || 0,
            qualifiedNum: res.data.qualifiedNum || 0,
          };
        })
        .then((res) => {
          this.dilogName = name;
          this.dilogType =
            type &&
            this.courseOptions.filter((item) => item.planId == type)[0] &&
            this.courseOptions.filter((item) => item.planId == type)[0]
              .planName;
          this.issueVisible = true;
          this.issueCourseId = courseId;
        });

      //
    },
    // 发布
    issueLesson(courseId) {
      // this.$confirm("确定要发布吗", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then(() => {
      //     // 判断是否录入答题合格数
      //     return getLessonById(courseId);
      //   })
      getLessonById(courseId)
        .then((res) => {
          // if (
          //   res.data.singleChoiceScore >= 0 &&
          //   res.data.multipleChoiceScore >= 0 &&
          //   res.data.judgmentScore >= 0 &&
          //   res.data.qualifiedNum >= 0
          // ) {
          return true;
          // }
        })
        .then((res) => {
          if (res) {
            // 成功就发布
            return issue({ courseId });
          } else {
            this.$message({
              message: "请先在题目列表录入题目分数跟合格分数",
              type: "warning",
            });
          }
        })
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "发布成功",
              type: "success",
            });
            this.getList();
            this.issueVisible = false;
          }
        })
        .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: 10vh !important;
}
::v-deep .el-dialog .el-dialog__body {
  padding-top: 5px;
}
.dialogName {
  margin-right: 50px;
  // color: #ccc;
  font-size: 16px;
}
.detail {
  // position: absolute;
  // bottom: -20px;
  // left: 10px;
  margin-top: 20px;
  .textC {
    font-weight: 800;
    font-size: 18px;
  }
  .detail-item {
    margin-right: 20px;
    color: red;
  }
}
</style>
