<template>
  <div class="app-container">
    <div class="filter-container">
      <div class="filter-row mb-10">
        <div class="filter-group">
          <div class="filter-lable">请输入课程：</div>
          <el-input v-model="KEYWORDS" placeholder="请输入课程名称" style="width: 200px;" />
        </div>
        <!--      <div class="filter-group">-->
        <!--        <div class="filter-lable"> 培训行业类型：</div>-->
        <!--        <SelectTree ref="keyHyRef" :options="dicListMap.trainDicList" :props="defaultProps" v-model="TRAINTYPE" placeholder="请选择培训行业类型" />-->
        <!--      </div>-->
        <div class="filter-group">
          <div class="filter-lable"> 培训板块类型：</div>
          <SelectTree ref="trainingSectionRef" :options="dicListMap.trainingSectionList" :props="defaultProps" v-model="trainingSectionKey" placeholder="请选择培训板块类型" />
        </div>
        <div class="filter-group">
          <div class="filter-lable"> 培训行业类型：</div>
          <SelectTree ref="keyTrainTypeRef" :options="dicListMap.trainDicList" :props="defaultProps" v-model="TRAINTYPE" placeholder="请选择培训行业类型" />
        </div>
        <div class="filter-group">
          <div class="filter-lable"> 岗位培训类型：</div>
          <SelectTree ref="keyGwRef" :options="dicListMap.postDicList" :props="defaultProps" v-model="POSTTYPE" placeholder="请选择岗位培训类型" />
        </div>
      </div>
      <div class="filter-row">
        <div class="filter-group mr-10">
          <div class="filter-lable" style="width:72px">
            创建时间：
          </div>
          <div class="filter-date">
            <el-date-picker v-model="dates" :default-time="['00:00:00', '23:59:59']" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" />
          </div>
        </div>

        <el-button v-waves type="primary" icon="el-icon-search" class="ml-10" @click="getQuery">
          搜索
        </el-button>
        <el-button v-waves type="success" icon="el-icon-refresh" @click="goKeyReset">
          重置
        </el-button>
      </div>
    </div>
    <el-table
      v-loading="listLoading"
      ref="multipleTable"
      :data="varList"
      :row-key="getRowKey"
      :header-cell-style="{
        'font-weight': 'bold',
        'color': '#000'
      }"
      tooltip-effect="dark"
      border
      fit
      highlight-current-row>
      <el-table-column :reserve-selection="true" type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="CURRICULUMNAME" label="课程名称" />
      <el-table-column :show-overflow-tooltip="true" prop="TSNAME" label="培训板块" />
      <el-table-column :show-overflow-tooltip="true" prop="train_type_name" label="培训行业类型" >
        <template slot-scope="{row}">
          <div v-if="row.CURRENCY == 1">通用</div>
          <div v-else>{{ row.train_type_name }}</div>
        </template>
      </el-table-column>
      <el-table-column :show-overflow-tooltip="true" prop="post_type_name" label="岗位培训类型" />
      <el-table-column prop="CLASSHOUR" label="学时（分钟）" width="100" align="center" />
      <el-table-column prop="videoCount" label="视频课件数" width="90" align="center" />
      <el-table-column prop="dataCount" label="资料课件数" width="90" align="center" />
      <el-table-column prop="CREATTIME" label="创建时间" width="150" align="center" />
      <el-table-column label="操作" align="center" width="370">
        <template slot-scope="{row}">
          <el-button v-if="!row.COURSEPAPERS_ID" type="success" icon="el-icon-view" size="mini" @click="handleShow(row.CURRICULUM_ID)">查看</el-button>
          <el-button v-if="!row.COURSEPAPERS_ID" v-show="edit" type="primary" icon="el-icon-edit" size="mini" @click="handleEdit(row.CURRICULUM_ID)">编辑</el-button>
          <el-button v-if="row.CURRICULUM_ID_REMOTE && row.ISCOMPLETE == 0" v-show="edit" type="warning" icon="el-icon-edit" size="mini" @click="handleEdit(row.CURRICULUM_ID)">完善课程</el-button>
          <el-button v-if="!row.COURSEPAPERS_ID" v-show="del" type="danger" icon="el-icon-delete" size="mini" @click="handleDelete(row.CURRICULUM_ID)">删除</el-button>
          <!--          <el-button v-if="!row.COURSEPAPERS_ID" type="success" icon="el-icon-document-add" size="mini" @click="handleEditExam(row.CURRICULUM_ID, row.CURRICULUMUSERS)">生成试卷</el-button>-->
          <el-button v-show="edit && row.STATE == 1" type="info" icon="el-icon-switch-button" size="mini" @click="handleEditState(row.CURRICULUM_ID,'2')">禁用</el-button>
          <el-button v-show="edit && row.STATE == 2" class="green-btn" icon="el-icon-switch-button" size="mini" @click="handleEditState(row.CURRICULUM_ID,'1')">启用</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="page-btn-group">
      <div>
        <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新建课程</el-button>
        <!--        <el-button type="success" icon="el-icon-plus" @click="inherit">继承</el-button>-->
      </div>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </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"
            style="width: 100%;"
            placeholder="请输入培训板块"
            filterable/>
        </el-form-item>
        <el-form-item label="是否通用" prop="CURRENCY">
          <el-radio-group id="CURRENCY" ref="CURRENCY" v-model="form.CURRENCY">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.CURRENCY == 0" label="培训行业类型" prop="TRAINTYPE" required>
          <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" style="width: 100%;" placeholder="请选择岗位培训类型" />
        </el-form-item>
        <el-form-item v-if="(dialogType=='edit' || dialogType=='inherit') && form.CAPTURE" label="已上传课程图片">
          <div >
            <img v-if="form.CAPTURE" :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" title="预览图片" append-to-body>
            <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.xzVideoList.length>0 || data.xzDataList.length>0" label="已经添加课件" prop="kejianList">
            <el-row>
              <!--                @click="delxzVideoList(index)" @click="delXzDataList(index)"-->
              <el-col :span="12">
                <el-table :data="data.xzVideoList" :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="delxzVideoList(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="dialogExamEdit" :visible.sync="dialogExamEdit" title="课程试卷" width="40%" style="padding-bottom:20px">
      <PaperEdit :curriculumid="CURRICULUM_ID" :curriculumusers="CURRICULUMUSERS" :questionnumoptions="QuestionNumOptions" :close-exam-edit="closeExamEdit" />
    </el-dialog>

    <!-- 课程试卷改为跳转查看 -->
    <el-dialog v-if="dialogExamShow" :visible.sync="dialogExamShow" title="课程试卷" width="90%">
      <PaperInfo :paperid="COURSEPAPERS_ID" :learnercategorylist="LearnerCategoryList" />
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogExamShow = false">取 消</el-button>
        <el-button type="error" @click="handleDeletePaper">删 除</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="培训行业类型">
              <template slot-scope="{row}">
                <div v-if="row.CURRENCY == 1">通用</div>
                <div v-else>{{ row.train_type_name }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="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.打" :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 PaperEdit from '@/views/onlinexxks/course/paper/components/edit'
import PaperInfo from '../../paper/components/info'
import SelectTree from '@/components/SelectTree'
export default {
  components: { Pagination, PaperEdit: PaperEdit, PaperInfo: PaperInfo, SelectTree },
  directives: { waves },
  data() {
    return {
      listLoading: true,
      add: false,
      del: false,
      edit: false,
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      config: config,
      KEYWORDS: '',
      trainingSectionKey: [],
      TRAINTYPE: '',
      POSTTYPE: '',
      LEARNERCATEGORY: '',
      dates: ['', ''], // 区间条件
      STARTTIMES: [],
      ENDTIMES: [],
      varList: [],
      currencyList: [{
        value: '0',
        label: '否'
      }, {
        value: '1',
        label: '是'
      }],
      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: [],
        CURRENCY: '' // 是否通过
      },
      hideUpload: false, // 显示图片
      multipleSelectionAll: [], // 所有选中的数据包含跨页数据
      multipleSelection: [], // 当前页选中的数据
      dialogFormEdit: false,
      dialogExamEdit: false,
      CURRICULUM_ID: '',
      CURRICULUMUSERS: '',
      dialogExamShow: false,
      COURSEPAPERS_ID: '',
      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' }],
        CURRENCY: [{ required: true, message: '是否通用为必选', trigger: 'blur' }]
      },
      dicListMap: {
        outlineDicList: [],
        trainDicList: [],
        postDicList: [],
        trainingSectionList: [],
        relatedTermList: []
      },
      dialogCoursewareShow: false,
      activeName: 'first', // 弹出成的 tabName
      videoMap: { // 视频课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzVideoList: []
      },
      dataMap: {// 资料课件数据
        list: [],
        total: 0,
        page: 1,
        limit: 10,
        xzDataList: []
      },
      curriculumZongji: 0,
      chapterList: [],
      chapterIndex: 0
    }
  },
  created() {
    this.getList()
    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.KEYWORDS = ''
      this.LEARNERCATEGORY = ''
      this.dates = []
      this.TRAINTYPE = ''
      this.POSTTYPE = ''
      this.$refs.keyGwRef.clearHandle()
      this.$refs.trainingSectionRef.clearHandle()
      this.$refs.keyTrainTypeRef.clearHandle()
      this.getList()
    },
    // 获取列表
    getList() {
      this.listLoading = true
      requestFN(
        '/curriculum/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          KEYWORDS: this.KEYWORDS,
          TRAINTYPE: this.TRAINTYPE,
          POSTTYPE: this.POSTTYPE,
          LEARNERCATEGORY: this.LEARNERCATEGORY,

          STARTTIME: this.dates[0],
          ENDTIME: this.dates[1],
          trainingSectionKey: this.trainingSectionKey
        }
      ).then((data) => {
        this.listLoading = false
        this.varList = data.varList
        this.total = data.page.totalResult
        this.hasButton()
        this.pd = data.pd
      }).catch((e) => {
        this.listLoading = false
      })
    },
    // 格式化适用人员名称
    formatterUsers(row, column) {
      var 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)
    },
    // 添加
    handleAdd() {
      this.$refs.form && this.$refs.form.clearValidate()
      this.dialogType = 'add'
      this.resetForm()

      if (this.$refs.pxTree) {
        this.$refs.pxTree.clearHandle()
      }
      if (this.$refs.gwTree) {
        this.$refs.gwTree.clearHandle()
      }
      // this.getDict()
      this.dialogFormEdit = true
    },
    // 继承
    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
      })
      console.info(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
        if (this.form.TRAINTYPE == 'null') {
          this.form.TRAINTYPE = ''
        }
        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 (this.form.CURRENCY == 1) {
          this.form.TRAINTYPE = ''
        }
        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.xzVideoList.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
          }

          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].xzVideoList.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.xzVideoList.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.xzVideoList.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))
          console.info(this.form)
          Object.keys(this.form).map(key => {
            formData.append(key, this.form[key])
          })
          const loading = this.$loading({
            lock: true,
            text: '数据保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          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(ID, state) {
      var text = '启用'
      if (state == 2) {
        text = '禁用'
      }
      this.$confirm('确定要' + text + '该课程吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/curriculum/editState',
          {
            CURRICULUM_ID: ID,
            STATE: state
          }
        ).then((data) => {
          var msg = '启用成功'
          if (state == 2) {
            msg = '禁用成功'
          }
          this.$message({
            message: msg,
            type: 'success'
          })
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    closeExamEdit() {
      this.dialogExamEdit = false
      this.getList()
    },
    handleShowExam(ExamId) {
      // this.COURSEPAPERS_ID = ExamId
      // this.dialogExamShow = true
      this.$parent.COURSEPAPERS_ID = ExamId
      this.$parent.activeName = 'PaperInfo'
    },
    handleDeletePaper() {
      this.$confirm('确定要删除该试卷吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/coursepapers/delete',
          {
            COURSEPAPERS_ID: this.COURSEPAPERS_ID
          }
        ).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.listLoading = false
          this.dialogExamShow = false
          this.varList = []
          this.listQuery.page = 1
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      }).catch(() => {
      })
    },
    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': '', 'xzVideoList': [], '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: '',
        xzVideoList: []
      }
      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].xzVideoList = 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.xzVideoList.forEach(video => {
          zongji += video.CLASSHOUR
        })
        chapter.xzDataList.forEach(data => {
          zongji += data.CLASSHOUR
        })
      })

      // if (this.chapterList[this.chapterIndex].xzVideoList) {
      //   this.chapterList[this.chapterIndex].xzVideoList.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',
          ISPERFECT: '1'
        }
      ).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,
          xzVideoList: []
        }
        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
    },
    delxzVideoList(chapterIndex, couIndex) {
      var keshi = this.chapterList[chapterIndex].xzVideoList[couIndex].CLASSHOUR
      this.curriculumZongji -= keshi
      this.chapterList[chapterIndex].xzVideoList.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].xzVideoList.length > 0) {
        this.chapterList[index].xzVideoList.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
      }
    },
    handleShow(rowID) {
      this.$parent.COURSEPAPERS_ID = rowID
      this.$parent.activeName = 'Info'
    }
  }
}

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