<!--学习资源-->
<template>
  <div class="app-container el-course hardware">
    <div class="list-max-big-box" v-if="pageType === 1">
      <div class="top-max-box">
        <div class="left-max-box scrollbar-box" v-hasPermiRouter="['exam:elCategory:list']">
          <div class="classify_btn" @click="goPageEdit(5,'')">管理分类 >></div>
          <el-tree
            :data="treeData"
            :props="defaultProps"
            :highlight-current="true"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            node-key="id"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
        <div class="center-max-box" v-hasPermiRouter="['exam:el_category:list']"></div>
        <div class="right-max-box">
          <el-form style="height:60px;" :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
            <el-form-item label="" prop="title" label-width="90px">
              <el-input
                v-model="queryParams.title"
                placeholder="请输入课程名称"
                size="small"
              />
            </el-form-item>
            <el-form-item label="" prop="title" style="float: right">
              <el-col :span="1.5">
                <p class="page-submit-common-style-button"
                   @click="goPageEdit(1)"
                   v-hasPermiRouter="['exam:elCourse:add']"
                >新增</p>
              </el-col>
            </el-form-item>
            <el-form-item >
              <p class="page-inquire-common-style-button" @click="handleQuery">查询</p>
              <p class="page-reset-common-style-button" @click="resetQuery">重置</p>
            </el-form-item>
          </el-form>
          <div class="min-list-box">
            <el-table class="table-box" v-loading="loading" border :data="el_courseList" :cell-style="cellStyle">
              <el-table-column label="课程名称" align="left" prop="title"  :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="goCourseDetails(scope.row)"
                             style="padding:0;height:23px;width:320px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;text-align: left;">{{scope.row.title}}</el-button>
                </template>
              </el-table-column>
              <el-table-column label="适用学院" align="left" prop="deptNames"  :show-overflow-tooltip="true" width="140"/>
              <el-table-column label="适用类型" align="left" prop="scopeType" :show-overflow-tooltip="true" width="140">
                <template slot-scope="scope">
                  <span v-for="(bigItem,bigIndex) in scope.row.scopeType" :key="bigIndex">
                    <span v-for="(item,index) in scopeTypes" :key="index" v-if="bigItem==item.type">{{bigIndex==0?item.value:'、'+item.value}}</span>
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="分类" align="left" prop="cateTitle" :show-overflow-tooltip="true" width="100"/>
              <el-table-column label="章节数" align="left" prop="chapters" width="80"/>
              <el-table-column label="有效时间" align="left" prop="createTime" width="120">
                <template slot-scope="scope">
                  {{scope.row.ceType==0?'永久':(scope.row.ceType==1?scope.row.ceTime:'')}}
                </template>
              </el-table-column>
              <el-table-column label="学习人数" align="left" prop="learns" width="100"/>
              <el-table-column label="访问人数" align="left" prop="accessNum" width="100"/>
              <el-table-column label="状态" align="left" prop="status" width="90">
                <template slot-scope="scope">
                  <el-switch
                    v-hasPermiRouter="['exam:elCourse:add','exam:elCourse:edit']"
                    class="switch"
                    @change="switchChange(scope.row)"
                    v-model="scope.row.status+''"
                    active-value=true
                    inactive-value=false
                    active-text="上架"
                    inactive-text="下架"
                  >
                  </el-switch>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="left" class-name="small-padding fixed-width" width="90">
                <template slot-scope="scope">
                  <div class="table-button-box">
                    <p class="table-button-null"></p>
                    <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)">
                      <p class="table-button-p">更多>></p>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="record">学习记录</el-dropdown-item>
                        <el-dropdown-item command="edit"   v-hasPermiRouter="['exam:elCourse:add','exam:elCourse:edit']">编辑</el-dropdown-item>
                        <el-dropdown-item command="delete" v-hasPermiRouter="['exam:elCourse:del']">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                    <p class="table-button-null"></p>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div class="bottom-max-box">
        <pagination :page-sizes="[20, 30, 40, 50]"
          v-show="total>0"
          :total="total"
          layout="total, prev, pager, next, sizes, jumper"
          :page.sync="queryParams.page"
          :limit.sync="queryParams.pageSize"
          @pagination="getList"
        />
      </div>
    </div>
    <!--编辑-->
    <edit-page v-if="pageType == 2" :infoId="infoId"></edit-page>
    <!--查看记录-->
    <detail-page v-if="pageType == 3" :infoId="infoId"></detail-page>
    <!--课程详情-->
    <course-details v-if="pageType == 4" :infoId="infoId"></course-details>
    <!--管理分类-->
    <add-classify v-if="pageType == 5" :pageData="pageData"></add-classify>
  </div>
