<template>
  <!--  新增课程-->
  <div class="app-warp">
    <div class="detail-structure">
      <el-page-header content="新增课程" @back="goBack"/>
      <div class="detail-container">
        <el-row :gutter="24">
          <el-col :span="15">
            <el-form ref="searchFrom" :model="searchFrom" label-width="70px">
              <el-row :gutter="12">
                <el-col :span="8">
                  <el-form-item label="课程名称">
                    <el-input v-model="searchFrom.KEYWORDS" placeholder="请输入课程名称"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="培训类型">
                    <el-input
                      v-model="searchFrom.trainAllName"
                      readonly
                      maxlength="255"
                      placeholder="这里输入培训类型..."
                      title="培训类型"
                      @click.native="dialogFormVisible = true"/>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-button v-waves type="primary" icon="el-icon-search" class="ml-10" @click="getList">
                    搜索
                  </el-button>
                  <el-button v-waves icon="el-icon-refresh" class="ml-10" @click="goKeyReset">
                    重置
                  </el-button>
                </el-col>
              </el-row>
            </el-form>
            <div class="app-container">
              <el-table
                v-loading="listLoading"
                :data="varList"
                :header-cell-style="{
                  background:'#f5f7fa',
                  'font-weight': 'bold',
                  'color': '#000'
                }"
                tooltip-effect="dark"
                border
                fit
                highlight-current-row>
                <el-table-column show-overflow-tooltip prop="CURRICULUMNAME" label="课程名称" fixed="left"/>
                <el-table-column show-overflow-tooltip prop="CLASSHOUR" label="学时"/>
                <el-table-column show-overflow-tooltip prop="TRAININGTYPE_NAME" label="培训类型"/>
                <el-table-column show-overflow-tooltip prop="INDUSTRY_ALL_NAME" label="行业类型"/>
                <el-table-column show-overflow-tooltip prop="POSTTYPE_NAME" label="岗位类型"/>
                <el-table-column show-overflow-tooltip prop="TRAINLEVEL_NAME" label="培训等级"/>
                <el-table-column label="操作" align="center" width="60" fixed="right">
                  <template slot-scope="{row}">
                    <span v-if="row.ISUSE=='1'" >已使用</span>
                    <el-button v-else type="text" @click="getLeftVideo(row.CURRICULUM_ID)">使用</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="page-btn-group">
                <div/>
                <pagination
                  :total="total"
                  :page.sync="listQuery.page"
                  :limit.sync="listQuery.limit"
                  @pagination="getList"/>
              </div>
            </div>
          </el-col>
          <el-col v-show="chapterList.length !== 0" :span="9">
            <div>
              <div class="level-title">
                <h1>总学时</h1>
              </div>
              <el-row class="font14" style="padding-left: 15px;">
                <el-col :span="12">所选课件总学时：<span>{{ countCLASSHOUR==0?countCLASSHOUR:countCLASSHOUR.toFixed(1) }}</span></el-col>
                <el-col :span="12">所选课件视频总时长：<span>{{ secondsCount(countVIDEOTIME) }}</span></el-col>
                <el-col :span="12" style="padding-top: 5px">课程总学时：<span>{{ pd.CLASSHOUR }}</span></el-col>
                <el-col :span="12" style="padding-top: 5px">课程视频总时长：<span>{{ secondsCount(pd.VIDEOTIME) }}</span></el-col>
              </el-row>
            </div>
            <div style="margin-top: 15px">
              <div class="level-title">
                <h1>章节编排</h1>
              </div>
              <div style="overflow-y: auto;height: 450px;">
                <div>
                  <!--                  <el-checkbox v-model="isSelectAll" @change="selectAll">-->
                  <!--                    {{ !isSelectAll ? '全选' : '全不选' }}-->
                  <!--                  </el-checkbox>-->
                  <el-button v-show="!isSelectAll" @click="selectAll(0)">全选</el-button>
                  <el-button v-show="isSelectAll" @click="selectAll(1)">全不选</el-button>
                </div>
                <el-tree
                  ref="chapterRef"
                  :data="chapterList"
                  :props="{children: 'nodes', label: 'COURSEWARENAME',id:'CHAPTER_ID'}"
                  node-key="CHAPTER_ID"
                  show-checkbox
                  class="course-management-tree"
                  default-expand-all
                  @check-change="handleCheckChange"
                >
                  <template slot-scope="{ node, data }">
                    <div style="flex:1;display:flex;justify-content: space-between;align-items: center">
                      <div style="flex:1;display:flex;justify-content: space-between;align-items: center;margin-right: 50px">
                        <div>
                          <i v-if="data.COURSEWARENAME" class="el-icon-video-camera"/>
                          <span>{{ data.NAME || data.COURSEWARENAME |ellipsis }}</span>
                        </div>
                        <div>
                          <span v-if="data.COURSEWARENAME" style="text-align: left">
                            课件时长：{{ secondsCount(data.VIDEOTIME) }}
                          </span>
                        </div>
                      </div>
                      <div>
                        <el-button
                          v-if="data.COURSEWARENAME"
                          type="primary"
                          size="mini"
                          @click="goViewVideo(data)">预览</el-button>
                      </div>
                    </div>
                  </template>
                </el-tree>
              </div>
            </div>
            <div style="text-align: center">
              <el-button type="primary" @click="confirm">保存</el-button>
              <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
            </div>
          </el-col>
          <el-col v-show="chapterList.length === 0" :span="9" style="text-align: center;padding-top: 100px;">
            暂无课程
          </el-col>
        </el-row>
      </div>
    </div>
    <el-dialog
      :visible.sync="dialogViewVideo"
      title="视频"
      width="800px"
      @close="player.dispose()">
      <div id="aLiVideoPlayer" class="prism-player"/>
    </el-dialog>
    <trainingTypeDialog :dialog-form-visible.sync="dialogFormVisible" @confirm="trainingTypeDialogConfirm"/>
  </div>
