<template>
  <div class="app-warp">
    <div class="app-structure">
      <div class="app-search">
        <el-form ref="searchFrom" :model="searchFrom" label-width="80px">
          <el-row>
            <el-col :span="6">
              <el-form-item label="课程名称" prop="CURRICULUM_NAME">
                <el-input v-model="searchFrom.CURRICULUM_NAME" placeholder="请输入课程名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-button v-waves type="primary" icon="el-icon-search" class="ml-10" @click="getQuery">
                搜索
              </el-button>
              <el-button icon="el-icon-refresh" @click="goKeyReset">
                重置
              </el-button>

            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-tools">
        <div class="app-function">
          <el-button type="primary" icon="el-icon-plus" @click="handleBatchAdd">批量添加</el-button>
          <!--          <el-button type="primary" icon="el-icon-refresh" @click="syncNow">立即更新</el-button>-->
        </div>
        <div class="app-minbtn">
          <span class="screening">
            <el-dropdown trigger="click">
              <el-button type="text" icon="el-icon-finished"/>
              <el-dropdown-menu slot="dropdown" style="margin-top:3px;">
                <div class="app-checkbox-group">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox v-for="item in checkboxList" :key="item" :label="item" style="display: block"/>
                  </el-checkbox-group>
                </div>
              </el-dropdown-menu>
            </el-dropdown>
          </span>
          <el-button type="text" icon="el-icon-refresh-left"/>
          <el-button type="text" icon="el-icon-full-screen"/>
        </div>
      </div>
      <div class="app-container">
        <el-table
          v-loading="listLoading"
          ref="multipleTable"
          :data="varList"
          :row-key="getRowKey"
          :header-cell-style="{
            background:'#f5f7fa',
            '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="CURRICULUM_NAME" label="课程名称" />
          <el-table-column v-if="checkList.includes('上传时间')" :show-overflow-tooltip="true" prop="CREATTIME" label="上传时间" />
          <el-table-column prop="VALID_DATE" label="有效时间" />
          <el-table-column v-if="checkList.includes('课件数')" prop="COURSEWARE_NUMBER" label="课件数" width="90" align="center" />
          <el-table-column v-if="checkList.includes('课程时长')" prop="VIDEOTIME" label="课程时长" width="140" align="center">
            <template slot-scope="{row}">
              {{ secondsCount(row.TIME) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="{row}">
              <el-button type="text" @click="handleShow(row.CURRICULUM_ID)">查看</el-button>
              <span class="app-divider"/>
              <el-button type="text" @click="syncCurriculum(row)">加入本地</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>
    </div>

    <el-dialog :visible.sync="dialogFormEdit" :title="dialogType==='edit'?'修改':'新增'" width="800px" top="60px" class="tree_dialog">
      <el-form ref="form" :rules="rules" :model="form" label-width="110px" style="width: 690px;margin:0 auto">
        <el-form-item label="课程名称" prop="CURRICULUMNAME">
          <el-input id="CURRICULUMNAME" ref="CURRICULUMNAME" v-model="form.CURRICULUMNAME" maxlength="255" placeholder="这里输入课程名称..." title="课程名称" />
        </el-form-item>
        <!--        <el-form-item label="培训行业类型" prop="TRAINTYPE">-->
        <!--          <SelectTree id="pxTreeByCur" ref="pxTreeByCur" :options="dicListMap.trainDicList" :props="defaultProps" v-model="form.TRAINTYPE" placeholder="请选择" />-->
        <!--        </el-form-item>-->
        <el-form-item label="培训板块" prop="trainingSection"><!-- 培训板块 -->
          <el-cascader
            :options="dicListMap.trainingSectionList"
            :props="{ multiple: true,value: 'id', children: 'nodes', label: 'name' }"
            v-model="form.trainingSection"
            placeholder="请输入培训板块"
            filterable/>
        </el-form-item>
        <el-form-item label="培训行业类型" prop="TRAINTYPE">
          <SelectTree ref="pxTree" :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" :options="dicListMap.postDicList" :props="defaultProps" v-model="form.POSTTYPE" placeholder="请选择岗位培训类型" />
        </el-form-item>
        <el-form-item v-if="dialogType=='edit' || dialogType=='inherit'" label="已上传课程图片">
          <div >
            <img :src="config.fileUrl + form.CAPTURE" width="100" height="100">
          </div>
        </el-form-item>
        <el-form-item label="课程图片" prop="hideUpload">
          <el-upload
            ref="upload"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-change="handleEditChange"
            :before-upload="beforeFileUpload"
            :auto-upload="false"
            :limit="1"
            :class="{hide:hideUpload}"
            action="#"
            accept=".jpg,.jpeg,.png"
            list-type="picture-card">
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="form.dialogVisible">
            <img :src="form.CAPTURE" width="100%" alt="">
          </el-dialog>
          <!--          <span v-if="form.VIDEOCAPTURE">{{ form.VIDEOCAPTURE.name }}</span>-->
          <!--          <el-upload :before-upload="beforeCaptureFileUpload" class="avatar-uploader" action="">-->
          <!--            <el-button type="primary">上传</el-button>-->
          <!--            <div slot="tip" class="el-upload__tip">只能上传jpeg、jpg、png文件</div>-->
          <!--          </el-upload>-->
        </el-form-item>
        <el-form-item label="课程介绍" prop="CURRICULUMINTRODUCE">
          <el-input id="CURRICULUMINTRODUCE" ref="CURRICULUMINTRODUCE" v-model="form.CURRICULUMINTRODUCE" type="textarea" maxlength="255" placeholder="这里输入课程介绍..." title="课程介绍" />
        </el-form-item>
        <el-form-item label="章节" prop="addkejianprop">
          <el-button type="primary" @click="addChapter">添加章节</el-button>
        </el-form-item>

        <div v-for="(data,index) in chapterList" :key="index">
          <el-form-item label="章节名称">
            <el-row>
              <el-col :span="12">
                <el-input ref="NAME" v-model="data.NAME" maxlength="255" placeholder="这里输入章节名称..." title="章节名称" />
              </el-col>
              <el-col :span="12">
                <el-button style="margin-left:20px" type="danger" @click="deleteChapter(index)">删除</el-button>
                <el-button type="primary" @click="selectCourseware(index)">批量添加课件</el-button>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item v-if="data.xzVidoList.length>0 || data.xzDataList.length>0" label="已经添加课件" prop="kejianList">
            <el-row>
              <!--                @click="delXzVidoList(index)" @click="delXzDataList(index)"-->
              <el-col :span="12">
                <el-table :data="data.xzVidoList" :summary-method="getSummaries" show-summary style="width: 95%" border>
                  <el-table-column prop="COURSEWARENAME" label="视频课件名称" />
                  <el-table-column prop="CLASSHOUR" label="学时(分钟)" width="60" align="center" />
                  <el-table-column prop="CLASSHOUR" label="操作" width="60" align="center">
                    <template slot-scope="scope">
                      <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="delXzVidoList(index,scope.$index)"/>
                    </template>
                  </el-table-column>
                </el-table>

              </el-col>
              <el-col :span="12">
                <el-table :data="data.xzDataList" :summary-method="getSummaries" show-summary style="width: 100%" border>
                  <el-table-column prop="COURSEWARENAME" label="资料课件名称" />
                  <el-table-column prop="CLASSHOUR" label="学时(分钟)" width="60" align="center"/>
                  <el-table-column prop="CLASSHOUR" label="操作" width="60" align="center" >
                    <template slot-scope="scope">
                      <el-button type="danger" icon="el-icon-delete" circle size="mini" @click="delXzDataList(index,scope.$index)"/>
                    </template>
                  </el-table-column>
                </el-table>
              </el-col>
            </el-row>
          </el-form-item>
        </div>

        <el-form-item label="课程总学时" prop="kejianList">
          <tr>
            <td >{{ curriculumZongji }}</td>
          </tr>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormEdit = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 选择课件 -->
    <el-dialog v-if="dialogCoursewareShow" :visible.sync="dialogCoursewareShow" title="选择课件" width="90%">
      <el-tabs v-model="activeName">
        <el-tab-pane label="视频课件" name="first">
          <div class="filter-container">
            <div class="filter-group">
              <div class="filter-lable">课件名称：</div>
              <el-input v-model="videoMap.KEYWORDS" placeholder="请输入课程名称或课程简介或课程目的" style="width: 200px;" />
            </div>
            <!--            <div class="filter-group">-->
            <!--              <div class="filter-lable">岗位培训类型：</div>-->
            <!--              <SelectTree ref="keyvidHyRef" :options="dicListMap.trainDicList" :props="defaultProps" v-model="videoMap.tarinTypeID" placeholder="请选择培训行业类型" style="width: 300px;" />-->
            <!--            </div>-->
            <el-button v-waves type="primary" icon="el-icon-search" @click="getVoidList"> 搜索 </el-button>
            <el-button v-waves type="success" icon="el-icon-refresh" @click="getCourseReset('1')"> 重置 </el-button>
          </div>
          <!--          课件名称、岗位培训类型-->
          <el-table v-loading="listLoading" ref="multipleVideoTable" :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 :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="课件名称" />
            <el-table-column prop="post_type_name" label="岗位培训类型" />
            <el-table-column prop="train_type_name" label="培训行业类型" />
            <el-table-column prop="CLASSHOUR" label="学时（分钟）" />
            <el-table-column prop="TEACHERNAME" label="讲师名称" />
          </el-table>
          <pagination :total="videoMap.total" :page.sync="videoMap.page" :limit.sync="videoMap.limit" @pagination="getVoidList" />
        </el-tab-pane>
        <el-tab-pane label="资料课件" name="second">
          <div class="filter-container">
            <div class="filter-group">
              <div class="filter-lable">课件名称：</div>
              <el-input v-model="dataMap.KEYWORDS" placeholder="请输入课程名称或课程简介或课程目的" style="width: 200px;" />
            </div>
            <!--            <div class="filter-group">-->
            <!--              <div class="filter-lable">岗位培训类型：</div>-->
            <!--              <SelectTree ref="keydataHyRef" :options="dicListMap.trainDicList" :props="defaultProps" v-model="dataMap.tarinTypeID" placeholder="请选择培训行业类型" />-->
            <!--            </div>-->
            <el-button v-waves type="primary" icon="el-icon-search" @click="getDataList"> 搜索 </el-button>
            <el-button v-waves type="success" icon="el-icon-refresh" @click="getCourseReset('2')"> 重置 </el-button>
          </div>
          <el-table v-loading="listLoading" ref="multipleDataoTable" :data="dataMap.list" :row-key="getRowKeyByDataTable" :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="课件名称" />
            <el-table-column prop="post_type_name" label="岗位培训类型" />
            <el-table-column prop="train_type_name" label="培训行业类型" />
            <el-table-column prop="CLASSHOUR" label="学时（分钟）" />
            <el-table-column prop="TEACHERNAME" label="讲师名称" />
          </el-table>
          <pagination :total="dataMap.total" :page.sync="dataMap.page" :limit.sync="dataMap.limit" @pagination="getDataList" />

        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogCoursewareShow = false">取 消</el-button>
        <el-button type="primary" @click="confirmByCou">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import { upload } from '@/utils/upload'
import waves from '@/directive/waves' // waves directive
import SelectTree from '@/components/SelectTree'
export default {
  components: { Pagination, SelectTree },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      searchFrom: {
        CURRICULUM_NAME: '',
        TRAINTYPE: '',
        POSTTYPE: '',
        TRAINLEVEL: '',
        INDUSTRY: '',
        TIME: [],
        ISSELL: ''
      },
      INDUSTRY: '',
      searchFromCollapse: true,
      total: 0,
      config: config,
      KEYWORDS: '',
      trainingSectionKey: [],
      TRAINTYPE: '',
      POSTTYPE: '',
      LEARNERCATEGORY: '',
      dates: ['', ''], // 区间条件
      STARTTIMES: [],
      ENDTIMES: [],
      varList: [],
      videoCoursewareList: [],
      dataCoursewareList: [],
      pd: [],
      QuestionNumOptions: [{
        value: '10',
        label: '10'
      }, {
        value: '20',
        label: '20'
      }, {
        value: '50',
        label: '50'
      }, {
        value: '100',
        label: '100'
      }],
      defaultProps: {
        value: 'id',
        children: 'nodes',
        label: 'name'
      },
      form: {
        CURRICULUMNAME: '', // 课程名称
        CURRICULUMINTRODUCE: '', // 课程介绍
        CURRICULUMAIM: '', // 课程目的
        STARTTIME: '', // 开始时间
        ENDTIME: '', // 结束时间
        CURRICULUMUSERS: '', // 适用人员
        VIDEOCOURSEWARES: '', // 视频课件组
        DATACOURSEWARES: '', // 资料课件组，
        TRAINTYPE: '', // 培训行业类型
        POSTTYPE: '', // 岗位培训类型
        FFILE: {}, // 图片
        dialogImageUrl: '',
        dialogVisible: false,
        CLASSHOUR: 0, // 课时总和
        trainingSection: []
      },
      hideUpload: false, // 显示图片
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogExamEdit: false,
      CURRICULUM_ID: '',
      CURRICULUMUSERS: '',
      dialogExamShow: false,
      dialogType: 'add',
      LearnerCategoryList: [],
      rules: {
        CURRICULUMNAME: [{ required: true, message: '课程名称不能为空', trigger: 'blur' }],
        // TRAINTYPE: [{ required: true, message: '培训行业类型不能为空', trigger: 'blur' }],
        POSTTYPE: [{ required: true, message: '岗位培训类型不能为空', trigger: 'blur' }],
        CURRICULUMINTRODUCE: [{ required: true, message: '课程介绍不能为空', trigger: 'blur' }]
      },
      dicListMap: {
        outlineDicList: [],
        trainDicList: [],
        postDicList: [],
        trainingSectionList: [],
        relatedTermList: []
      },
      dialogCoursewareShow: false,
      activeName: 'first', // 弹出成的 tabName
      videoMap: { // 视频课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzVidoList: []
      },
      dataMap: {// 资料课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzDataList: []
      },
      curriculumZongji: 0,
      chapterList: [],
      chapterIndex: 0,
      trainingList: [],
      postList: [],
      trainLevelList: [],
      industryTreeData: [],
      industryProps: {
        children: 'nodes',
        label: 'NAME',
        value: 'INDUSTRYTYPE_ID'
      },
      checkList: ['上传时间', '培训类型', '行业类型', '岗位', '课件数', '课程时长'],
      checkboxList: ['上传时间', '培训类型', '行业类型', '岗位', '课件数', '课程时长']
    }
  },
  watch: {
    'searchFrom.TRAINTYPE': {
      handler() {
        this.searchFrom.POSTTYPE = ''
        this.searchFrom.INDUSTRY = ''
        this.searchFrom.TRAINLEVEL = ''
        this.$refs.keyIndTypeRef.clearHandle()
        this.getPostList()
        this.getTrainLevelList()
        this.dicListMap['industryTreeData'] = []
        // this.dicListMap['trainLevelDicList'] = []
      }
    },
    'searchFrom.POSTTYPE': {
      handler() {
        this.searchFrom.INDUSTRY = ''
        this.searchFrom.TRAINLEVEL = ''
        this.$refs.keyIndTypeRef.clearHandle()
        this.getIndTree()
      }
    }
  },
  created() {
    this.getList()
    // this.getTrainingList()
    // this.getPostList()
    // this.getTrainLevelList()
    // this.getIndTree()
    // this.getDict()
    // this.getIdcList()
  },
  methods: {
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计'
          return
        } else if (index === 2) {
          sums[index] = '分钟'
          return
        } else if (index === 1) {
          const values = data.map(item => Number(item[column.property]))
          if (!values.every(value => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            // sums[index] += '小时'
          } else {
            sums[index] = 'N/A'
          }
        }
      })
      return sums
    },
    getRowKey(row) {
      return row.CURRICULUM_ID
    },
    // 搜索
    getQuery() {
      this.$refs.multipleTable.clearSelection()
      this.getList()
    },
    goKeyReset() {
      this.$refs.searchFrom.resetFields()
      this.dicListMap['postDicList'] = []
      this.dicListMap['industryTreeData'] = []
      this.dicListMap['trainLevelDicList'] = []
      this.getList()
    },
    syncCurriculum(row) {
      this.$confirm('确定要加入吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/videoRes/syncCurriculum',
          {
            CURRICULUM_ID: row.CURRICULUM_ID,
            DOCKINGCOURSES_ID: row.DOCKINGCOURSES_ID
          }
        ).then(() => {
          this.$message({
            message: '加入成功',
            type: 'success'
          })
          this.getList()
          this.listLoading = false
          // this.varList = []
          this.listQuery.page = 1
          // this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/videoRes/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        // todo 对接课程管理 测试
        // '/dockingCurriculum/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          ...this.searchFrom
        }
      ).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 CURRICULUMUSERS_VAL = ''
      const CURRICULUMUSERS = row.CURRICULUMUSERS.split(',')
      for (let i = 0; i < CURRICULUMUSERS.length; i++) {
        for (let j = 0; j < this.LearnerCategoryList.length; j++) {
          const option = this.LearnerCategoryList[j]
          if (option.BIANMA === CURRICULUMUSERS[i]) {
            CURRICULUMUSERS_VAL += option.NAME + ','
          }
        }
      }
      return CURRICULUMUSERS_VAL.slice(0, CURRICULUMUSERS_VAL.length - 1)
    },
    // 批量添加
    handleBatchAdd() {
      if (this.$refs.multipleTable.selection.length == 0) {
        this.$message.warning('请选择课程')
        return false
      }
      this.curriculumIdList = []
      const curriculumList = this.$refs.multipleTable.selection// 选择的视频课件内容
      curriculumList.forEach(item => {
        if (item.LOCAL != 0) {
          const info = {}
          info.CURRICULUM_ID = item.CURRICULUM_ID
          info.DOCKINGCOURSES_ID = item.DOCKINGCOURSES_ID
          this.curriculumIdList.push(info)
        }
      })
      if (this.curriculumIdList.length == 0) {
        this.$message.warning('你选择的课程都是加入过本地的')
        return false
      }
      // idList
      requestFN(
        '/videoRes/batchAddCourses',
        {
          idList: JSON.stringify(this.curriculumIdList)
        }
      ).then((data) => {
        this.$refs.multipleTable.clearSelection()
        this.$message.success('批量添加成功')
        this.getList()
      }).catch((e) => {
      })
    },
    // 同步课程与课件的过期时间
    syncNow() {
      this.$confirm('确定要立即更新吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message.success('同步')
        requestFN(
          '/videoRes/updNow',
          {
          }
        ).then((data) => {
          this.getList()
        }).catch()
      }).catch()
    },
    // 继承
    inherit() {
      this.resetForm()
      this.dialogType = 'inherit'
      const _selectData = this.$refs.multipleTable.selection
      if (_selectData == null || _selectData.length == 0) {
        this.$message({
          message: '请选中要继承的课程...',
          type: 'error'
        })
        return false
      } else if (_selectData.length > 1) {
        this.$message({
          message: '继承只能选择一个课程...',
          type: 'error'
        })
        return false
      }
      // const id = _selectData.map((item, index) => {
      //   return item.CURRICULUM_ID
      // })
      requestFN(
        '/curriculum/goEdit',
        {
          CURRICULUM_ID: _selectData[0].CURRICULUM_ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        var trainingSectionIDS = [] // 培训板块
        data.coursewareAllList.forEach((item, index) => {
          if (item.RECORD_TYPE_ID == 'trainingSection') {
            const valID = item.DICTIONARIES_IDS.split(',')
            trainingSectionIDS.push(valID)
          }
        })
        this.form.trainingSection = trainingSectionIDS
        this.chapterList = data.chapterList
        this.curriculumZongji = data.pd.CLASSHOUR
        // const node = {}
        // node.id = this.form.TRAINTYPE
        // console.info(this.form.TRAINTYPE)
        // const node2 = {}
        // node2.id = this.form.POSTTYPE
        // console.info(this.form.POSTTYPE)
        // if (this.$refs.pxTreeByCur) {
        //   this.$nextTick(() => { // 此处使用这个可以等节点渲染后再获取节点
        //     this.$refs.pxTreeByCur.handleNodeClick(node)
        //     this.$refs.gwTree.handleNodeClick(node2)
        //   })

        // }
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles()
          this.form.FFILE = {}
          this.hideUpload = false
        }

        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 修改
    handleEdit(ID) {
      this.resetForm()
      this.dialogType = 'edit'
      requestFN(
        '/curriculum/goEdit',
        {
          CURRICULUM_ID: ID
        }
      ).then((data) => {
        this.form = Object.assign({}, data.pd) // copy obj
        this.chapterList = data.chapterList
        this.curriculumZongji = data.pd.CLASSHOUR
        var trainingSectionIDS = [] // 培训板块
        data.coursewareAllList.forEach((item, index) => {
          if (item.RECORD_TYPE_ID == 'trainingSection') {
            const valID = item.DICTIONARIES_IDS.split(',')
            trainingSectionIDS.push(valID)
          }
        })
        this.form.trainingSection = trainingSectionIDS
        console.info(this.form.trainingSection)
        // const node = {}
        // node.id = this.form.TRAINTYPE
        // const node2 = {}
        // node2.id = this.form.POSTTYPE
        // if (this.$refs.pxTreeByCur) {
        //   this.$nextTick(() => { // 此处使用这个可以等节点渲染后再获取节点
        //     this.$refs.pxTreeByCur.handleNodeClick(node)
        //     this.$refs.gwTree.handleNodeClick(node2)
        //   })
        // }
        if (this.$refs.upload) {
          this.$refs.upload.clearFiles()
          this.form.FFILE = {}
          this.hideUpload = false
        }

        this.dialogFormEdit = true
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 保存
    confirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 判断章节是否为空
          if (this.chapterList.length == 0) {
            this.$message.warning('请添加章节')
            return false
          }
          var chapterWarnType = 0
          this.chapterList.forEach(row => {
            if (chapterWarnType == 0 && !row.NAME) {
              chapterWarnType = 1
            }
            if (chapterWarnType == 0 && row.xzVidoList.length == 0 && row.xzDataList.length == 0) {
              chapterWarnType = 2
            }
          })
          if (chapterWarnType == 1) {
            this.$message.warning('请输入章节名称')
            return false
          } else if (chapterWarnType == 2) {
            this.$message.warning('请选择章节课件')
            return false
          }

          const loading = this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          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)
            }
          })
          var cl = []
          for (var i = 0; i < this.chapterList.length; i++) {
            var VIDEOCOURSEWARES = ''
            var DATACOURSEWARES = ''
            this.chapterList[i].xzVidoList.forEach(row1 => {
              if (row1.VIDEOCOURSEWARE_ID) {
                VIDEOCOURSEWARES += row1.VIDEOCOURSEWARE_ID + ','
              }
            })
            this.chapterList[i].xzDataList.forEach(row2 => {
              if (row2.DATACOURSEWARE_ID) {
                DATACOURSEWARES += row2.DATACOURSEWARE_ID + ','
              }
            })

            // var DATACOURSEWARES = Object.keys(row.xzDataList).map(key => {
            //   return key.DATACOURSEWARE_ID
            // }).get().join(',')

            var chapter = { 'CHAPTER_ID': this.chapterList[i].CHAPTER_ID, 'NAME': this.chapterList[i].NAME, 'VIDEOCOURSEWARES': VIDEOCOURSEWARES, 'DATACOURSEWARES': DATACOURSEWARES, SORT: i + 1 }
            cl.push(chapter)
          }
          // if (this.videoMap.xzVidoList.length == 0 && this.dataMap.xzDataList.length == 0) {
          //   this.$message({
          //     message: '请选择课件',
          //     type: 'warning'
          //   })
          //   return false
          // }
          if (!this.form.FFILE && !this.form.CAPTURE) {
            this.$message.warning('课程图片不能为空，请上传')
            return false
          }
          // this.form.VIDEOCOURSEWARES = ''
          this.form.CLASSHOUR = this.curriculumZongji
          // this.videoMap.xzVidoList.forEach(row => {
          //   if (row.CLASSHOUR) {
          //     this.form.CLASSHOUR += parseInt(row.CLASSHOUR)
          //   }
          //   if (row.VIDEOCOURSEWARE_ID) {
          //     this.form.VIDEOCOURSEWARES += row.VIDEOCOURSEWARE_ID + ','
          //   }
          // })
          // this.form.DATACOURSEWARES = ''
          // this.dataMap.xzDataList.forEach(row => {
          //   if (row.CLASSHOUR) {
          //     this.form.CLASSHOUR += parseInt(row.CLASSHOUR)
          //   }
          //   if (row.DATACOURSEWARE_ID) {
          //     this.form.DATACOURSEWARES += row.DATACOURSEWARE_ID + ','
          //   }
          // })

          const formData = new FormData()
          formData.append('chapterList', JSON.stringify(cl))
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          upload(
            '/curriculum/' + this.dialogType,
            formData
          ).then((data) => {
            loading.close()
            this.dialogFormEdit = false
            this.getList()
          }).catch((e) => {
            loading.close()
          })
        } else {
          return false
        }
      })
    },
    handleEditExam(CURRICULUM_ID, CURRICULUMUSERS) {
      requestFN(
        '/question/countByCourseware',
        {
          CURRICULUMID: CURRICULUM_ID
        }
      ).then((data) => {
        this.QuestionNumOptions = [
          { value: '10', label: '10' },
          { value: '20', label: '20' },
          { value: '50', label: '50' },
          { value: '100', label: '100' }
        ]
        if (data.pd.DATACOUNT < 10) {
          this.QuestionNumOptions = [
            { value: '10', label: '10', disabled: true },
            { value: '20', label: '20', disabled: true },
            { value: '50', label: '50', disabled: true },
            { value: '100', label: '100', disabled: true }
          ]
        } else if (data.pd.DATACOUNT < 20) {
          this.QuestionNumOptions = [
            { value: '10', label: '10' },
            { value: '20', label: '20', disabled: true },
            { value: '50', label: '50', disabled: true },
            { value: '100', label: '100', disabled: true }
          ]
        } else if (data.pd.DATACOUNT < 50) {
          this.QuestionNumOptions = [
            { value: '10', label: '10' },
            { value: '20', label: '20' },
            { value: '50', label: '50', disabled: true },
            { value: '100', label: '100', disabled: true }
          ]
        } else if (data.pd.DATACOUNT < 100) {
          this.QuestionNumOptions = [
            { value: '10', label: '10' },
            { value: '20', label: '20' },
            { value: '50', label: '50' },
            { value: '100', label: '100', disabled: true }
          ]
        }
        this.CURRICULUM_ID = CURRICULUM_ID
        this.CURRICULUMUSERS = CURRICULUMUSERS
        this.dialogExamEdit = true
      }).catch((e) => {
      })
    },

    // 启用禁用
    handleEditState(CURRICULUM_ID, ISSELL) {
      var text = '上架'
      if (ISSELL == 0) {
        text = '下架'
      }
      this.$confirm('确定要' + text + '该课程吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/curriculum/editIsSell',
          {
            CURRICULUM_ID,
            ISSELL
          }
        ).then((data) => {
          var msg = '上架成功'
          if (ISSELL == 2) {
            msg = '下架成功'
          }
          this.$message({
            message: msg,
            type: 'success'
          })
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },

    closeExamEdit() {
      this.dialogExamEdit = false
      this.getList()
    },

    handleDelete(id) {
      this.$confirm('确定要删除课程吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/curriculum/delete',
          {
            CURRICULUM_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.CURRICULUM_ID
      }).join(',')

      this.$confirm('删除课程的同时会删除相关的课程习题、课程考试试卷、阶段考试试卷等信息，确定要删除选中的数据吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/curriculum/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(() => {
      })
    },
    addChapter() {
      var o = { 'CHAPTER_ID': '', 'NAME': '', 'xzVidoList': [], 'xzDataList': [] }
      this.chapterList.push(o)
    },
    // 判断按钮权限，用于是否显示按钮
    // hasButton: function() {
    //   var keys = 'curriculum:add,curriculum:del,curriculum:edit,toExcel'
    //   requestFN(
    //     '/head/hasButton',
    //     {
    //       keys: keys
    //     }
    //   ).then((data) => {
    //     this.add = data.curriculumfhadminadd		// 新增权限
    //     this.del = data.curriculumfhadmindel		// 删除权限
    //     this.edit = data.curriculumfhadminedit	// 修改权限
    //   }).catch((e) => {
    //     this.listLoading = false
    //   })
    // },
    // 获取数据字典数据
    getDict: function() {
      requestFN(
        '/videocourseware/getSelect',
        { VIDEOUSERS: this.form.CURRICULUMUSERS }
      ).then((data) => {
        this.videoCoursewareList = data.list
      }).catch((e) => {

      })

      requestFN(
        '/datacourseware/getSelect',
        { COURSEWAREUSERS: this.form.CURRICULUMUSERS }
      ).then((data) => {
        this.dataCoursewareList = data.list
      }).catch((e) => {

      })

      requestFN(
        '/dictionaries/getLevels',
        {
          DICTIONARIES_ID: '532282f9c48346b8b646531909c739df'
        }
      ).then((data) => {
        this.LearnerCategoryList = data.list
      }).catch((e) => {

      })
    },
    resetForm() {
      this.form = {
        CURRICULUMNAME: '', // 课程名称
        CURRICULUMINTRODUCE: '', // 课程介绍
        CURRICULUMAIM: '', // 课程目的
        STARTTIME: '', // 开始时间
        ENDTIME: '', // 结束时间
        CURRICULUMUSERS: '', // 适用人员
        VIDEOCOURSEWARES: '', // 视频课件组
        DATACOURSEWARES: '', // 资料课件组，
        TRAINTYPE: '', // 培训行业类型
        POSTTYPE: '', // 岗位培训类型
        FFILE: {}, // 图片
        dialogImageUrl: '',
        dialogVisible: false,
        hideUpload: false, // 显示图片
        CLASSHOUR: 0 // 课时总和
      }
      this.chapterList = []
      this.curriculumZongji = 0

      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
        this.form.FFILE = {}
        this.hideUpload = false
      }
      this.resetVideoAndDataMap()
    },
    resetVideoAndDataMap() {
      this.videoMap = { // 视频课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        KEYWORDS: '',
        tarinTypeID: '',
        xzVidoList: []
      }
      this.dataMap = {// 资料课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        KEYWORDS: '',
        tarinTypeID: '',
        xzDataList: []
      }
    },
    getIdcList() {
      this.getDicListByPID('d538d11e4eec409ab428f5d2f3c67c24', 'trainingSectionList') // 培训板块
      this.getDicListByPID('4459d3ff36d1475d8b2266da959fcc44', 'relatedTermList') // 相关词条
      this.getDicListByPID('052369aa22d242118236cde52d0c67ea', 'trainDicList')
      this.getDicListByPID('f6a7c4f5602f46e291d06b1390a3f820', 'postDicList')
    },
    getDicListByPID(pId, listName) {
      requestFN(
        '/dictionaries/listAllDictToParId',
        {
          parentId: pId
        }
      ).then((data) => {
        this.dicListMap[listName] = JSON.parse(data.zTreeNodes)
      }).catch((e) => {

      })
    },
    // 删除章节
    deleteChapter(index) {
      this.chapterList.splice(index, 1)
      this.countDuration()
    },
    // 选择课件
    selectCourseware(index) {
      this.dialogCoursewareShow = true
      this.chapterIndex = index
      this.resetVideoAndDataMap()
      this.getVoidList()
      this.getDataList()
      this.$nextTick(function() {
        this.handleSelectionChangeByVideoTable(index)
      })
    },
    confirmByCou() { // 点击确认
      this.chapterList[this.chapterIndex].xzVidoList = this.$refs.multipleVideoTable.selection// 选择的视频课件内容
      this.chapterList[this.chapterIndex].xzDataList = this.$refs.multipleDataoTable.selection// 选择的资料课件内容
      this.countDuration()
      this.dialogCoursewareShow = false
    },
    countDuration() {
      this.curriculumZongji = 0
      var zongji = 0

      this.chapterList.forEach(chapter => {
        chapter.xzVidoList.forEach(video => {
          zongji += video.CLASSHOUR
        })
        chapter.xzDataList.forEach(data => {
          zongji += data.CLASSHOUR
        })
      })

      // if (this.chapterList[this.chapterIndex].xzVidoList) {
      //   this.chapterList[this.chapterIndex].xzVidoList.forEach(row1 => {
      //     zongji += row1.CLASSHOUR
      //   })
      // }
      // if (this.chapterList[this.chapterIndex].xzDataList) {
      //   this.chapterList[this.chapterIndex].xzDataList.forEach(row2 => {
      //     zongji += row2.CLASSHOUR
      //   })
      // }
      this.curriculumZongji = zongji
      this.dialogCoursewareShow = false
    },
    getVoidList() { // 获取视频课件 videoMap.tarinTypeID
      requestFN(
        '/videocourseware/list?showCount=' + this.videoMap.limit + '&currentPage=' + this.videoMap.page,
        {
          KEYWORDS: this.videoMap.KEYWORDS,
          tarinTypeID: this.videoMap.tarinTypeID,
          STATE: '0'
        }
      ).then((data) => {
        this.videoMap.list = data.varList
        this.videoMap.total = data.page.totalResult
      }).catch((e) => {
      })
    },
    getDataList() { // 获取资料课件
      requestFN(
        '/datacourseware/list?showCount=' + this.dataMap.limit + '&currentPage=' + this.dataMap.page,
        {
          KEYWORDS: this.dataMap.KEYWORDS,
          tarinTypeID: this.dataMap.tarinTypeID,
          STATE: '0'
        }
      ).then((data) => {
        this.dataMap.list = data.varList
        this.dataMap.total = data.page.totalResult
      }).catch((e) => {
      })
    },
    getCourseReset(type) { // 视频课件和资料课件的条件重置
      if (type == '1') {
        this.videoMap.KEYWORDS = ''
        this.videoMap.tarinTypeID = ''
        this.$refs.keyvidHyRef.clearHandle()
        this.videoMap = { // 视频课件数据
          list: [],
          total: 0,
          page: 1,
          limit: 10,
          xzVidoList: []
        }
        this.getVoidList()
      }
      if (type == '2') {
        this.dataMap.KEYWORDS = ''
        this.dataMap.tarinTypeID = ''
        this.$refs.keydataHyRef.clearHandle()
        this.dataMap = {// 资料课件数据
          list: [],
          total: 0,
          page: 1,
          limit: 10,
          xzDataList: []
        }
        this.getDataList()
      }
    },
    getRowKeyByVideoTable(row) {
      return row.VIDEOCOURSEWARE_ID
    },
    getRowKeyByDataTable(row) {
      return row.DATACOURSEWARE_ID
    },
    delXzVidoList(chapterIndex, couIndex) {
      var keshi = this.chapterList[chapterIndex].xzVidoList[couIndex].CLASSHOUR
      this.curriculumZongji -= keshi
      this.chapterList[chapterIndex].xzVidoList.splice(couIndex, 1)
    },
    delXzDataList(chapterIndex, couIndex) {
      var keshi = this.chapterList[chapterIndex].xzDataList[couIndex].CLASSHOUR
      this.curriculumZongji -= keshi
      this.chapterList[chapterIndex].xzDataList.splice(couIndex, 1)
    },
    handleSelectionChangeByVideoTable(index) {
      // 再次打开选择课件回显 -- 视频课件
      if (this.chapterList[index].xzVidoList.length > 0) {
        this.chapterList[index].xzVidoList.forEach(row => {
          this.$refs.multipleVideoTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleVideoTable.clearSelection()
      }
      // 再次打开选择课件回显 -- 资料课件
      if (this.chapterList[index].xzDataList.length > 0) {
        this.chapterList[index].xzDataList.forEach(row => {
          this.$refs.multipleDataoTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleDataoTable.clearSelection()
      }
    },
    handlePictureCardPreview(file, fileList) {
      this.form.FFILE = file.raw
      this.form.dialogVisible = true
    },
    handleRemove(file, fileList) {
      this.form.FFILE = file.raw
      this.hideUpload = fileList.length >= 1
    },
    handleEditChange(file, fileList) {
      this.form.FFILE = file.raw
      this.hideUpload = fileList.length >= 1
    },

    beforeFileUpload(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.FFILE = file
      }
    },
    completeEdit(rowID) {
      this.$parent.CURRICULUM_ID = rowID
      this.$parent.activeName = 'CompleteEdit'
    },
    handleShow(rowID) {
      this.$parent.CURRICULUM_ID = rowID
      this.$parent.activeName = 'Info'
    },
    bc() {
      requestFN(
        '/dockingCurriculum/tb',
        {}
      ).then((data) => {
        this.$message.success('刷新一下')
      }).catch((e) => {
      })
    },
    getTrainingList() {
      requestFN(
        '/trainingtype/listAll',
        {}
      ).then((data) => {
        this.trainingList = data.varList
      }).catch((e) => {
      })
    },
    getPostList() {
      requestFN(
        '/posttype/listAll',
        { TRAININGTYPE_ID: this.searchFrom.TRAINTYPE }
      ).then((data) => {
        this.postList = data.varList
      }).catch((e) => {
      })
    },
    getTrainLevelList() {
      requestFN(
        '/trainleveltype/listAll',
        { TRAININGTYPE_ID: this.searchFrom.TRAINTYPE }
      ).then((data) => {
        this.trainLevelList = data.varList
      }).catch((e) => {
      })
    },
    getIndTree() {
      requestFN(
        '/industrytype/getIndustryTree',
        { POSTTYPE_ID: this.searchFrom.POSTTYPE }
      ).then((data) => {
        this.industryTreeData = data.zTreeNodes
      }).catch((e) => {
      })
    },
    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 + '秒'
        }
      }
    }
  }
}

</script>
<style>
.tree_dialog .selectTree{
  width: 300px;
}
  .hide .el-upload--picture-card {
    display: none;
  }
</style>
