<template>
  <div class="app-warp">

    <div class="detail-structure">
      <el-page-header content="课程编辑" @back="goBack"/>

      <div class="detail-container">
        <div class="level-title">
          <h1>课程基本信息</h1>
        </div>
        <div class="course_form">
          <el-form ref="form" :rules="rules" :model="form" label-width="110px">
            <el-form-item label="课程名称" prop="CURRICULUMNAME">
              <el-input v-model="form.CURRICULUMNAME" maxlength="255" placeholder="这里输入课程名称..." title="课程名称"/>
            </el-form-item>
            <el-form-item label="培训类型" class="is-required">
              <div @click="dialogFormVisible = true">
                <el-input
                  v-model="trainAllName"
                  :readonly="true"
                  maxlength="255"
                  placeholder="这里输入培训类型..."
                  title="培训类型"/>
              </div>
            </el-form-item>
            <el-form-item label="课程描述" prop="CURRICULUMINTRODUCE">
              <el-input
                v-model="form.CURRICULUMINTRODUCE"
                rows="5"
                type="textarea"
                maxlength="255"
                placeholder="这里输入课程介绍..."
                title="课程介绍"/>
            </el-form-item>

            <el-form-item label="课程封面" class="is-required">
              <el-upload
                ref="upload"
                :limit="1"
                :file-list="fileList"
                :class="{hide:hideUpload}"
                :on-remove="handleRemove"
                :on-preview="handlePictureCardPreview"
                :on-change="beforeFileUpload"
                :auto-upload="false"
                class="avatar-uploader"
                action="#"
                accept=".jpg,.jpeg,.png"
                list-type="picture-card">
                <i class="el-icon-plus"/>
              </el-upload>
              <el-dialog :visible.sync="dialogVisible">
                <img :src="dialogImageUrl" width="100%" alt="">
              </el-dialog>
            </el-form-item>
          </el-form>
        </div>
        <div class="level-title">
          <h1>课程章节</h1>
        </div>
        <div class="course_warp">
          <div class="course_directory2">
            <div v-for="(item, i) in chapterListOutSide" :key="item.no" class="course_item">
              <div class="course_row">
                <div class="course_icon">
                  <i
                    v-if="item.nodes && item.nodes.length != 0 && item.iconDirection == '1'"
                    class="el-icon-caret-bottom"
                    @click="changeIcon(item,'2')"/>
                  <i v-else-if="item.iconDirection == '2'" class="el-icon-caret-right" @click="changeIcon(item,'1')"/>
                </div>
                <div class="course_number">{{ i + 1 }}</div>
                <div class="course_play">
                  <i v-if="item.VIDEOCOURSEWARE_ID" class="el-icon-video-camera"/>
                </div>
                <div class="course_input">
                  <el-input
                    v-if="item.showNameInput"
                    v-model="item.NAME"
                    maxlength="255"
                    size="mini"
                    @blur="inputBulr(item)"/>
                  <template v-else>{{ item.NAME }}</template>
                </div>

                <div v-if="item.VIDEOCOURSEWARE_ID">
                  <el-button size="mini" @click="goViewVideo(item.VIDEOCOURSEWARE_ID)">预览</el-button>
                </div>
              </div>
              <div
                v-for="(children, j) in item.nodes"
                :key="children.no"
                class="course_subrow">
                <div class="course_icon">
                  <!-- <i class="el-icon-caret-bottom"/> -->
                </div>
                <div class="course_number">{{ i + 1 }}-{{ j + 1 }}</div>
                <div class="course_play">
                  <i v-if="children.VIDEOCOURSEWARE_ID" class="el-icon-video-camera"/>
                </div>
                <div class="course_input">
                  <el-input
                    v-if="children.showNameInput"
                    v-model="children.NAME"
                    maxlength="255"
                    size="mini"
                    @blur="inputBulr(children)"/>
                  <template v-else>{{ children.NAME }}</template>
                </div>
                <div v-if="children.VIDEOCOURSEWARE_ID">
                  <el-button size="mini" @click="goViewVideo(children.VIDEOCOURSEWARE_ID)">预览</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="level-title">
          <h1>是否上下架</h1>
        </div>
        <el-form>
          <el-form-item label=" " class="is-required" prop="ISSELL">
            <el-radio-group v-model="form.ISSELL" disabled>
              <el-radio label="1">上架</el-radio>
              <el-radio label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="level-title">
          <h1>课程属性</h1>
        </div>
        <el-form>
          <el-form-item label=" " class="is-required" prop = "COLLECTIVE">
            <el-radio-group v-model="form.COLLECTIVE" disabled>
              <el-radio :label="0">平台通用</el-radio>
              <el-radio :label="1">机构专用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="detail_foot">
          <el-button type="primary" @click="confirm">编辑课程</el-button>
          <el-button type="warning" @click="saveCache">保存至草稿箱</el-button>
          <el-button icon="el-icon-arrow-left" @click="goBack">返回</el-button>
        </div>
      </div>
    </div>
    <el-dialog :visible.sync="dialogFormVisible" title="培训类型" top="80px" width="1040px">
      <el-form :model="form" class="appformwith">
        <div class="type_field_box">
          <div class="type_field_item">
            <div class="type_field_top">培训类型</div>
            <div class="type_field_content type_pa">
              <div
                v-for="(item,i) in trainingList"
                :key="i"
                :class="TRAINTYPE == item.TRAININGTYPE_ID?'type_li_active':''"
                class="type_li"
                @click="checkTrain(item)">
                {{ item.NAME }}
              </div>
            </div>
          </div>
          <div class="type_field_item" style="width:320px">
            <div class="type_field_top">行业类型</div>
            <div class="type_field_content m-scroll-style">

              <div class="type_field_search">
                <el-input
                  v-model="filterText"
                  placeholder="请输入关键字进行过滤..."
                  prefix-icon="el-icon-search"
                  size="mini"
                  clearable/>
              </div>
              <el-tree
                v-loading="treeLoading"
                ref="tree"
                :data="industryTreeData"
                :props="industryProps"
                :check-on-click-node="true"
                :filter-node-method="filterNode"
                :node-key = "industryProps.value"
                :check-strictly="true"
                highlight-current="true"
                class="type_tree"
                @check="treeCheck"
                @node-click="handleNodeClick"/>
            </div>
          </div>
          <div class="type_field_item">
            <div class="type_field_top">岗位类型</div>
            <div class="type_field_content type_pa">
              <div
                v-for="(item,i) in postList"
                :key="i"
                :class="POSTTYPE == item.POSTTYPE_ID?'type_li_active':''"
                class="type_li"
                @click="checkPost(item)">
                {{ item.NAME }}
              </div>
            </div>
          </div>
          <div class="type_field_item">
            <div class="type_field_top">培训级别</div>
            <div class="type_field_content type_pa">
              <div
                v-for="(item,i) in trainLevelList"
                :key="i"
                :class="TRAINLEVEL === item.TRAINLEVEL_ID?'type_li_active':''"
                class="type_li"
                @click="checkTrainLevel(item)">
                {{ item.NAME }}
              </div>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="selectIndustry">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog v-if="dialogCoursewareShow" :visible.sync="dialogCoursewareShow" title="选择课件" width="90%" top="50px">
      <div style="height: 600px">
        <el-row :gutter="20">
          <div style="height: 600px">
            <el-row :gutter="20">
              <el-col :span="15">
                <el-form :model="videoMap" label-width="75px">
                  <el-row>
                    <el-col :span="12" style="display: flex;">
                      <el-form-item label="课件名称" prop="KEYWORDS">
                        <el-input v-model="videoMap.KEYWORDS" placeholder="请输入课件名称"/>
                      </el-form-item>
                      <div style="margin-left: 14px;">
                        <el-button v-waves type="primary" icon="el-icon-search" @click="getVideoList">搜索</el-button>
                        <el-button v-waves type="success" icon="el-icon-refresh" @click="getCourseReset('1')"> 重置</el-button>
                      </div>
                    </el-col>
                  </el-row>
                </el-form>
                <!--          课件名称、岗位培训类型-->
                <el-table
                  v-loading="listLoading"
                  ref="multipleVideoTable"
                  :data="videoMap.list"
                  :row-key="getRowKeyByVideoTable"
                  :header-cell-style="{ 'font-weight': 'bold','color': '#000' ,'background':'#f5f7fa'}"
                  tooltip-effect="dark"
                  border
                  fit
                  highlight-current-row>
                  <el-table-column
                    :reserve-selection="true"
                    type="selection"
                    width="55"
                    align="center"/>
                  <!--                  <el-table-column v-show="addCouType === 'radio'" width="35" align="center">-->
                  <!--                    <template slot-scope="{row}">-->
                  <!--                      <el-radio v-model="videoCheck" :label="row.VIDEOCOURSEWARE_ID">-->
                  <!--                        <span style="display:none;">占位符</span>-->
                  <!--                      </el-radio>-->
                  <!--                    </template>-->
                  <!--                  </el-table-column>-->
                  <el-table-column type="index" label="序号" width="50" align="center"/>
                  <el-table-column prop="COURSEWARENAME" label="课程名称"/>
                  <el-table-column prop="POSTTYPE_NAME" label="岗位"/>
                  <el-table-column prop="INDUSTRY_END_NAME" label="行业类型"/>
                  <el-table-column prop="TRAININGTYPE_NAME" label="课件类型"/>
                  <el-table-column prop="TEACHERNAME" label="讲师"/>
                  <el-table-column prop="CLASSHOUR" label="课件学时"/>
                  <el-table-column prop="RELATEDTERMNAME" label="相关词条"/>
                </el-table>
                <div class="page-btn-group">
                  <div/>
                  <pagination
                    :total="videoMap.total"
                    :page.sync="videoMap.page"
                    :limit.sync="videoMap.limit"
                    @pagination="getVideoList"/>
                </div>
              </el-col>
              <el-col :span="9">

                <div class="overflow">
                  <div class="level-title">
                    <h1>课程章节</h1>
                  </div>
                  <div class="course_warp">
                    <div>
                      <el-button type="primary" @click="changeCatLevel('1',2)">
                        <svg-icon class-name="directoryo-icon" icon-class="directoryo"/>
                        一级目录样式
                      </el-button>
                      <el-button type="primary" @click="changeCatLevel('2',2)">
                        <svg-icon class-name="directoryt-icon" icon-class="directoryt"/>
                        二级目录样式
                      </el-button>
                    </div>

                    <div class="course_directory2">
                      <div v-for="(item, i) in chapterList" :key="item.no" class="course_item">
                        <div class="course_row">
                          <div class="course_icon">
                            <i
                              v-if="item.nodes && item.nodes.length != 0 && item.iconDirection == '1'"
                              class="el-icon-caret-bottom"
                              @click="changeIcon(item,'2')"/>
                            <i v-else-if="item.iconDirection == '2'" class="el-icon-caret-right" @click="changeIcon(item,'1')"/>
                          </div>
                          <div class="course_number">{{ i + 1 }}</div>
                          <div class="course_play">
                            <i v-if="item.VIDEOCOURSEWARE_ID" class="el-icon-video-camera"/>
                          </div>
                          <div class="course_input">
                            <el-input
                              v-if="item.showNameInput"
                              :value="item.NAME"
                              maxlength="255"
                              size="mini"
                              @input="(event)=>{item.NAME=event;$forceUpdate()}"
                              @blur="inputBulr(item)"/>
                            <template v-else>{{ item.NAME }}</template>
                          </div>
                          <div>
                            <el-button size="mini" @click="deleteChapter(i)">删除</el-button>
                          </div>
                          <div>
                            <el-button :disabled="item.showNameInput" size="mini" @click="rename(item)">重命名</el-button>
                          </div>
                          <div v-if="form.CATALOGUELEVEL == '2'">
                            <el-button :disabled="item.showNameInput" size="mini" @click="underChapter('multiple',{index1:i})">保存课件到此章节下
                            </el-button>
                          </div>
                          <div v-if="item.VIDEOCOURSEWARE_ID">
                            <el-button size="mini" @click="goViewVideo(item.VIDEOCOURSEWARE_ID)">预览</el-button>
                          </div>
                        </div>
                        <div
                          v-for="(children, j) in item.nodes"
                          v-show="item.iconDirection == '1'"
                          :key="children.no"
                          class="course_subrow">
                          <div class="course_icon">
                            <!-- <i class="el-icon-caret-bottom"/> -->
                          </div>
                          <div class="course_number">{{ i + 1 }}-{{ j + 1 }}</div>
                          <div class="course_play">
                            <i v-if="children.VIDEOCOURSEWARE_ID" class="el-icon-video-camera"/>
                          </div>
                          <div class="course_input">
                            <el-input
                              v-if="children.showNameInput"
                              :value="children.NAME"
                              maxlength="255"
                              size="mini"
                              @input="(event)=>{children.NAME=event;$forceUpdate()}"
                              @blur="inputBulr(children)"/>
                            <template v-else>{{ children.NAME }}</template>
                          </div>
                          <div>
                            <el-button size="mini" @click="deleteChapter(j, item)">删除</el-button>
                          </div>
                          <div>
                            <el-button :disabled="children.showNameInput" size="mini" @click="rename(children)">重命名</el-button>
                          </div>
                          <div v-if="children.VIDEOCOURSEWARE_ID">
                            <el-button size="mini" @click="goViewVideo(children.VIDEOCOURSEWARE_ID)">预览</el-button>
                          </div>
                        </div>
                      </div>
                    </div>
                    <div style="margin-top: 5px">
                      <el-button
                        v-if="form.CATALOGUELEVEL == '1'"
                        :disabled="addFirstChapterFlag"
                        type="primary"
                        icon="el-icon-plus"
                        round
                        size="mini"
                        @click="underChapter">保存课件到此章节下
                      </el-button>
                      <el-button
                        v-if="form.CATALOGUELEVEL == '2'"
                        :disabled="addFirstChapterFlag"
                        type="primary"
                        icon="el-icon-plus"
                        round
                        size="mini"
                        @click="addFirstChapter()">新增一级项
                      </el-button>
                    </div>
                  </div>
                </div>
              </el-col>
            </el-row>
        </div></el-row>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCoursewareShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmByCou">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogViewVideo" title="预览" width="800px" @close="player.dispose()">
      <div id="aLiVideoPlayer" class="prism-player"/>
    </el-dialog>
    <!--外部编课修改内容的 dialog-->
    <el-dialog v-if="updCurricuLum" :visible.sync="updCurricuLum" title="选择课件" width="90%" top="50px">
      <el-form :model="videoMap" label-width="100px">
        <el-row>
          <el-col :span="6">
            <el-form-item label="课件名称" prop="KEYWORDS">
              <el-input v-model="videoMap.KEYWORDS" placeholder="请输入课件名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="讲师" prop="teacherKey">
              <el-input v-model="videoMap.teacherKey" placeholder="请输入讲师"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训类型" prop="TRAINTYPE">
              <el-select v-model="videoMap.TRAINTYPE" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in dicListMap.trainDicList"
                  :key="item.TRAININGTYPE_ID"
                  :label="item.NAME"
                  :value="item.TRAININGTYPE_ID"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="行业类型" prop="INDUSTRY">
              <SelectTree
                ref="keyIndTypeRef"
                :options="industryTreeData"
                :props="industryProps"
                v-model="videoMap.INDUSTRY"
                style="width: 100%;"
                placeholder="请选择培训行业类型"/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="岗位类型" prop="POSTTYPE">
              <el-select v-model="videoMap.POSTTYPE" placeholder="请选择" style="width: 100%;">
                <el-option
                  v-for="item in dicListMap.postDicList"
                  :key="item.POSTTYPE_ID"
                  :label="item.NAME"
                  :value="item.POSTTYPE_ID"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="相关词条" prop="teacherKey">
              <SelectTree
                ref="relatedtermRef"
                :options="dicListMap.relatedTermList"
                :props="{ multiple: true,value: 'id', children: 'nodes', label: 'name' }"
                v-model="videoMap.RELATEDTERM"
                placeholder="请输入相关词条"
                filterable/>
                <!--              <SelectTree ref="trainingSectionRef" :options="dicListMap.trainingSectionList" :props="defaultProps" v-model="trainingSectionKey" placeholder="请选择培训板块类型" />-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label-width="10px">
              <el-button v-waves type="primary" icon="el-icon-search" @click="getVideoList">搜索</el-button>
              <el-button v-waves type="success" icon="el-icon-refresh" @click="getCourseReset('1')"> 重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!--          课件名称、岗位培训类型-->
      <el-table
        v-loading="listLoading"
        ref="multipleVideoTable2"
        :data="videoMap.list"
        :row-key="getRowKeyByVideoTable"
        :header-cell-style="{ 'font-weight': 'bold','color': '#000' }"
        tooltip-effect="dark"
        border
        fit
        highlight-current-row>
        <el-table-column
          v-if="addCouType === 'multiple'"
          :reserve-selection="true"
          type="selection"
          width="55"
          align="center"/>
        <el-table-column v-if="addCouType === 'radio'" width="35" align="center">
          <template slot-scope="{row}">
            <el-radio v-model="videoCheck" :label="row.VIDEOCOURSEWARE_ID">
              <span style="display:none;">占位符</span>
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" width="50" align="center"/>
        <el-table-column prop="COURSEWARENAME" label="课程名称"/>
        <el-table-column prop="POSTTYPE_NAME" label="岗位"/>
        <el-table-column prop="INDUSTRY_END_NAME" label="行业类型"/>
        <el-table-column prop="TRAININGTYPE_NAME" label="课件类型"/>
        <el-table-column prop="TEACHERNAME" label="讲师"/>
        <el-table-column prop="CLASSHOUR" label="课件学时"/>
        <el-table-column prop="RELATEDTERMNAME" label="相关词条"/>
      </el-table>
      <pagination
        :total="videoMap.total"
        :page.sync="videoMap.page"
        :limit.sync="videoMap.limit"
        @pagination="getVideoList"/>
      <div slot="footer" class="dialog-footer">
        <el-button @click="updCurricuLum = false">取 消</el-button>
        <el-button type="primary" @click="confirmUpdCurriculum">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves'