</template>

<script>
import trainingTypeDialog from '@/components/trainingTypeDialog'
import Pagination from '@/components/Pagination'
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves'

export default {
  components: {
    trainingTypeDialog, Pagination
  },
  directives: {
    waves
  },
  filters: {
    ellipsis(value) {
      if (!value) return ''
      if (value.length > 10) {
        return value.slice(0, 10) + '...'
      }
      return value
    }
  },
  data() {
    return {
      searchFrom: {
        KEYWORDS: '',
        trainAllName: ''
      },
      total: 0,
      listQuery: {
        page: 1,
        limit: 10
      },
      dialogFormVisible: false,
      listLoading: false,
      varList: [],
      totalTime: 0,
      chapterList: [],
      dialogViewVideo: false,
      player: {},
      checkedVideoList: [],
      pd: {},
      countCLASSHOUR: 0,
      countVIDEOTIME: 0,
      CURRICULUM_ID: '',
      isSelectAll: false
    }
  },
  inject: ['setActiveName', 'parentObj'],
  created() {
    this.getList()
  },
  methods: {
    getList() {
      requestFN('/curriculum/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page, {
        ...this.searchFrom,
        ISSELL: '1',
        CLASS_ID: this.parentObj.CLASS_ID
      }).then(res => {
        this.listLoading = false
        this.varList = res.varList
        this.total = res.page.totalResult
      })
    },
    trainingTypeDialogConfirm(e) {
      Object.keys(e).forEach(key => {
        this.$set(this.searchFrom, key, e[key])
      })
    },
    goKeyReset() {
      this.searchFrom.KEYWORDS = ''
      this.searchFrom.trainAllName = ''
      this.searchFrom.POSTTYPE = ''
      this.searchFrom.TRAINTYPE = ''
      this.searchFrom.INDUSTRY_END_ID = ''
      this.searchFrom.TRAINTYPE_NAME = ''
      this.searchFrom.POSTTYPE_NAME = ''
      this.searchFrom.TRAINLEVEL = ''
      this.searchFrom.TRAINLEVEL_NAME = ''
      this.searchFrom.INDUSTRY3 = ''
      this.searchFrom.INDUSTRY3_NAME = ''
      this.searchFrom.INDUSTRY_END_ID = ''
      this.searchFrom.INDUSTRY_END_NAME = ''
      this.getList()
    },
    getLeftVideo(CURRICULUM_ID) {
      requestFN('/platform/curriculum/goEdit', { CURRICULUM_ID }).then(res => {
        this.chapterList = res.chapterList
        this.pd = res.pd
        this.CURRICULUM_ID = CURRICULUM_ID

        this.checkedVideoList = []
        this.countCLASSHOUR = 0
        this.countVIDEOTIME = 0
        this.isSelectAll = false
      })
    },
    goViewVideo(row) {
      requestFN(
        '/platform/videocourseware/getPlayInfo',
        {
          VIDEOCOURSEWARE_ID: row.VIDEOCOURSEWARE_ID,
          CURRICULUM_ID: row.CURRICULUM_ID,
          VIDEOFILES: row.VIDEOFILES,
          DOMAIN_NAME: window.location.hostname
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.dialogViewVideo = true
          this.$nextTick(() => {
            if (this.player) {
              this.player = null
            }
            // eslint-disable-next-line no-undef
            this.player = new Aliplayer({
              id: 'aLiVideoPlayer',
              source: JSON.stringify(data.urlList),
              width: '100%',
              height: '500px',
              autoplay: true,
              isLive: false,
              components: [{
                name: 'QualityComponent',
                // eslint-disable-next-line no-undef
                type: AliPlayerComponent.QualityComponent,
                args: [function(definition, desc) {
                  console.log(definition + '-----' + desc)
                }]
              }]
            }, function(player) {
              console.log('The player is created')
              /* Register the sourceloaded of the player, query the resolution of the video, invoke the resolution component, and call the setCurrentQuality method to set the resolution. */
              player.on('sourceloaded', function(params) {
                var paramData = params.paramData
                var desc = paramData.desc
                var definition = paramData.definition
                player.getComponent('QualityComponent').setCurrentQuality(desc, definition)
              })
            })
          })
        } else {
          this.$message.warning(data.message)
        }
      }).catch((e) => {
      })
    },
    closePlay() {
      this.$refs.videoPlayer.player.pause()
    },
    secondsCount(second) {
      if (!second) return 0
      const h = parseInt(second / 60 / 60, 10)
      const m = parseInt(second / 60 % 60, 10)
      const s = parseInt(second % 60, 10)
      if (h) {
        return h + '小时' + m + '分钟' + s + '秒'
      } else {
        if (m) {
          return m + '分钟' + s + '秒'
        } else {
          return s + '秒'
        }
      }
    },
    selectAll(e) {
      if (e === 0) {
        this.isSelectAll = true
      } else {
        this.isSelectAll = false
      }
      if (this.isSelectAll) {
        this.$refs.chapterRef.setCheckedNodes(this.chapterList)
        this.$nextTick(() => {
          if (this.checkedVideoList.length == 0) {
            this.isSelectAll = false
          }
        })
      } else {
        this.$refs.chapterRef.setCheckedNodes([])
      }
    },
    handleCheckChange(data, checked, indeterminate) {
      if (data.disabled) {
        this.$refs.chapterRef.setChecked(data, false, false)
        return
      }
      if (data.VIDEOCOURSEWARE_ID) {
        if (checked) {
          this.checkedVideoList.push(data)
        } else {
          this.checkedVideoList.splice(this.checkedVideoList.findIndex(item => item.VIDEOCOURSEWARE_ID === data.VIDEOCOURSEWARE_ID), 1)
        }
        this.$nextTick(() => {
          this.countCLASSHOUR = this.checkedVideoList.reduce((total, item) => {
            return ((total + Number(item.CLASSHOUR) || 0) * 100) / 100
          }, 0)
          this.countVIDEOTIME = this.checkedVideoList.reduce((total, item) => {
            return total + Number(item.VIDEOTIME)
          }, 0)
        })
      }
    },
    confirm() {
      if (this.$refs.chapterRef.getHalfCheckedKeys().length === 0 && this.$refs.chapterRef.getCheckedKeys().length === 0) {
        this.$message.error('请选择课程')
        return
      }
      var s = this.$refs.chapterRef.getCheckedKeys().concat(this.$refs.chapterRef.getHalfCheckedKeys())
      requestFN('/classCurriculum/addClassCurriculum', {
        CLASS_ID: this.parentObj.CLASS_ID,
        CURRICULUM_ID: this.CURRICULUM_ID,
        ENTERPRISE_ID: this.parentObj.ENTERPRISE_ID,
        chapterList: s.toString()
      }).then(res => {
        this.$message.success('新增成功')
        this.goBack()
      })
    },
    goBack() {
      if (this.parentObj.TYPE === 'add') {
        this.setActiveName('CourseList')
      } else {
        this.setActiveName('ClassDetailsList')
      }
    }
  }
}
</script>

<style lang="scss">
.course-management-tree {
  font-size: 14px;

  .el-tree-node {
    padding: 3px 0;
  }
}
</style>
