<template>
  <div class="app-container">
    <div class="filter-container">

      <div class="filter-row mb-10">
        <div class="filter-group">
          <div class="filter-lable"> 课程名称：</div>
          <el-input v-model="KEYWORDS" placeholder="搜索课件名称" clearable style="width: 200px;" @clear="getQuery"/>
        </div>
        <div class="filter-group">
          <div class="filter-lable"> 培训教师：</div>
          <el-input v-model="teacherKey" placeholder="搜索教师名称" clearable style="width: 200px;" />
        </div>
        <div class="filter-group">
          <div class="filter-lable"> 培训板块类型：</div>
          <SelectTree ref="trainingSectionRef" :options="dicListMap.trainingSectionList" :props="defaultProps" v-model="trainingSectionKey" placeholder="请选择培训板块类型" />
        </div>
        <div class="filter-group">
          <div class="filter-lable"> 培训行业类型：</div>
          <SelectTree ref="keyTrainTypeRef" :options="dicListMap.trainDicList" :props="defaultProps" v-model="TRAINTYPE" placeholder="请选择培训行业类型" />
        </div>
        <div class="filter-group">
          <div class="filter-lable"> 岗位培训类型：</div>
          <SelectTree ref="keyGwRef" :options="dicListMap.postDicList" :props="defaultProps" v-model="POSTTYPE" placeholder="请选择岗位培训类型" />
        </div>
      </div>

      <div class="filter-row">
        <div class="filter-group mr-10">
          <div class="filter-lable"> 课件状态：</div>
          <el-select v-model="vidSate" placeholder="请选择" style="width:200px">
            <el-option v-for="item in vidStateList" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </div>
        <el-button v-waves class="ml-10" type="primary" icon="el-icon-search" @click="getQuery">
          搜索
        </el-button>
        <el-button v-waves type="success" icon="el-icon-refresh" @click="goKeyReset">
          重置
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        :reserve-selection="true"
        type="selection"
        width="55"
        align="center"/>
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="COURSEWARENAME" label="课件名称" >
        <template slot-scope="{row}">
          <a v-show="row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.pdf'" @click="goViewPdf(row.COURSEWAREFILES)">
            {{ row.COURSEWARENAME }}
          </a>
          <a
            v-show="row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.doc'
              || row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.xls'
              || row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.ppt'
              || row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.docx'
              || row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.xlsx'
            || row.COURSEWAREFILES.slice(row.COURSEWAREFILES.lastIndexOf('.')) == '.pptx'"
            :href="'http://view.officeapps.live.com/op/view.aspx?src='+serverurl+row.COURSEWAREFILES"
            title="查看"
            target="_blank"
            style="cursor:pointer;">
            {{ row.COURSEWARENAME }}
          </a>
        </template>
      </el-table-column>
      <el-table-column prop="post_type_name" label="岗位培训类型" align="center" />
      <el-table-column prop="train_type_name" label="培训行业类型" align="center" width="120"/>
      <el-table-column prop="TEACHERNAME" label="讲师名称" align="center" width="100"/>
      <el-table-column prop="CLASSHOUR" label="课件学时（分钟）" align="center" width="140" />
      <el-table-column prop="CREATTIME" label="上传时间" align="center" />
      <el-table-column prop="STATE" label="课件状态" align="center" width="100">
        <template slot-scope="{row}">
          <template v-if="row.STATE=='0'">
            <div>启用</div>
          </template>
          <template v-else-if="row.STATE=='1'">
            <div class="color-red">禁用</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="420">
        <template slot-scope="{row}">
          <div class="clear_interval">
            <el-button v-show="edit && row.STATE == 0" type="info" icon="el-icon-switch-button" size="mini" @click="handleEditState(row.DATACOURSEWARE_ID,'1')">禁用</el-button>
            <el-button v-show="edit && row.STATE == 1" class="green-btn" icon="el-icon-switch-button" size="mini" @click="handleEditState(row.DATACOURSEWARE_ID,'0')">启用</el-button>
            <!-- <el-button v-show="edit && row.CURRICULUMCOUNT == 0 && row.STAGECOUNT == 0" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row.DATACOURSEWARE_ID)">编辑</el-button> -->
            <el-button type="primary" icon="el-icon-info" size="mini" @click="goInfo(row.DATACOURSEWARE_ID)">详情</el-button>
            <el-button v-show="del && row.CURRICULUMCOUNT == 0 && row.STAGECOUNT == 0" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.DATACOURSEWARE_ID)">删除</el-button>
            <el-button type="success" icon="el-icon-document" size="mini" @click="handleQuestion(row.DATACOURSEWARE_ID)">课件习题</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">上传新课件</el-button>
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>

    <el-dialog v-if="dialogFormEdit" :visible.sync="dialogFormEdit" :title="dialogType==='info'?'详情':'新增'" width="610px" top="60px">
      <el-form ref="form" :rules="rules" :model="form" label-width="120px" style="width: 500px;">
        <el-form-item label="课件名称" prop="COURSEWARENAME">
          <el-input id="COURSEWARENAME" ref="COURSEWARENAME" :disabled="dialogType == 'info'" v-model="form.COURSEWARENAME" maxlength="255" placeholder="这里输入课件名称..." title="课件名称"/>
        </el-form-item>
        <el-form-item label="培训板块" prop="trainingSection"><!-- 培训板块 -->
          <el-cascader
            :disabled="dialogType == 'info'"
            :options="dicListMap.trainingSectionList"
            :props="{ multiple: true,value: 'id', children: 'nodes', label: 'name' }"
            v-model="form.trainingSection"
            style="width: 100%;"
            placeholder="请输入培训板块"
            filterable/>
        </el-form-item>
        <el-form-item label="培训行业类型" prop="TRAINTYPE">
          <SelectTree ref="pxTree" :disabled="dialogType == 'info'" :options="dicListMap.trainDicList" :props="defaultProps" v-model="form.TRAINTYPE" :dis-state ="true" placeholder="请选择" style="width:100%"/>
        </el-form-item>
        <el-form-item label="岗位培训类型" prop="POSTTYPE">
          <SelectTree ref="gwTree" :disabled="dialogType == 'info'" :options="dicListMap.postDicList" :props="defaultProps" v-model="form.POSTTYPE" placeholder="请选择" style="width:100%"/>
        </el-form-item>
        <el-form-item label="课件学时(分钟)" prop="CLASSHOUR">
          <!--          <el-input ref="CLASSHOUR" v-model="form.CLASSHOUR" type="number" maxlength="11" placeholder="这里输入课件学时..." title="课件学时"/>-->
          <el-input-number :disabled="dialogType == 'info'" v-model="form.CLASSHOUR" :min="1" label="课件学时" style="width: 100%;"/>
          <span class="ml-10">分钟</span>
        </el-form-item>
        <el-form-item label="讲师名称" prop="SPEAKER">
          <!--          <el-input id="SPEAKER" ref="SPEAKER" v-model="form.SPEAKER" maxlength="255" placeholder="这里输入主讲人..." title="主讲人"/>-->
          <el-select :disabled="dialogType == 'info'" v-model="form.SPEAKER" filterable placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in teacherAllList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="课件文件">
          <div v-if="form.fileIsType">
            <el-upload
              ref="dataUpload"
              :on-remove="handleRemoveData"
              :before-upload="beforeDataFileUpload"
              :file-list="fileList"
              :auto-upload="false"
              :limit="1"
              accept=".pdf"
              class="upload-demo"
              action=""
              multiple>
              <div>
                <el-button size="small" type="primary" style="width:110px">点击上传</el-button>
                <span class="red-tip">*只能上传pdf文件</span>
              </div>
            </el-upload>
          </div>
          <div v-else>
            <a v-if="form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.pdf'" class="a_link" @click="goViewPdf(form.COURSEWAREFILES)">
              {{ form.COURSEWARENAME_update }}
            </a>
            <a
              v-if="form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.doc'
                || form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.xls'
                || form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.ppt'
                || form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.docx'
                || form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.xlsx'
              || form.COURSEWAREFILES.slice(form.COURSEWAREFILES.lastIndexOf('.')) == '.pptx'"
              :href="'http://view.officeapps.live.com/op/view.aspx?src='+serverurl+form.COURSEWAREFILES"
              class="a_link"
              title="查看"
              target="_blank"
              style="cursor:pointer;">
              {{ form.COURSEWARENAME_update }}
            </a>
            <i v-show="form.kjCount =='0' && dialogType != 'info' " class="el-icon-close" @click="delFujian"/>
          </div>
        </el-form-item>
        <el-form-item label="课件截图">
          <div v-if="form.captureIsType" style="display:flex">
            <el-upload
              ref="dataCaptureUpload"
              :on-remove="handleRemove"
              :on-change="handleEditChange"
              :before-upload="beforeCaptureFileUpload"
              :auto-upload="false"
              :limit="1"
              :class="{hide:hideUpload}"
              action="#"
              accept=".jpg,.jpeg,.png"
              list-type="picture-card">
              <i class="el-icon-plus" />
            </el-upload>
            <span style="margin-left:20px;color: red;font-size: 12px">
              * 建议上传尺寸224*160。
            </span>
          </div>
          <div v-else class="img-size">
            <div style="display:flex">
              <img :src="config.fileUrl + form.COURSEWARECAPTURE" width="100%" alt="">
              <i v-show="form.kjCount =='0' && dialogType != 'info' " class="el-icon-close" @click="delFujianTupian"/>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="课件描述" prop="COURSEWAREINTRODUCE"><!-- 课件介绍 -->
          <el-input id="COURSEWAREINTRODUCE" ref="COURSEWAREINTRODUCE" :disabled="dialogType == 'info'" v-model="form.COURSEWAREINTRODUCE" type="textarea" maxlength="255" placeholder="这里输入课件介绍..." title="课件介绍"/>
        </el-form-item>
        <el-form-item label="大纲类型" prop="ONTLINETYPE">
          <el-select :disabled="dialogType == 'info'" v-model="form.ONTLINETYPE" placeholder="请选择" style="width: 100%;">
            <el-option v-for="item in dicListMap.outlineDicList" :key="item.DICTIONARIES_ID" :label="item.NAME" :value="item.DICTIONARIES_ID"/>
          </el-select>
        </el-form-item>
        <el-form-item label="相关词条" prop="trainingSection"><!-- 相关词条 -->
          <el-cascader
            :disabled="dialogType == 'info'"
            :options="dicListMap.relatedTermList"
            :props="{ multiple: true,value: 'id', children: 'nodes', label: 'name' }"
            v-model="form.relatedTerm"
            style="width: 100%;"
            placeholder="请输入相关词条"
            filterable/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button v-show="dialogType != 'info'" type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogViewPdf" title="文档" width="80%" top="60px">
      <div>
        <pdf
          :page="pageNum"
          :src="pdfUrl"
          @progress="loadedRatio = $event"
          @num-pages="pageTotalNum=$event"
        />
        <div style="marginTop: 10px; color: #409EFF">{{ pageNum }} / {{ pageTotalNum }}</div>
        <el-button-group>
          <el-button type="primary" icon="el-icon-arrow-left" size="mini" @click="prePage">上一页</el-button>
          <el-button type="primary" size="mini" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"/></el-button>
        </el-button-group>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import { upload } from '@/utils/upload'
