<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">
          <!--          {{ dicListMap.trainingSectionList }}-->
          <div class="filter-lable"> 培训板块类型：</div>
          <SelectTree ref="trainingSectionRef" :options="dicListMap.trainingSectionList" :props="defaultProps" v-model="trainingSectionKey" placeholder="请选择培训板块类型" />
          <!--          <Treeselect 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 type="primary" icon="el-icon-search" style="margin-left:5px" @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 @click="goViewVideo(row)">{{ row.COURSEWARENAME }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="post_type_name" label="岗位培训类型" align="center" />
      <el-table-column :show-overflow-tooltip="true" prop="train_type_name" label="培训行业类型" >
        <template slot-scope="{row}">
          <div v-if="row.CURRENCY == 1">通用</div>
          <div v-else>{{ row.train_type_name }}</div>
        </template>
      </el-table-column>
      <!--  <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 prop="STATE" label="课件来源" align="center" width="100">
        <template slot-scope="{row}">
          <template v-if="row.CURRICULUM_ID_REMOTE">
            <div>商城</div>
          </template>
          <template v-else>
            <div>自传</div>
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="NUMEXAMPLE" label="习题数" align="center" />
      <el-table-column label="操作" align="center" width="520">
        <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.VIDEOCOURSEWARE_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.VIDEOCOURSEWARE_ID,'0')">启用</el-button>
            <el-button v-show="edit && row.ISPERFECT === '0'" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row.VIDEOCOURSEWARE_ID)">编辑</el-button>
            <el-button type="primary" icon="el-icon-info" size="mini" @click="goInfo(row.VIDEOCOURSEWARE_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.VIDEOCOURSEWARE_ID)">删除</el-button>
            <el-button type="success" icon="el-icon-document" size="mini" @click="handleQuestion(row.VIDEOCOURSEWARE_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>
        <!--        <el-button v-show="del" type="danger" icon="el-icon-delete" plain @click="batchDel">删除</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="600px" top="60px">
      <el-form ref="form" :rules="rules" :model="form" label-width="140px" 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="CURRENCY">
          <el-radio-group id="CURRENCY" ref="CURRENCY" v-model="form.CURRENCY">
            <el-radio :disabled="dialogType == 'info'" label="0">否</el-radio>
            <el-radio :disabled="dialogType == 'info'" label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.CURRENCY == 0" label="培训行业类型" prop="TRAINTYPE">
          <SelectTree ref="pxTree" :disabled="dialogType == 'info'" :options="dicListMap.trainDicList" :props="defaultProps" v-model="form.TRAINTYPE" 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">
          &lt;!&ndash;          <el-input ref="CLASSHOUR" v-model="form.CLASSHOUR" type="number" maxlength="11" placeholder="这里输入课件学时..." title="课件学时" style="width:100px"/>&ndash;&gt;
          <el-input-number v-model="form.CLASSHOUR" :min="1" label="课件学时"/>
          <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" style="display:flex">
            <el-upload ref="videoUpload" :on-remove="handleRemoveVideo" :on-error="handleUploadVideoError" :on-exceed="handleUploadVideoExceed" :before-upload="beforeVideoFileUpload" :file-list="fileList" :limit="1" accept=".mp4" class="upload-demo" action="" multiple>
              <div>
                <el-button size="small" type="primary" style="width:110px">点击上传</el-button>
                <span class="red-tip">* 只能上传mp4文件.最大上传500M</span>
              </div>
            </el-upload>
          </div> -->
          <div v-if="form.fileIsType">
            <div>
              <input v-show="false" id="fileUpload" ref="fileUpload" type="file" @change="fileChange($event)">
              <el-button type="primary" @click="uploadFile">选择文件</el-button>
              <span v-if="file">{{ file.name }}</span>
            </div>
            <div class="color-red">
              * 只能上传mp4文件.最大上传500M
            </div>
            <!-- <label class="status">上传状态: <span>{{ statusText }}</span></label>
            <div class="upload-type">
              上传方式一, 使用 UploadAuth 上传:
              <button :disabled="uploadDisabled" @click="authUpload">开始上传</button>
              <button :disabled="pauseDisabled" @click="pauseUpload">暂停</button>
              <button :disabled="resumeDisabled" @click="resumeUpload">恢复上传</button>

              <span class="progress">上传进度: <i id="auth-progress">{{ authProgress }}</i> %</span>
            </div> -->
          </div>
          <div v-else>
            <a class="a_link" @click="goViewVideo(form)">{{ 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 v-if="!form.captureIsType && !form.fileIsType" label="课件截图">
          <!-- <div style="display:flex">
            <el-upload ref="videoCaptureUpload" :on-remove="handleRemove" :on-change="handleEditChange" :before-upload="beforeFCaptureileUpload" :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 class="img-size">
            <img :src="form.VIDEOCAPTURE" width="100%" alt="">
          </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>
    <div v-if="isShowProgress" class="popContainer">
      <div class="progress_title">视频上传中，请耐心等待...</div>
      <el-progress
        :percentage="authProgress"
        type="circle"
        class="progress"/>
    </div>

    <el-dialog v-show="dialogViewVideo" :visible.sync="dialogViewVideo" title="视频" width="800px" @close="closePlayer">
      <!-- <div>
        <video-player ref="videoPlayer" :playsinline="true" :options="playerOptions" class="video-player vjs-custom-skin" />
      </div> -->

      <div id="aLiVideoPlayer" class="prism-player"/>
    </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 { videoPlayer } from 'vue-video-player'
import 'video.js/dist/video-js.css'
import SelectTree from '@/components/SelectTree'
import Treeselect from '@riophae/vue-treeselect'

import axios from 'axios'
export default {
  components: { Pagination, videoPlayer, 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: '', // 课件名称
        CURRENCY: '', // 是否通过
        SPEAKER: '', // 主讲人
        COURSEWAREINTRODUCE: '', // 课件介绍
        VIDEOFILES: '', // 课件文件路径
        VIDEOCAPTURE: '', // 课件截图
        VIDEOUSERS: [], // 适用人员
        TRAINTYPE: '',
        POSTTYPE: '',
        vfile: '',
        vcfile: '',
        CLASSHOUR: 0,
        dialogVisible: false,
        fileIsType: true,
        trainingSection: [],
        relatedTerm: [],
        captureIsType: true
      },
      hideUpload: false, // 显示图片
      fileList: [],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name',
        multiple: true,
        checkStrictly: true
      },
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogType: 'add',
      LearnerCategoryList: [],
      serverurl: config.fileUrl,
      dialogViewVideo: false,
      playerOptions: {
        playbackRates: [0.5, 1.0, 1.5, 2.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放。
        muted: false, // 默认情况下将会消除任何音频。
        loop: false, // 是否视频一结束就重新开始。
        preload: 'auto', // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: 'zh-CN',
        aspectRatio: '16:9', // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
        sources: [{
          type: 'video/mp4', // 类型
          src: 'https://whrx.qhdsafety.com/file/uploadFiles/file/13cf0f4ec77e4d98ae8cdd9c3386ae0c/20210625/691910cd81024986a392f6203c4045f8.mp4' // url地址
        }],
        poster: '', // 封面地址
        notSupportedMessage: '此视频暂无法播放，请稍后再试', // 允许覆盖Video.js无法播放媒体源时显示的默认信息。
        controlBar: {
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true // 是否显示全屏按钮
        }
      },
      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' }],
        CURRENCY: [{ required: true, message: '是否通用为必选', trigger: 'blur' }]
      },
      dicListMap: {
        outlineDicList: [],
        trainDicList: [],
        postDicList: [],
        trainingSectionList: [],
        relatedTermList: []
      },
      teacherAllList: [],
      vidStateList: [{ value: '0', label: '启用' },
        { value: '1', label: '禁用' }
      ],
      authProgress: 0,
      isShowProgress: false,
      player: {},
      isEditVideo: false,
      file: {}
    }
  },
  async created() {
    window.addEventListener('touchmove', e => e.preventDefault())
    await this.getList()
    await this.getDict()
    await this.getIdcList()
  },
  methods: {
    getRowKey(row) {
      return row.VIDEOCOURSEWARE_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(
        '/videocourseware/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
      })
    },
    // 格式化适用人员名称
    formatterUsers(row, column) {
      var VIDEOUSERS_VAL = ''
      const VIDEOUSERS = row.VIDEOUSERS.slice(1, row.VIDEOUSERS.length - 1).split(',')
      for (let i = 0; i < VIDEOUSERS.length; i++) {
        for (let j = 0; j < this.LearnerCategoryList.length; j++) {
          const option = this.LearnerCategoryList[j]
          if (option.BIANMA === VIDEOUSERS[i]) {
            VIDEOUSERS_VAL += option.NAME + ','
          }
        }
      }
      return VIDEOUSERS_VAL.slice(0, VIDEOUSERS_VAL.length - 1)
    },
    // 添加
    handleAdd() {
      this.dialogType = 'add'
      this.resetForm()
      // this.getDict()
      this.dialogFormEdit = true
    },

    goInfo(ID) {
      this.resetForm()
      // this.getDict()
      this.dialogType = 'info'
      requestFN(
        '/videocourseware/goEdit',
        {
          VIDEOCOURSEWARE_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        // console.info(this.form)
        // //培训板块     相关词条 回显
        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.VIDEOUSERS = this.form.VIDEOUSERS.slice(1, this.form.VIDEOUSERS.length - 1).split(',')
        this.form.COURSEWARENAME_update = this.form.COURSEWARENAME
        this.form.fileIsType = false
        this.form.captureIsType = false
        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 修改
    handleEdit(ID) {
      this.resetForm()
      // this.getDict()
      this.dialogType = 'edit'
      requestFN(
        '/videocourseware/goEdit',
        {
          VIDEOCOURSEWARE_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        // console.info(this.form)
        // //培训板块     相关词条 回显
        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.VIDEOUSERS = this.form.VIDEOUSERS.slice(1, this.form.VIDEOUSERS.length - 1).split(',')
        this.form.COURSEWARENAME_update = this.form.COURSEWARENAME
        this.form.fileIsType = false
        this.form.captureIsType = false
        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 修改
    handleEditState(ID, state) {
      requestFN(
        '/videocourseware/editState',
        {
          VIDEOCOURSEWARE_ID: ID,
          STATE: state
        }
      ).then((data) => {
        this.getList()
      }).catch((e) => {
        this.listLoading = false
      })
    },
    validStr(str) {
      if (str != null && str != '' && typeof (str) != 'undefined' && str != 0) { return true }
      return false
    },
    // 保存
    confirm() {
      if (this.form.fileIsType) {
        if (!this.file) {
          this.$message.warning('课件文件不能为空，请上传')
          return false
        }
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          Object.keys(this.form).map(key => {
            if (key == 'trainingSection' && this.form[key]) {
              var trainingSectionIDS = ''
              this.form[key].forEach((item, index) => {
                trainingSectionIDS += item + ';'
              })
              this.form.trainingSection = trainingSectionIDS
              // formData.append('trainingSection', trainingSectionIDS)
            } else if (key == 'relatedTerm' && this.form[key]) {
              var relatedTermIDS = ''
              this.form[key].forEach((item, index) => {
                relatedTermIDS += item + ';'
              })
              this.form.relatedTerm = relatedTermIDS
              // formData.append('relatedTerm', relatedTermIDS)
            }
          })
          this.form.isEditVideo = this.isEditVideo
          if ((this.dialogType == 'add' && this.uploader) || (this.dialogType == 'edit' && this.isEditVideo)) {
            this.authUpload()
            this.dialogFormEdit = false
            this.isShowProgress = true
          } else {
            this.saveInfo()
          }
        } else {
          return false
        }
      })
    },
    closePlayer() {
      this.player.dispose()
    },
    saveInfo() {
      requestFN(
        '/videocourseware/' + this.dialogType,
        this.form
      ).then((data) => {
        this.$message({
          message: data.msg,
          type: data.type
        })
        this.isShowProgress = false
        this.dialogFormEdit = false
        this.getList()
      }).catch((e) => {
      })
    },
    handleQuestion(ID) {
      this.$parent.COURSEWAREID = ID
      this.$parent.COURSEWARETYPE = '1'
      this.$parent.activeName = 'Question'
    },
    beforeVideoFileUpload(file) {
      const types = ['video/mp4']
      const isImage = types.includes(file.type)
      const isLt500M = file.size / 1024 / 1024 < 500
      if (this.fileList.length > 0) {
        this.$message.error('文件超出个数限制!')
        return false
      }
      if (!isImage) {
        this.$message.error('上传视频只能是 MP4 格式!')
        return false
      } else if (!isLt500M) {
        this.$message.error('上传视频大小不能超过 500MB!')
        return false
      } else {
        // const filistMap = {}
        // console.info(file)
        // filistMap.name = file.name
        // file.status = 'success'
        // filistMap.file = file
        this.fileList.push(file)
        this.$forceUpdate()
        return true
      }
    },
    beforeFCaptureileUpload(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.vcfile = file
        this.form.VIDEOCAPTURE = file
      }
    },
    handlePictureCardPreview(file, fileList) {
      this.form.vcfile = file
      this.form.VIDEOCAPTURE = file
      this.form.dialogImageUrl = file.url
      this.form.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.vcfile = file
      this.form.VIDEOCAPTURE = file
      this.hideUpload = fileList.length >= 1
    },
    handleEditChange(file, fileList) {
      this.form.vcfile = file
      this.form.VIDEOCAPTURE = file
      this.hideUpload = fileList.length >= 1
    },
    handleRemoveVideo(file, fileList) { // 文件列表移除文件时的钩子
      this.fileList = []
    },
    handleUploadVideoExceed(file, fileList) { // 上传超出数量限制时的钩子
      this.$message.warning('最多上传1个课件哦！')
    },
    // eslint-disable-next-line handle-callback-err
    handleUploadVideoError(err, file, fileList) {
      this.fileList = fileList
      file.status = 'success'
      this.fileList.push(file)
    },
    handleDelete(id) {
      this.$confirm('确定要删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/videocourseware/delete',
          {
            VIDEOCOURSEWARE_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.VIDEOCOURSEWARE_ID
      }).join(',')

      this.$confirm('确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/videocourseware/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: '3c0d9b5e74834adfacb76139e5d731e5'
        }
      ).then((data) => {
        this.dicListMap.outlineDicList = data.list
      }).catch((e) => {
      })
    },
    resetForm() {
      this.form = {
        COURSEWARENAME: '', // 课件名称
        SPEAKER: '', // 主讲人
        COURSEWAREINTRODUCE: '', // 课件介绍
        VIDEOFILES: '', // 课件文件路径
        VIDEOCAPTURE: '', // 课件截图
        VIDEOUSERS: '', // 适用人员
        vfile: '',
        vcfile: '',
        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.videoUpload) {
        this.$refs.videoUpload.clearFiles()
      }
      if (this.$refs.videoCaptureUpload) {
        this.form.vcfile = ''
        this.form.VIDEOCAPTURE = ''
        this.hideUpload = false
        this.$refs.videoCaptureUpload.clearFiles()
      }
      this.file = {}
    },
    goViewVideo(row) {
      if (row.VIDEOCOURSEWARE_ID_REMOTE) {
        requestFN(
          '/videoRes/getVideoPlayAuth',
          {
            VIDEOCOURSEWARE_ID: row.VIDEOCOURSEWARE_ID_REMOTE,
            CURRICULUM_ID: row.CURRICULUM_ID_REMOTE
          }
        ).then((data) => {
          data.responseBody.videoList.map(item => {
            const video = {}
            video[item.difinition] = item.playUrl
            return video
          })
          if (data.result == 'success') {
            this.dialogViewVideo = true
            const video = {}
            data.responseBody.videoList.map(item => {
              video[item.definition] = item.playURL
            })
            console.log(video)
            this.$nextTick(() => {
              // eslint-disable-next-line no-undef
              this.player = new Aliplayer({
                id: 'aLiVideoPlayer',
                source: JSON.stringify(video),
                width: '100%',
                height: '500px',
                autoplay: true,
                isLive: false,
                components: [{
                  name: 'QualityComponent',
                  type: window.AliPlayerComponent.QualityComponent,
                  args: [function(definition, desc) {
                    console.log(definition + '-----' + desc)
                  }]
                }]

              }, function(player) {
                console.log('The player is created')
                player.on('sourceloaded', function(params) {
                  var paramData = params.paramData
                  var desc = paramData.desc
                  var definition = paramData.definition
                  player.getComponent('QualityComponent').setCurrentQuality(desc, definition)
                })
              })
            })
          }
        })
      } else {
        requestFN(
          '/videocourseware/getVideoPlayAuth',
          {
            videoId: row.VIDEOFILES
          }
        ).then((data) => {
          console.info(row.VIDEOFILES)
          console.info(data.playAuth)
          if (data.type == 'success') {
            this.dialogViewVideo = true
            this.$nextTick(() => {
              // eslint-disable-next-line no-undef
              this.player = new Aliplayer({
                'id': 'aLiVideoPlayer',
                'vid': row.VIDEOFILES,
                'playauth': data.playAuth,
                'qualitySort': 'asc',
                'format': 'm3u8',
                'encryptType': 1,
                'mediaType': 'video',
                'width': '100%',
                'height': '500px',
                'autoplay': true,
                'isLive': false,
                'rePlay': false,
                'playsinline': true,
                'preload': true,
                'controlBarVisibility': 'hover',
                'useH5Prism': true
              }, function(player) {
                console.log('The player is created')
              }
              )
            })
          }
        }).catch((e) => {
        })
      }
      // const type = row.VIDEOFILES.slice(row.VIDEOFILES.lastIndexOf('.') + 1)
      // this.playerOptions.sources[0].src = this.serverurl + row.VIDEOFILES
      // this.playerOptions.poster = this.serverurl + row.VIDEOCAPTURE
      // this.playerOptions.sources[0].type = 'video/' + type
    },
    // closePlay() {
    //   this.$refs.videoPlayer.player.pause()
    // },
    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() // 获取教师信息
    },
    delFujian() {
      this.fileList = []
      this.isEditVideo = true
      this.form.COURSEWARENAME_update = ''
      this.form.fileIsType = true
      this.form = Object.assign({}, this.form)
      // this.$forceUpdate()
    },
    delFujianTupian() {
      this.form.captureIsType = true
      this.form.vcfile = ''
      this.form.VIDEOCAPTURE = ''
      this.hideUpload = false
    },
    getTeacher() { // 获取教师信息
      requestFN(
        '/teacher/listAllSelect',
        {}
      ).then((data) => {
        this.teacherAllList = JSON.parse(data.zTreeNodes)
      }).catch((e) => {
      })
    },

    uploadFile() {
      this.$refs.fileUpload.dispatchEvent(new MouseEvent('click'))
    },
    fileChange(e) {
      const size = 1024 * 1024 * 500
      if (!e.target.files[0]) {
        this.$message.warning('请先选择需要上传的文件!')
        return
      } else if (e.target.files[0].type != 'video/mp4') {
        this.$message.warning('请选择MP4文件!')
        return
      } else if (e.target.files[0].size > size) {
        this.$message.warning('文件大小超过500M，请重新上传!')
        return
      }

      this.file = e.target.files[0]
      // eslint-disable-next-line no-unused-vars
      var Title = this.file.name
      var userData = '{"Vod":{}}'
      if (this.uploader) {
        this.uploader.stopUpload()
        this.authProgress = 0
        this.statusText = ''
      }
      this.uploader = this.createUploader()
      this.uploader.addFile(this.file, null, null, null, userData)
      this.uploadDisabled = false
      this.pauseDisabled = true
      this.resumeDisabled = true
    },
    authUpload() {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload()
        this.uploadDisabled = true
        this.pauseDisabled = false
      }
    },
    // 暂停上传
    pauseUpload() {
      if (this.uploader !== null) {
        this.uploader.stopUpload()
        this.resumeDisabled = false
        this.pauseDisabled = true
      }
    },
    // 恢复上传
    resumeUpload() {
      if (this.uploader !== null) {
        this.uploader.startUpload()
        this.resumeDisabled = true
        this.pauseDisabled = false
      }
    },
    createUploader(type) {
      const self = this
      // eslint-disable-next-line no-undef
      const uploader = new AliyunUpload.Vod({
        timeout: self.timeout || 60000,
        partSize: self.partSize || 1048576,
        parallel: self.parallel || 5,
        retryCount: self.retryCount || 3,
        retryDuration: self.retryDuration || 2,
        region: self.region,
        userId: self.userId,
        // 添加文件成功
        addFileSuccess(uploadInfo) {
          self.uploadDisabled = false
          self.resumeDisabled = false
          self.statusText = '添加文件成功, 等待上传...'
          // console.log('addFileSuccess: ' + uploadInfo.file.name)
        },
        // 开始上传
        onUploadstarted(uploadInfo) {
          // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
          // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
          // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
          // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
          // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
          // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
          if (!uploadInfo.videoId) {
            const createUrl = config.httpurl + 'audioOrVideo/createUploadVideo?Title=' + uploadInfo.file.name + '&FileName=' + uploadInfo.file.name
            axios.get(createUrl).then(({ data }) => {
              const uploadAuth = data.body.uploadAuth
              const uploadAddress = data.body.uploadAddress
              const videoId = data.body.videoId
              uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
            })

            self.statusText = '文件开始上传...'
            console.log('onUploadStarted:' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
          } else {
            // 如果videoId有值，根据videoId刷新上传凭证
            // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
            const refreshUrl = config.httpurl + 'audioOrVideo/refreshUploadVideo?Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
            axios.get(refreshUrl).then(({ data }) => {
              const uploadAuth = data.data.uploadAuth
              const uploadAddress = data.data.uploadAddress
              const videoId = data.data.videoId
              uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
            })
          }
        },
        // 文件上传成功
        onUploadSucceed(uploadInfo) {
          console.log('onUploadSucceed: ' + uploadInfo.file.name + ', endpoint:' + uploadInfo.endpoint + ', bucket:' + uploadInfo.bucket + ', object:' + uploadInfo.object)
          self.statusText = '文件上传成功!'

          self.uploadDisabled = true
          self.resumeDisabled = true
          self.form.videoId = uploadInfo.videoId
          self.saveInfo()
        },
        // 文件上传失败
        onUploadFailed(uploadInfo, code, message) {
          console.log('onUploadFailed: file:' + uploadInfo.file.name + ',code:' + code + ', message:' + message)
          self.statusText = '文件上传失败!'
        },
        // 取消文件上传
        onUploadCanceled(uploadInfo, code, message) {
          console.log('Canceled file: ' + uploadInfo.file.name + ', code: ' + code + ', message:' + message)
          self.statusText = '文件已暂停上传'
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress(uploadInfo, totalSize, progress) {
          console.log('onUploadProgress:file:' + uploadInfo.file.name + ', fileSize:' + totalSize + ', percent:' + Math.ceil(progress * 100) + '%')
          const progressPercent = Math.ceil(progress * 100)
          self.authProgress = progressPercent
          self.statusText = '文件上传中...'
          // const loading = self.$loading({
          //   lock: true,
          //   text: self.authProgress,
          //   spinner: 'el-icon-loading',
          //   background: 'rgba(0, 0, 0, 0.7)'
          // })
          // if (self.authProgress == 100) {
          //   loading.close()
          //   self.$message({
          //     message: '视频课件保存成功',
          //     type: 'success'
          //   })
          //   self.dialogFormEdit = false
          //   self.getList()
          // }
        },
        // 上传凭证超时
        onUploadTokenExpired(uploadInfo) {
          // 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时
          // 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth
          // 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth
          const refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
          axios.get(refreshUrl).then(({ data }) => {
            const uploadAuth = data.UploadAuth
            uploader.resumeUploadWithAuth(uploadAuth)
            console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
          })
          self.statusText = '文件超时...'
        },
        // 全部文件上传结束
        onUploadEnd(uploadInfo) {
          console.log('onUploadEnd: uploaded all the files')
          self.statusText = '文件上传完毕'
        }
      })
      return uploader
    }
  }
}

</script>
<style lang="scss">
  html{
    touch-action:none;
  }
  .hide .el-upload--picture-card {
    display: none;
  }

  .popContainer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999999;
 background: rgba(0, 0, 0, 0.6);
 .el-progress__text{
   color: #fff;
 }
 .progress_title{
   position: relative;
    top: 35%;
    color: #e8e8e8;
    left:44.7%;
    text-shadow:#000 1px 1px 2px
 }
  .progress {
    position: relative;
    top: 37%;
    color: #fff;
    left:46%;
    // margin: auto;
  }
}
</style>