</template>

<script>
  import { listDepartments } from "@/api/commonality/noPermission";
  import {
    examElCourse, examElCourseDel, examElCourseAdd,
    examElCourseEdit, examElCategoryTreeList, examElCourseCourseList
  } from "@/api/safetyEducationExam/index";
  import editPage from "./edit.vue";
  import detailPage from "./detail.vue";
  import courseDetails from "./courseDetails.vue";
  import addClassify from "../el_category/index";

export default {
  name: "El_course",
  components: {
    editPage,
    detailPage,
    courseDetails,
    addClassify
  },
  data() {
    return {
      //页面状态
      pageType:1,
      pageData:{
        type:2,//1资源管理2课程管理
      },
      //树数据
      treeData:[],
      defaultProps: {
        children: "children",
        label: "title"
      },
      //学院
      deptOptions:[],
      //适用范围
      scopeTypes: [
        {
          type: 1,
          value: "安全准入考试",
        },
        {
          type: 2,
          value: "负面清单考试",
        },
        {
          type: 3,
          value: "黑名单考试",
        },
        {
          type: 4,
          value: "模拟考试",
        },
      ],
      statusList:[
        {
          type: true,
          value: "上架",
        },
        {
          type: false,
          value: "下架",
        },
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学习资源表格数据
      el_courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        page: 1,
        pageSize:20,
        title: '',
      },
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" },
          { required: true, message: "标题不能为空", validator: this.spaceJudgment, trigger: "blur" }
        ],
      },
      infoId:{},
    };
  },
  created() {
    this.getTreeData();
    //this.getDeptList();
  },
  methods: {
    //课程状态
    switchChange(row){
      //1上架0下架
      this.$confirm('是否确定'+(row.status==true?'下架':'上架')+'?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.upDownShelf(row.id,row.status==false?true:false)


      }).catch(() => {
      });
    },
    //上架下架
    upDownShelf(id,status){
      let obj = {
        id:id,
        status:status,//课程状态 0 下架，1 上架
      };
      examElCourseEdit(obj).then( response => {
        this.msgSuccess("修改成功");
        this.getList();
      });
    },
    //去课程详情页面
    goCourseDetails(row){
      this.pageType = 4;
      this.infoId.id = row.id;
    },
    //单元格样式
    cellStyle({row, column, rowIndex, columnIndex}) {//根据测试结果动态调整单元格样式，成功-绿色，失败-红色，不支持-黄色
      if(column.title) {
        return "color:red;"
      }
    },
    /* 查询学院列表 */
    getDeptList(){
      listDepartments().then(response => {
        // this.deptOptions = response.data;
        this.$set(this, 'deptOptions', response.data)
      });
    },
    // 更多操作触发
    handleCommand(command, row) {
      switch (command) {
        case "record":
          this.goPageEdit(3,row.id);
          break;
        case "edit":
          this.goPageEdit(2,row.id);
          break;
        case "delete":
          this.handleDelete(row);
          break;
        default:
          break;
      }
    },
    //新增/编辑按钮
    goPageEdit(type,id){
      if(type == 1){
        this.infoId = {};
        this.pageType = 2;
      }else if(type == 2){
        this.infoId.id = id;
        this.pageType = 2;
      }else if(type == 3){
        this.infoId.id = id;
        this.pageType = 3;
      }else if(type == 4){
        this.pageType = 1;
        this.getList();
        this.getTreeData();
      }else if(type==5){//管理分类
        this.pageType = 5;
      }
    },
    /** 查询分类树 */
    getTreeData() {
      this.loading = true;
      examElCategoryTreeList({},2).then( response => {
        let list = [];
        let obj = {
          children:[],
          title:"所有分类",
          id:"",
        };
        list.push(obj);
        for(let i=0;i<response.data.length;i++){
          list.push(response.data[i]);
        }
        this.treeData =  list;
        this.getList();
      });
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.page = 1;
      this.queryParams.pageSize = 20;
      this.queryParams.cateId = data.id;
      this.getList();
    },
    /** 查询学习资源列表 */
    getList() {
      let self = this;
      this.loading = true;
      let obj = JSON.parse(JSON.stringify(this.queryParams))
      if(this.dateRange[0]) {
        obj.beginTime=this.dateRange[0]+'T00:00:00';
        obj.endTime=this.dateRange[1]+'T23:59:59';
      } else {
        obj.beginTime='';
        obj.endTime='';
      }
      examElCourseCourseList(obj).then( response => {
        this.el_courseList =  response.data.records;
        for(let i=0;i<self.el_courseList.length;i++){
          if(self.el_courseList[i].scopeType){
            self.el_courseList[i].scopeType = self.el_courseList[i].scopeType.split(',');
          }
        }
        this.total =  response.data.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        userId: null,
        createBy: null,
        updateBy: null,
        deptId: null,
        deptName: null,
        createTime: null,
        updateTime: null,
        remark: null,
        cateId: null,
        title: null,
        private: null,
        level: null,
        orderRest: null,
        duration: null,
        label: null,
        effectiveTime: null,
        ceType: null,
        ceTime: null,
        keywords: null,
        img: null,
        status: 0,
        videoDraggable: null,
        points: null,
        settings: null,
        type: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.$set(this,'queryParams',{
        page: 1,
        pageSize:20,
        cateId:"",
        title: '',
      });
      this.dateRange=[];
      this.$refs.tree.setCurrentKey();
      this.handleQuery();
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            examElCourseEdit(this.form).then( response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            examElCourseAdd(this.form).then( response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if(row.status == true){
        this.msgError('请先下架课程后再进行删除操作')
        return
      }
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return examElCourseDel({id:ids});
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('exam/el_course/export', {
        ...this.queryParams
      }, `exam_el_course.xlsx`)
    }
  }
};
</script>

<style scoped lang="scss">
  .el-course {
    display: flex!important;
    flex-direction: column;
    box-shadow: 0 0 8px 2px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .list-max-big-box{
      flex:1;
      display: flex!important;
      flex-direction: column;
      padding:20px!important;
      overflow: hidden;
      .top-max-box{
        flex:1;
        display: flex;
        overflow: hidden!important;
        .left-max-box{
          width:250px;
          .classify_btn{
            font-size: 14px;
            font-family: Microsoft YaHei;
            font-weight: 400;
            color: #0183FA;
            line-height: 70px;
            cursor: pointer;
            text-align: left;
          }
        }
        .center-max-box{
          border-right:2px dashed #E0E0E0;
          margin-right:30px;
          margin-top:20px;
        }
        .right-max-box{
          flex:1;
          display: flex;
          flex-direction: column;
          overflow: hidden!important;
          .min-list-box{
            flex: 1;
            overflow: hidden!important;
            display: flex;
            .button-box{
              width:300px;
              display: flex;
            }
          }
        }
      }
      .bottom-max-box{
        height:50px;
      }
    }
  }

</style>
<style  lang="scss">
.el-course{
  .el-tree-node__label{
    width: 188px;
    display:block;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }
}
</style>