import pdf from 'vue-pdf'
import SelectTree from '@/components/SelectTree'
import Treeselect from '@riophae/vue-treeselect'

export default {
  components: { Pagination, pdf, SelectTree, Treeselect },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      config: config,
      KEYWORDS: '',
      teacherKey: '',
      trainingSectionKey: '',
      TRAINTYPE: '',
      POSTTYPE: '',
      vidSate: '',
      varList: [],
      pd: [],
      form: {
        COURSEWARENAME: '', // 课件名称
        SPEAKER: '', // 主讲人
        COURSEWAREINTRODUCE: '', // 课件介绍
        COURSEWAREFILES: '', // 资料文件
        COURSEWARECAPTURE: '', // 封面截图
        COURSEWAREUSERS: '', // 适用人员
        cfile: '',
        ccfile: '',
        dialogVisible: false,
        fileIsType: true,
        trainingSection: [],
        relatedTerm: [],
        captureIsType: true
      },
      hideUpload: false, // 显示图片
      fileList: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogType: 'add',
      LearnerCategoryList: [],
      // pdf预览
      dialogViewPdf: false,
      serverurl: config.fileUrl,
      pdfUrl: '',
      pageNum: 1,
      pageTotalNum: 1, // 总页数
      loadedRatio: 0, // 当前页面的加载进度，范围是0-1 ，等于1的时候代表当前页已经完全加载完成了
      rules: {
        COURSEWARENAME: [{ required: true, message: '课件名称不能为空', trigger: 'blur' }],
        TRAINTYPE: [{ required: true, message: '请选择培训行业类型', trigger: 'blur' }],
        // POSTTYPE: [{ required: true, message: '请选择岗位培训类型', trigger: 'blur' }],
        CLASSHOUR: [{ required: true, message: '课件学时不能为空', trigger: 'blur' }],
        SPEAKER: [{ required: true, message: '讲师名称不能为空', trigger: 'blur' }],
        COURSEWAREINTRODUCE: [{ required: true, message: '课件描述不能为空', trigger: 'blur' }],
        ONTLINETYPE: [{ required: true, message: '请选择大纲类型', trigger: 'blur' }]
      },
      dicListMap: {
        outlineDicList: [],
        trainDicList: [],
        postDicList: [],
        trainingSectionList: [],
        relatedTermList: []
      },
      teacherAllList: [],
      vidStateList: [{ value: '0', label: '启用' },
        { value: '1', label: '禁用' }
      ]
    }
  },
  created() {
    this.getList()
    this.getDict()
    this.getIdcList()
  },
  methods: {
    getRowKey(row) {
      return row.DATACOURSEWARE_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.KEYWORDS = ''
      this.TRAINTYPE = ''
      this.POSTTYPE = ''
      this.vidSate = ''
      this.teacherKey = ''
      this.$refs.keyGwRef.clearHandle()
      this.$refs.trainingSectionRef.clearHandle()
      this.$refs.keyTrainTypeRef.clearHandle()
      this.getQuery()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/datacourseware/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          TRAINTYPE: this.TRAINTYPE,
          POSTTYPE: this.POSTTYPE,
          STATE: this.vidSate,
          teacherKey: this.teacherKey,
          trainingSectionKey: this.trainingSectionKey
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      this.getDict()
      this.dialogFormEdit = true
    },

    goInfo(ID) {
      this.resetForm()

      // this.getDict()
      this.dialogType = 'info'
      requestFN(
        '/datacourseware/goEdit',
        {
          DATACOURSEWARE_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        // 培训板块     相关词条 回显
        var trainingSectionIDS = [] // 培训板块
        var relatedTermIDS = [] //  相关词条
        data.coursewareAllList.forEach((item, index) => {
          if (item.RECORD_TYPE_ID == 'trainingSection') {
            const valID = item.DICTIONARIES_IDS.split(',')
            trainingSectionIDS.push(valID)
          } else if (item.RECORD_TYPE_ID == 'relatedTerm') {
            const valID = item.DICTIONARIES_IDS.split(',')
            relatedTermIDS.push(valID)
          }
        })
        this.form.trainingSection = trainingSectionIDS
        this.form.relatedTerm = relatedTermIDS
        this.form.COURSEWARENAME_update = this.form.COURSEWARENAME
        this.form.fileIsType = false
        this.form.captureIsType = false

        // this.form.COURSEWAREUSERS = this.form.COURSEWAREUSERS.slice(1, this.form.COURSEWAREUSERS.length - 1).split(',')
        // const node = {}
        // node.id = this.form.TRAINTYPE
        // const node2 = {}
        // node2.id = this.form.POSTTYPE
        // this.$nextTick(() => { // 此处使用这个可以等节点渲染后再获取节点
        //   this.$refs.pxTree.handleNodeClick(node)
        //   this.$refs.gwTree.handleNodeClick(node2)
        // })
        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 修改
    handleEdit(ID) {
      this.resetForm()

      // this.getDict()
      this.dialogType = 'edit'
      requestFN(
        '/datacourseware/goEdit',
        {
          DATACOURSEWARE_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        // 培训板块     相关词条 回显
        var trainingSectionIDS = [] // 培训板块
        var relatedTermIDS = [] //  相关词条
        data.coursewareAllList.forEach((item, index) => {
          if (item.RECORD_TYPE_ID == 'trainingSection') {
            const valID = item.DICTIONARIES_IDS.split(',')
            trainingSectionIDS.push(valID)
          } else if (item.RECORD_TYPE_ID == 'relatedTerm') {
            const valID = item.DICTIONARIES_IDS.split(',')
            relatedTermIDS.push(valID)
          }
        })
        this.form.trainingSection = trainingSectionIDS
        this.form.relatedTerm = relatedTermIDS
        this.form.COURSEWARENAME_update = this.form.COURSEWARENAME
        this.form.fileIsType = false
        this.form.captureIsType = false

        // this.form.COURSEWAREUSERS = this.form.COURSEWAREUSERS.slice(1, this.form.COURSEWAREUSERS.length - 1).split(',')
        // const node = {}
        // node.id = this.form.TRAINTYPE
        // const node2 = {}
        // node2.id = this.form.POSTTYPE
        // this.$nextTick(() => { // 此处使用这个可以等节点渲染后再获取节点
        //   this.$refs.pxTree.handleNodeClick(node)
        //   this.$refs.gwTree.handleNodeClick(node2)
        // })
        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    validStr(str) {
      if (str != null && str != '' && typeof (str) != 'undefined' && str != 0) { return true }
      return false
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.$refs.dataUpload) {
            this.$refs.dataUpload.submit()
          }
          if (this.$refs.dataCaptureUpload) {
            this.$refs.dataCaptureUpload.submit()
          }
          if (this.form.fileIsType) {
            if (!this.validStr(this.form.cfile)) {
              this.$message.warning('课件文件不能为空，请上传')
              return false
            }
          }
          if (this.form.captureIsType) {
            if (!this.validStr(this.form.ccfile)) {
              this.$message.warning('课件截图不能为空，请上传')
              return false
            } else {
              this.form.ccfile = this.form.ccfile.raw
            }
          }
          const loading = this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          // this.form.COURSEWAREUSERS = ',' + this.form.COURSEWAREUSERS.join(',') + ','
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            if (key == 'trainingSection' && this.form[key]) {
              var trainingSectionIDS = ''
              this.form[key].forEach((item, index) => {
                trainingSectionIDS += item + ';'
              })
              formData.append('trainingSection', trainingSectionIDS)
            } else if (key == 'relatedTerm' && this.form[key]) {
              var relatedTermIDS = ''
              this.form[key].forEach((item, index) => {
                relatedTermIDS += item + ';'
              })
              formData.append('relatedTerm', relatedTermIDS)
            } else {
              formData.append(key, this.form[key])
            }
          })
          upload(
            '/datacourseware/' + this.dialogType,
            formData
          ).then((data) => {
            loading.close()
            this.$message({
              message: '资料课件保存成功',
              type: 'success'
            })
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    handleQuestion(ID) {
      this.$parent.COURSEWAREID = ID
      this.$parent.COURSEWARETYPE = '2'
      this.$parent.activeName = 'Question'
    },
    beforeDataFileUpload(file) {
      const types = ['doc', 'docx', 'pdf']
      const fileSuffix = file.name.slice(file.name.lastIndexOf('.') + 1)
      const isImage = types.includes(fileSuffix.toLowerCase())
      if (this.fileList.length > 0) {
        this.$message.error('文件超出个数限制!')
        return false
      }
      if (!isImage) {
        this.$message.error('上传文件格式只能是PDF 格式!')
        return false
      } else {
        const filistMap = {}
        filistMap.name = file.name
        filistMap.file = file
        this.fileList.push(filistMap)
        this.form.cfile = file
        this.form.COURSEWAREFILES = file
        this.$forceUpdate()
        return true
      }
    },
    handleRemoveData(file, fileList) { // 文件列表移除文件时的钩子
      if (file.file) {
        const types = ['doc', 'docx', 'pdf']
        const isImage = types.includes(file.file.type)
        if (isImage) {
          this.fileList = []
        }
      }
    },
    beforeCaptureFileUpload(file) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
      } else {
        this.form.ccfile = file
        this.form.COURSEWARECAPTURE = file
        this.$forceUpdate()
        return false
      }
    },
    handlePictureCardPreview(file, fileList) {
      this.form.ccfile = file
      this.form.COURSEWARECAPTURE = file
      this.form.dialogImageUrl = file.url
      this.form.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.ccfile = file
      this.form.COURSEWARECAPTURE = file
      this.hideUpload = fileList.length >= 1
    },
    handleEditChange(file, fileList) {
      this.form.ccfile = file
      this.form.COURSEWARECAPTURE = file
      this.hideUpload = fileList.length >= 1
    },
    // pdf 预览
    goViewPdf(filePath) {
      this.pageNum = 1
      this.pdfUrl = this.serverurl + filePath
      this.dialogViewPdf = true
    },
    // 上一页
    prePage() {
      let page = this.pageNum
      page = page > 1 ? page - 1 : this.pageTotalNum
      this.pageNum = page
    },

    // 下一页
    nextPage() {
      let page = this.pageNum
      page = page < this.pageTotalNum ? page + 1 : 1
      this.pageNum = page
    },

    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/datacourseware/delete',
          {
            DATACOURSEWARE_ID: id
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    batchDel() {
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要删除的项...',
          type: 'error'
        })
        return false
      }
      const ids = _selectData.map((item, index) => {
        return item.DATACOURSEWARE_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/datacourseware/deleteAll',
          {
            DATA_IDS: ids
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.varList = []
          this.listQuery.page = 1
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 判断按钮权限，用于是否显示按钮
    hasButton: function() {
      var keys = 'courseware:add,courseware:del,courseware:edit,toExcel'
      requestFN(
        '/head/hasButton',
        {
          keys: keys
        }
      ).then((data) => {
        this.add = data.coursewarefhadminadd		// 新增权限
        this.del = data.coursewarefhadmindel		// 删除权限
        this.edit = data.coursewarefhadminedit	// 修改权限
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '532282f9c48346b8b646531909c739df'
        }
      ).then((data) => {
        this.LearnerCategoryList = data.list
      }).catch((e) => {

      })
      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '3c0d9b5e74834adfacb76139e5d731e5'
        }
      ).then((data) => {
        this.dicListMap.outlineDicList = data.list
      }).catch((e) => {
      })
    },
    resetForm() {
      this.form = {
        COURSEWARENAME: '', // 课件名称
        SPEAKER: '', // 主讲人
        COURSEWAREINTRODUCE: '', // 课件介绍
        COURSEWAREFILES: '', // 资料文件
        COURSEWARECAPTURE: '', // 封面截图
        COURSEWAREUSERS: '', // 适用人员
        CLASSHOUR: 0,
        TRAINTYPE: '',
        POSTTYPE: '',
        ONTLINETYPE: '',
        fileIsType: true,
        captureIsType: true
      }
      if (this.$refs.pxTree) {
        this.$refs.pxTree.clearHandle()
      }
      if (this.$refs.gwTree) {
        this.$refs.gwTree.clearHandle()
      }
      if (this.$refs.dataUpload || this.fileList.length > 0) {
        this.fileList = []
        this.form.ccfile = ''
        this.form.COURSEWARECAPTURE = ''
        this.hideUpload = false
        this.$refs.dataUpload.clearFiles()
      }
      if (this.$refs.dataCaptureUpload) {
        this.form.cfile = ''
        this.$refs.dataCaptureUpload.clearFiles()
      }
    },
    getDicListByPID(pId, listName) {
      requestFN(
        '/dictionaries/listAllDictToParId',
        {
          parentId: pId
        }
      ).then((data) => {
        this.dicListMap[listName] = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
    },
    getIdcList() {
      this.getDicListByPID('052369aa22d242118236cde52d0c67ea', 'trainDicList')
      this.getDicListByPID('f6a7c4f5602f46e291d06b1390a3f820', 'postDicList')
      this.getDicListByPID('d538d11e4eec409ab428f5d2f3c67c24', 'trainingSectionList') // 培训板块
      this.getDicListByPID('4459d3ff36d1475d8b2266da959fcc44', 'relatedTermList') // 相关词条
      this.getTeacher()
    },
    // 修改
    handleEditState(ID, state) {
      requestFN(
        '/datacourseware/editState',
        {
          DATACOURSEWARE_ID: ID,
          STATE: state
        }
      ).then((data) => {
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    delFujian(item) {
      this.form.fileIsType = true
      this.form.COURSEWAREFILES = ''
    },
    delFujianTupian(item) {
      this.form.captureIsType = true
      this.form.COURSEWARECAPTURE = ''
      this.form.ccfile = ''
      this.hideUpload = false
    },
    getTeacher() { // 获取教师信息
      requestFN(
        '/teacher/listAllSelect',
        {}
      ).then((data) => {
        this.teacherAllList = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    }
  }
}

</script>
<style lang="scss">
  .hide .el-upload--picture-card {
    display: none;
  }
  div.popContainer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.3);
  }
</style>
