<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="KEYWORDS">
                <el-input v-model="searchFrom.KEYWORDS" placeholder="请输入课程名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="创建时间" prop="TIME">
                <el-date-picker
                  v-model="searchFrom.TIME"
                  style="width: 100%;"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="培训类型" prop="TRAINTYPE">
                <el-select v-model="searchFrom.TRAINTYPE" placeholder="请选择培训类型" style="width: 100%;">
                  <el-option
                    v-for="item in trainingList"
                    :key="item.TRAININGTYPE_ID"
                    :label="item.NAME"
                    :value="item.TRAININGTYPE_ID"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-show="!searchFromCollapse" :span="6">
              <el-form-item label="行业类型" prop="INDUSTRY">
                <SelectTree
                  ref="keyIndTypeRef"
                  :options="industryTreeData"
                  :props="industryProps"
                  v-model="searchFrom.INDUSTRY"
                  style="width: 100%;"
                  placeholder="请选择培训行业类型"/>
              </el-form-item>
            </el-col>
            <el-col v-show="!searchFromCollapse" :span="6">
              <el-form-item label="岗位类型" prop="POSTTYPE">
                <el-select v-model="searchFrom.POSTTYPE" placeholder="请选择岗位类型" style="width: 100%;">
                  <el-option
                    v-for="item in postList"
                    :key="item.POSTTYPE_ID"
                    :label="item.NAME"
                    :value="item.POSTTYPE_ID"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col v-show="!searchFromCollapse" :span="6">
              <el-form-item label="培训级别" prop="TRAINLEVEL">
                <el-select v-model="searchFrom.TRAINLEVEL" placeholder="请选择培训级别" style="width: 100%;">
                  <el-option
                    v-for="item in trainLevelList"
                    :key="item.TRAINLEVEL_ID"
                    :label="item.NAME"
                    :value="item.TRAINLEVEL_ID"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item style="text-align: right">
                <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-button type="text" @click="searchFromCollapse = !searchFromCollapse">
                  {{ searchFromCollapse ? '展开' : '合并' }} <i
                    :class="searchFromCollapse ? 'el-icon-arrow-down' : 'el-icon-arrow-up'"/></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="app-tools">
        <!--        bug 7943 如果要了就解开
<div class="app-function">-->
        <!--          <el-button v-show="add" type="primary" icon="el-icon-plus" @click="handleAdd">新建课程</el-button>-->
        <!--          <el-button v-show="del" type="danger" icon="el-icon-delete" @click="batchDel">批量删除</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="CURRICULUMNAME" label="课程名称"/>
          <el-table-column
            v-if="checkList.includes('上传时间')"
            :show-overflow-tooltip="true"
            prop="CREATTIME"
            label="上传时间"/>
          <el-table-column
            v-if="checkList.includes('培训类型')"
            :show-overflow-tooltip="true"
            prop="TRAININGTYPE_NAME"
            label="培训类型"/>
          <el-table-column
            v-if="checkList.includes('行业类型')"
            :show-overflow-tooltip="true"
            prop="INDUSTRY_END_NAME"
            label="行业类型"/>
          <el-table-column v-if="checkList.includes('岗位类型')" prop="POSTTYPE_NAME" label="岗位类型" align="center"/>
          <el-table-column v-if="checkList.includes('课程属性')" prop="COLLECTIVE" label="课程属性" align="center">
            <template slot-scope="{row}">
              <template v-if="row.COLLECTIVE=='0'">
                <div>平台通用</div>
              </template>
              <template v-else>
                <div>指定机构专用</div>
              </template>
            </template>
          </el-table-column>
          <el-table-column
            v-if="checkList.includes('课件数')"
            prop="COURSEWARECOUNT"
            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.VIDEOTIME) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300px">
            <template slot-scope="{row}">
              <el-button type="text" @click="editCurriculum(row.CURRICULUM_ID)">编辑</el-button>
              <span class="app-divider"/>
              <el-button type="text" @click="delCurriculum(row.CURRICULUM_ID)">删除</el-button>
              <span class="app-divider"/>
              <el-button type="text" @click="convertCurriculum(row.CURRICULUM_ID)">转为正式课程</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page-btn-group">
          <div/>
          <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 通过 el-pagination二次打包
import { requestFN } from '@/utils/request'
import waves from '@/directive/waves' // waves directive
import PaperEdit from '../../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
      },
      searchFrom: {
        KEYWORDS: '',
        TRAINTYPE: '',
        POSTTYPE: '',
        TRAINLEVEL: '',
        INDUSTRY: '',
        TIME: [],
        ISSELL: ''
      },
      searchFromCollapse: true,
      total: 0,
      config: config,
      KEYWORDS: '',
      TRAINTYPE: '',
      POSTTYPE: '',
      LEARNERCATEGORY: '',
      varList: [],
      videoCoursewareList: [],
      dataCoursewareList: [],
      pd: [],
      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.POSTTYPE': {
      handler() {
        this.searchFrom.TRAINLEVEL = ''
        this.getTrainLevelList()
      }
    }
  },
  created() {
    this.getList()
    this.getIndTree()
    this.getTrainingList()
    this.getPostList()
  },
  methods: {
    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.$refs.keyIndTypeRef.clearHandle()
      this.getList()
    },
    // 获取列表
    getList() {
      console.info(this.INDUSTRY)
      console.info(this.searchFrom)
      this.listLoading = true
      requestFN(
        '/curriculumCache/list?showCount=' + this.listQuery.limit + '&currentPage=' + this.listQuery.page,
        {
          ...this.searchFrom,
          STARTTIME: this.searchFrom.TIME[0],
          ENDTIME: this.searchFrom.TIME[1]
        }
      ).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
      })
    },
    // 添加
    handleAdd() {
      this.$parent.CURRICULUM_ID = ''
      this.$parent.TYPE = 'add'
      this.$parent.activeName = 'Edit'
    },
    // 删除
    delCurriculum(CURRICULUM_ID) {
      // 批量删除
      // const ArrayDATA_IDS = []
      // ArrayDATA_IDS.push(CURRICULUM_ID)
      this.$confirm('确定要移除课程吗?。', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        requestFN(
          '/curriculumCache/delete',
          {
            CURRICULUM_IDS: CURRICULUM_ID
          }
        ).then((data) => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.$refs.multipleTable.clearSelection()
          this.getList()
        }).catch((e) => {
          this.listLoading = false
        })
      })
    },
    convertCurriculum(CURRICULUM_ID) {
      this.$confirm('确定要转为正式课程吗?。', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        requestFN(
          '/curriculumCache/confirmation',
          {
            CURRICULUM_ID: CURRICULUM_ID
          }
        ).then(() => {
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.listLoading = 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(
          '/curriculumCache/delete',
          {
            CURRICULUM_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) => {

      })
    },
    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
    },
    completeEdit(rowID) {
      this.$parent.CURRICULUM_ID = rowID
      requestFN(
        '/videocourseware/iscompleteall',
        {
          CURRICULUM_ID: rowID
        }
      ).then((data) => {
        if (data.ISTRUE === '0') {
          this.$parent.activeName = 'CompleteEdit'
        } else {
          this.$message.error('请先去完善课程中的课件信息。')
        }
      }).catch((e) => {
      })
    },
    editCurriculum(rowID) {
      this.$parent.CURRICULUM_ID = rowID
      this.$parent.TYPE = 'edit'
      this.$parent.activeName = 'Edit'
    },
    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',
        { POSTTYPE_ID: this.searchFrom.POSTTYPE }
      ).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 % 24, 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>