import SelectTree from '@/components/SelectTree'
import { upload } from '../../../../utils/upload' // waves directive
export default {
  components: { Pagination, SelectTree },
  directives: { waves },
  data() {
    return {
      listLoading: false,
      dialogType: 'add',
      config: config,
      // 行业类型树
      treeLoading: false,
      industryTreeData: [],
      industryProps: {
        value: 'INDUSTRYTYPE_ID',
        children: 'nodes',
        label: 'NAME'
      },
      trainAllName: '',
      dialogFormVisible: false,
      postList: [],
      trainingList: [],
      trainLevelList: [],
      initFlag: false,
      TRAINLEVEL: '',
      TRAINLEVEL_NAME: '',
      TRAINTYPE: '',
      POSTTYPE: '',
      POSTTYPE_NAME: '',
      TRAINTYPE_NAME: '',
      INDUSTRY1: '',
      INDUSTRY2: '',
      INDUSTRY_LAST: '',
      INDUSTRY_LAST_NAME: '',
      filterText: '',
      dialogCoursewareShow: false,
      updCurricuLum: false,
      fileList: [],
      rules: {
        CURRICULUMNAME: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
        CURRICULUMINTRODUCE: [{ required: true, message: '课程描述不能为空', trigger: 'blur' }],
        COLLECTIVE: [{ required: true, message: '课程属性不能为空', trigger: 'blur' }],
        ISSELL: [{ required: true, message: '请选择是否上下架', trigger: 'blur' }]
      },
      form: {
        CURRICULUMNAME: '', // 课件名称
        CURRICULUMINTRODUCE: '', // 课件介绍
        INDUSTRY_ALL_TYPE: [], // 行业类型id
        INDUSTRY_ALL_NAME: [], // 行业名字
        TRAINTYPE: '',
        POSTTYPE: '',
        POSTTYPE_NAME: '',
        TRAINTYPE_NAME: '',
        INDUSTRY_LAST: '',
        INDUSTRY_END_ID: '',
        VALID_DATE: '',
        INDUSTRY_LAST_NAME: '',
        CATALOGUELEVEL: '1',
        COLLECTIVE: 0,
        ISSELL: '0'
      },
      chapterList: [],
      chapterListOutSide: [],
      videoMap: { // 视频课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzVidoList: [],
        KEYWORDS: '',
        teacherKey: '',
        TRAINTYPE: '',
        POSTTYPE: '',
        RELATEDTERM: '',
        INDUSTRY: ''
      },
      dicListMap: {
        outlineDicList: [],
        trainDicList: [],
        postDicList: [],
        trainingSectionList: [],
        relatedTermList: [],
        industryTreeData: []
      },
      videoCheck: '',
      addFirstChapterFlag: false,
      addCouType: '',
      addCouObj: {},
      hideUpload: false,
      dialogImageUrl: '',
      dialogVisible: false,
      dialogViewVideo: false,
      player: {}
    }
  },
  watch: {

    'POSTTYPE': {
      handler(newVal, oldVal) {
        // if (!this.initFlag) {
        //   this.initFlag = true
        // }
        this.POSTTYPE = newVal
        this.getTrainLevelList()
      }
    },
    'videoMap.TRAINTYPE': {
      handler() {
        // this.videoMap.POSTTYPE = ''
        // this.videoMap.INDUSTRY = ''
        // this.$refs.keyIndTypeRef.clearHandle()
        // this.getPostList1()
        // this.dicListMap['trainLevelDicList'] = []
      }
    },
    'videoMap.POSTTYPE': {
      handler() {
        // this.videoMap.INDUSTRY = ''
        // this.$refs.keyIndTypeRef.clearHandle()
      }
    },
    'filterText': {
      handler(val) {
        this.$refs.tree.filter(val)
      }
    }
  },
  created() {
    this.getTrainingList()
    this.getTrainList()
    this.getTreeList()
    this.getPostList()
    this.getPostList1()
    this.getDicListByPID('4459d3ff36d1475d8b2266da959fcc44', 'relatedTermList') // 相关词条
    if (this.$parent.CURRICULUM_ID) {
      this.msg = 'edit'
      this.getData()
    }
  },
  methods: {
    // 课程暂存
    saveCache() {
      const loading = this.$loading({
        lock: true,
        text: '提交中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const formData = new FormData()
      Object.keys(this.form).map(key => {
        formData.append(key, this.form[key])
      })
      if (this.$refs.upload.uploadFiles.length > 0) {
        for (var i = 0; i < this.$refs.upload.uploadFiles.length; i++) {
          if (this.$refs.upload.uploadFiles[i]) {
            formData.append('FFILE', this.$refs.upload.uploadFiles[i].raw)
          }
        }
      }
      formData.append('chapterList', JSON.stringify(this.chapterListOutSide))
      upload('/curriculumCache/add', formData).then((data) => {
        loading.close()
        if (data.message) {
          this.$message({
            message: data.message,
            type: 'warning'
          })
        } else {
          this.$message({
            message: '暂存成功',
            type: 'success'
          })
          this.goBack()
        }
      }).catch((e) => {
        loading.close()
        this.$message({
          message: '暂存失败',
          type: 'error'
        })
      })
    },
    // 保存
    confirm() {
      if (this.$refs.upload.uploadFiles.length === 0) {
        this.$message.warning('请上传课程封面')
        return false
      }
      if (this.chapterListOutSide.length === 0) {
        this.$message.warning('课件内容不能为空')
        return false
      }
      if (this.form.CATALOGUELEVEL === '1') {
        for (let i = 0; i < this.chapterList.length; i++) {
          if (!this.chapterListOutSide[i].VIDEOCOURSEWARE_ID) {
            this.$message.warning('课件内容不能为空')
            return false
          }
        }
      } else {
        for (let i = 0; i < this.chapterListOutSide.length; i++) {
          for (let j = 0; j < this.chapterListOutSide[i].nodes.length; j++) {
            if (!this.chapterListOutSide[i].nodes[j].VIDEOCOURSEWARE_ID) {
              this.$message.warning('课件内容不能为空')
              return false
            }
          }
        }
      }
      if (!this.form.ISSELL) {
        this.$message.warning('请选择是否上下架')
        return false
      }
      this.$refs.form.validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          const formData = new FormData()
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          if (this.$refs.upload.uploadFiles.length > 0) {
            for (var i = 0; i < this.$refs.upload.uploadFiles.length; i++) {
              if (this.$refs.upload.uploadFiles[i]) {
                formData.append('FFILE', this.$refs.upload.uploadFiles[i].raw)
              }
            }
          }
          formData.append('chapterList', JSON.stringify(this.chapterListOutSide))
          formData.delete('INDUSTRY_ALL_NAME')
          formData.delete('INDUSTRY_ALL_TYPE')

          formData.append('INDUSTRY_ALL_NAME', this.form.INDUSTRY_ALL_NAME)
          formData.append('INDUSTRY_ALL_TYPE', this.form.INDUSTRY_ALL_TYPE)
          upload('/curriculum/edit', formData).then((data) => {
            loading.close()
            if (data.message) {
              this.$message({
                message: data.message,
                type: 'warning'
              })
            } else {
              this.$message({
                message: '操作成功',
                type: 'success'
              })
              this.goBack()
            }
          }).catch((e) => {
            loading.close()
            this.$message({
              message: '操作失败',
              type: 'error'
            })
          })
        } else {
          return false
        }
      })
    },
    getDicListByPID(pId, listName) {
      requestFN(
        '/dictionaries/listAllDictToParId',
        {
          parentId: pId
        }
      ).then((data) => {
        this.dicListMap[listName] = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
    },
    getData() {
      requestFN(
        '/curriculum/goEdit',
        { CURRICULUM_ID: this.$parent.CURRICULUM_ID }
      ).then((data) => {
        this.form = data.pd

        this.dialogImageUrl = this.config.fileUrl + data.pd.COVERPATH
        if (data.pd.COVERPATH) {
          this.hideUpload = true
        }
        this.fileList.push({ name: '1', url: this.dialogImageUrl })
        this.trainAllName = data.pd.TYPENAME
        this.chapterListOutSide = data.chapterList
        this.$nextTick(() => {
          this.$forceUpdate()
        })
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 保存课件到此章节下
    underChapter(addCouType, addCouObj) {
      if (!this.$refs.multipleVideoTable.selection.length > 0) {
        this.$message.warning('请选择章节')
        return
      }
      this.addCouType = addCouType
      this.addCouObj = addCouObj
      this.confirmByCouInside()
      this.$refs.multipleVideoTable.clearSelection()
    },
    // 保存课件到此章节下
    underSecondLevelChapter(addCouObj) {
      if (!this.$refs.multipleVideoTable.selection.length > 0) {
        this.$message.warning('请选择章节')
        return
      }
      this.addCouObj = addCouObj
      this.confirmByCouInside()
    },
    addFirstChapter(OUTSIDE) {
      var firstChapter = {
        VIDEOCOURSEWARE_ID: '',
        NAME: '',
        showNameInput: true,
        SORT: this.chapterList.length + 1,
        iconDirection: '1',
        nodes: []
      }
      this.addFirstChapterFlag = true
      if (OUTSIDE) {
        this.chapterListOutSide.push(firstChapter)
      } else {
        this.chapterList.push(firstChapter)
      }
    },
    addSecondChapter(item) {
      var secondChapter = {
        VIDEOCOURSEWARE_ID: '',
        NAME: '',
        showNameInput: true,
        SORT: item.nodes.length + 1,
        nodes: []
      }
      item.nodes.push(secondChapter)
    },
    changeIcon(item, type) {
      item.iconDirection = type
    },
    inputBulr(item) {
      if (item.NAME) {
        setTimeout(() => {
          this.addFirstChapterFlag = false
          item.showNameInput = false
          this.$forceUpdate()
        }, 200)
      }
    },
    rename(item) {
      item.showNameInput = true
      this.$forceUpdate()
    },
    addCou(addCouType, addCouObj, updOrBacthAdd) {
      this.resetVideoAndDataMap()
      this.getVideoList()
      this.videoCheck = ''
      if (updOrBacthAdd == 1) {
        this.updCurricuLum = true
      } else {
        this.dialogCoursewareShow = true
      }
      this.addCouType = addCouType
      this.addCouObj = addCouObj
      this.chapterList = JSON.parse(JSON.stringify(this.chapterListOutSide))
    },
    getRowKeyByVideoTable(row) {
      return row.VIDEOCOURSEWARE_ID
    },
    resetVideoAndDataMap() {
      this.videoMap = { // 视频课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzVidoList: [],
        KEYWORDS: '',
        teacherKey: '',
        TRAINTYPE: '',
        POSTTYPE: '',
        RELATEDTERM: '',
        INDUSTRY: ''
      }
    },
    confirmByCou() {
      this.chapterListOutSide = JSON.parse(JSON.stringify(this.chapterList))
      this.dialogCoursewareShow = false
      this.$forceUpdate()
    },
    // 修改内容的确认
    confirmUpdCurriculum() {
      const chapterList = JSON.parse(JSON.stringify(this.chapterListOutSide))
      // eslint-disable-next-line no-unused-vars
      let expandChapterList = []
      if (this.addCouType === 'radio') {
        // 单选
        if (this.form.CATALOGUELEVEL === '2') {
          // 二级目录
          for (let i = 0; i < chapterList.length; i++) {
            expandChapterList.push(...chapterList[i].nodes)
          }
          for (let i = 0; i < expandChapterList.length; i++) {
            if (expandChapterList[i].VIDEOCOURSEWARE_ID === this.videoCheck) {
              this.$message.error('课件名称不能重复')
              return
            }
          }
          this.chapterListOutSide[this.addCouObj.index1].nodes[this.addCouObj.index2].VIDEOCOURSEWARE_ID = this.videoCheck
        } else {
          // 一级目录
          expandChapterList = [...chapterList]
          for (let i = 0; i < expandChapterList.length; i++) {
            if (expandChapterList[i].VIDEOCOURSEWARE_ID === this.videoCheck) {
              this.$message.error('课件名称不能重复')
              return
            }
          }
          this.chapterListOutSide[this.addCouObj.index1].VIDEOCOURSEWARE_ID = this.videoCheck
        }
      } else {
        // 多选
        const selection = this.$refs.multipleVideoTable.selection
        for (let i = 0; i < selection.length; i++) {
          selection[i].NAME = selection[i].COURSEWARENAME
        }
        if (this.form.CATALOGUELEVEL === '1') {
          // 一级目录
          expandChapterList = [...selection, ...this.chapterList]
          for (let i = 0; i < expandChapterList.length; i++) {
            for (let j = 1; j < expandChapterList.length; j++) {
              if (i !== j && expandChapterList[i].VIDEOCOURSEWARE_ID === expandChapterList[j].VIDEOCOURSEWARE_ID) {
                this.$message.error('课件名称不能重复')
                return
              }
            }
          }
          this.chapterListOutSide = [...this.chapterListOutSide, ...selection]
        } else {
          // 二级目录
          expandChapterList = [...selection]
          for (let i = 0; i < chapterList.length; i++) {
            expandChapterList.push(...chapterList[i].nodes)
          }
          for (let i = 0; i < expandChapterList.length; i++) {
            for (let j = 1; j < expandChapterList.length; j++) {
              if (i !== j && expandChapterList[i].VIDEOCOURSEWARE_ID === expandChapterList[j].VIDEOCOURSEWARE_ID) {
                this.$message.error('课件名称不能重复')
                return
              }
            }
          }
          this.chapterListOutSide[this.addCouObj.index1].nodes = [...this.chapterListOutSide[this.addCouObj.index1].nodes, ...selection]
        }
      }
      this.$nextTick(() => {
        this.$message.success('操作成功')
        this.updCurricuLum = false
        this.$forceUpdate()
      })
    },
    // 批量课件的确认
    confirmByCouInside() {
      const chapterList = JSON.parse(JSON.stringify(this.chapterList))
      // eslint-disable-next-line no-unused-vars
      let expandChapterList = []
      if (this.addCouType === 'radio') {
        // 单选
        if (this.form.CATALOGUELEVEL === '2') {
          // 二级目录
          for (let i = 0; i < chapterList.length; i++) {
            expandChapterList.push(...chapterList[i].nodes)
          }
          for (let i = 0; i < expandChapterList.length; i++) {
            if (expandChapterList[i].VIDEOCOURSEWARE_ID === this.videoCheck) {
              this.$message.error('课件名称不能重复')
              return
            }
          }
          this.chapterList[this.addCouObj.index1].nodes[this.addCouObj.index2].VIDEOCOURSEWARE_ID = this.videoCheck
        } else {
          // 一级目录
          expandChapterList = [...chapterList]
          for (let i = 0; i < expandChapterList.length; i++) {
            if (expandChapterList[i].VIDEOCOURSEWARE_ID === this.videoCheck) {
              this.$message.error('课件名称不能重复')
              return
            }
          }
          this.chapterList[this.addCouObj.index1].VIDEOCOURSEWARE_ID = this.videoCheck
        }
      } else {
        // 多选
        const selection = this.$refs.multipleVideoTable.selection
        for (let i = 0; i < selection.length; i++) {
          selection[i].NAME = selection[i].COURSEWARENAME
        }
        if (this.form.CATALOGUELEVEL === '1') {
          // 一级目录
          expandChapterList = [...selection, ...this.chapterList]
          for (let i = 0; i < expandChapterList.length; i++) {
            for (let j = 1; j < expandChapterList.length; j++) {
              if (i !== j && expandChapterList[i].VIDEOCOURSEWARE_ID === expandChapterList[j].VIDEOCOURSEWARE_ID) {
                this.$message.error('课件名称不能重复')
                return
              }
            }
          }
          this.chapterList = [...this.chapterList, ...selection]
        } else {
          // 二级目录
          expandChapterList = [...selection]
          for (let i = 0; i < chapterList.length; i++) {
            expandChapterList.push(...chapterList[i].nodes)
          }
          for (let i = 0; i < expandChapterList.length; i++) {
            for (let j = 1; j < expandChapterList.length; j++) {
              if (i !== j && expandChapterList[i].VIDEOCOURSEWARE_ID === expandChapterList[j].VIDEOCOURSEWARE_ID) {
                this.$message.error('课件名称不能重复')
                return
              }
            }
          }
          this.chapterList[this.addCouObj.index1].nodes = [...this.chapterList[this.addCouObj.index1].nodes, ...selection]
        }
      }
      this.$nextTick(() => {
        this.$message.success('操作成功')
        // this.dialogCoursewareShow = false
        this.$forceUpdate()
      })
    },
    deleteChapter(index, item) {
      let message = ''
      let title = ''
      if (item) {
        message = '你确定删除该二级项及关联的所有课件和试卷？'
        title = '删除二级项'
      } else {
        message = '你确定删除该一级项及下面所有二级项内容？'
        title = '删除一级项'
      }
      this.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (item) {
          item.nodes.splice(index, 1)
        } else {
          this.chapterList.splice(index, 1)
        }
        this.addFirstChapterFlag = false
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    deleteChapterOutSide(index, item) {
      let message = ''
      let title = ''
      if (item) {
        message = '你确定删除该二级项及关联的所有课件和试卷？'
        title = '删除二级项'
      } else {
        message = '你确定删除该一级项及下面所有二级项内容？'
        title = '删除一级项'
      }
      this.$confirm(message, title, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (item) {
          item.nodes.splice(index, 1)
        } else {
          this.chapterListOutSide.splice(index, 1)
        }
        this.addFirstChapterFlag = false
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    getVideoList() { // 获取视频课件 videoMap.tarinTypeID
      this.listLoading = true
      requestFN(
        '/videocourseware/list?showCount=' + this.videoMap.limit + '&currentPage=' + this.videoMap.page,
        {
          KEYWORDS: this.videoMap.KEYWORDS,
          teacherKey: this.videoMap.teacherKey,
          TRAINTYPE: this.videoMap.TRAINTYPE,
          POSTTYPE: this.videoMap.POSTTYPE,
          RELATEDTERM: this.videoMap.RELATEDTERM,
          INDUSTRY_END_ID: this.videoMap.INDUSTRY,
          CANUSE: '1',
          STATE: '0',
          ISCOMPLETE: '1'
        }
      ).then((data) => {
        this.listLoading = false
        this.videoMap.list = data.varList
        this.videoMap.total = data.page.totalResult
      }).catch((e) => {
      })
    },
    getCourseReset(type) { // 视频课件和资料课件的条件重置
      // this.$refs.keyIndTypeRef.clearHandle()
      // this.$refs.relatedtermRef.clearHandle()

      this.videoMap = { // 视频课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzVidoList: [],
        KEYWORDS: '',
        teacherKey: '',
        TRAINTYPE: '',
        POSTTYPE: '',
        RELATEDTERM: '',
        INDUSTRY: ''
      }
      this.getVideoList()
    },
    selectIndustry() {
      if (!this.POSTTYPE) {
        this.$message.warning('岗位类型必选')
        return
      }
      if (!this.TRAINTYPE) {
        this.$message.warning('培训类型必选')
        return
      }
      if (!this.TRAINLEVEL) {
        if (this.trainLevelList.length > 0) {
          this.$message.warning('培训级别必选')
          return
        }
      }
      if (!this.INDUSTRY_LAST) {
        this.$message.warning('行业类型必选')
        return false
      }
      this.form.TRAINTYPE = this.TRAINTYPE
      this.form.TRAINTYPE_NAME = this.TRAINTYPE_NAME
      this.form.TRAINLEVEL = this.TRAINLEVEL
      this.form.TRAINLEVEL_NAME = this.TRAINLEVEL_NAME
      this.form.POSTTYPE = this.POSTTYPE
      this.form.POSTTYPE_NAME = this.POSTTYPE_NAME
      this.form.INDUSTRY_END_ID = this.INDUSTRY_LAST
      this.form.INDUSTRY_LAST_NAME = this.INDUSTRY_LAST_NAME

      var pn = this.form.POSTTYPE_NAME ? '-' + this.form.POSTTYPE_NAME : ''
      var iname = this.form.INDUSTRY_LAST_NAME ? '-' + this.form.INDUSTRY_LAST_NAME : ''
      var tlName = this.form.TRAINLEVEL_NAME ? '-' + this.form.TRAINLEVEL_NAME : ''
      this.trainAllName = this.form.TRAINTYPE_NAME + iname + pn + tlName
      this.dialogFormVisible = false
    },
    treeCheck(data, list) {
      let thisNode = this.$refs.tree.getNode(data) // 获取当前节点
      this.form.INDUSTRY_ALL_TYPE = []
      this.form.INDUSTRY_ALL_NAME = []
      const keys = [] // 获取已勾选节点的key值
      const names = [] // 获取已勾选节点的key值
      keys.unshift(thisNode.data.INDUSTRYTYPE_ID)
      names.unshift(thisNode.data.NAME)
      if (thisNode.checked) { // 当前节点若被选中
        for (let i = thisNode.level; i > 1; i--) {
          // 当前子节点选中，取消勾选父节点
          this.$refs.tree.setChecked(thisNode.parent, false)
          // 判断是否有父级节点
          if (!thisNode.parent.checked) { // 父级节点未被选中，则将父节点替换成当前节点，往上继续查询，并将此节点key存入keys数组
            thisNode = thisNode.parent
            keys.unshift(thisNode.data.INDUSTRYTYPE_ID)
            names.unshift(thisNode.data.NAME)
          }
        }
      }
      this.form.INDUSTRY_ALL_TYPE = keys
      this.form.INDUSTRY_ALL_NAME = names
    },
    handleNodeClick(node, data, value) {
      this.INDUSTRY_LAST = node.INDUSTRYTYPE_ID
      this.INDUSTRY_LAST_NAME = node.NAME
      this.INDUSTRY_LEVEL = data.level
    },
    filterNode(value, data) {
      if (!value) return true
      return data.NAME.indexOf(value) !== -1
    },
    checkPost(item) {
      this.$set(this, 'POSTTYPE', item.POSTTYPE_ID)
      this.$set(this, 'POSTTYPE_NAME', item.NAME)
      this.$set(this, 'TRAINLEVEL_NAME', '')
      this.$set(this, 'TRAINLEVEL_ID', '')
      this.$set(this, 'TRAINLEVEL', '')
    },
    checkTrain(item) {
      this.$set(this, 'TRAINTYPE', item.TRAININGTYPE_ID)
      this.$set(this, 'TRAINTYPE_NAME', item.NAME)
    },
    checkTrainLevel(item) {
      this.$set(this, 'TRAINLEVEL', item.TRAINLEVEL_ID)
      this.$set(this, 'TRAINLEVEL_NAME', item.NAME)
    },
    // 培训类型
    getTrainingList() {
      requestFN(
        '/trainingtype/listAll',
        {}
      ).then((data) => {
        this.trainingList = data.varList
      }).catch((e) => {
      })
    },
    changeCatLevel(level, OUTSIDE) {
      if (this.form.CATALOGUELEVEL === level) return
      this.addFirstChapterFlag = false
      this.form.CATALOGUELEVEL = level
      if (OUTSIDE == 1) {
        this.chapterListOutSide = []
        this.$set(this, 'chapterListOutSide', [])
      }
      this.chapterList = []
      this.$set(this, 'chapterList', [])
    },
    // 岗位类型
    getPostList() {
      requestFN(
        '/posttype/listAll',
        {
        }
      ).then((data) => {
        this.postList = data.varList
      }).catch((e) => {
      })
    },
    // 行业类型树
    getTreeList() {
      this.treeLoading = true
      requestFN(
        '/industrytype/getIndustryTree'
      ).then((data) => {
        this.treeLoading = false
        this.industryTreeData = data.zTreeNodes
      }).catch((e) => {
        this.treeLoading = false
      })
    },
    // 岗位级别
    getTrainLevelList() {
      requestFN(
        '/trainleveltype/listAll',
        { POSTTYPE_ID: this.POSTTYPE }
      ).then((data) => {
        this.trainLevelList = data.varList
      }).catch((e) => {
      })
    },
    goBack() {
      this.$parent.activeName = 'refreshList'
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },
    handleRemove(file, fileList) {
      this.hideUpload = fileList.length >= 1
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    beforeFileUpload(file, fileList) {
      const types = ['image/jpeg', 'image/jpg', 'image/png']
      const isImage = types.includes(file.raw.type)
      if (!isImage) {
        this.$message.error('上传图片只能是 JPG、JPEG、PNG 格式!')
        fileList.pop()
      }
      this.hideUpload = fileList.length >= 1
    },
    getTrainList() {
      requestFN(
        '/trainingtype/listAll',
        {}
      ).then((data) => {
        this.dicListMap['trainDicList'] = data.varList
      }).catch((e) => {

      })
    },
    getPostList1() {
      requestFN(
        '/posttype/listAll',
        {
          TRAININGTYPE_ID: this.videoMap.TRAINTYPE
        }
      ).then((data) => {
        this.dicListMap['postDicList'] = data.varList
      }).catch((e) => {

      })
    },
    getIndTree() {
      if (this.videoMap.POSTTYPE) {
        requestFN(
          '/industrytype/getIndustryTree',
          { POSTTYPE_ID: this.videoMap.POSTTYPE }
        ).then((data) => {
          this.dicListMap['industryTreeData'] = data.zTreeNodes
        }).catch((e) => {
        })
      }
    },
    goViewVideo(VIDEOCOURSEWARE_ID) {
      requestFN(
        '/videocourseware/getVideoPlayInfo',
        {
          VIDEOCOURSEWARE_ID: VIDEOCOURSEWARE_ID
        }
      ).then((data) => {
        if (data.result == 'success') {
          this.dialogViewVideo = true
          this.$nextTick(() => {
            // 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) => {
      })
      // 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
    }
  }
}
</script>

<style lang="scss" scoped>
.table-ui {
  td {
    line-height: 34px;
  }

  .tbg {
    width: 200px;
  }

  .img-flex {
    display: flex;
  }

  .img-ui {
    width: 110px;
    height: 110px;
    margin-right: 20px;

    & img {
      width: 100%;
      height: 100%;
    }
  }
}
.overflow {
  height: 550px;
  overflow: scroll;
  overflow-x:hidden
}
</style>
