<style lang="scss" scoped>
  .search-box p {
    display: inline-block;
    border: 1px solid #f2f2f2;
    border-radius: 5px;
    margin-right: 10px;
    padding: 5px 10px;
    cursor: pointer;
  }

  #office-iframe {
    height: 800px;
  }
</style>
<template>
  <a-row :gutter="10">

    <a-col :sm="6" style="margin-bottom: 20px;z-index: 10">
      <a-card class="search-box" style="min-height:500px" title="在线视频培训列表">
        <a slot="extra" @click="addList">
          新增培训视频
        </a>
        <a-directory-tree  @select="onSelect" @expand="onExpand" :loadData="onLoadData"
          :treeData="treeData">
        </a-directory-tree>
      </a-card>
    </a-col>
    <a-col :sm="18" style="margin-bottom: 20px;z-index: 10">
      <a-card class="search-box">
        <!-- <div @click="openFile">打开文件</div> -->
        <div v-if="course">
          <a-breadcrumb>
            <a-breadcrumb-item>{{ course.media }}</a-breadcrumb-item>
            <a-breadcrumb-item>{{ course.title }}</a-breadcrumb-item>
            <a-breadcrumb-item>{{ course.topic }}</a-breadcrumb-item>
          </a-breadcrumb>
          <h3 style="text-align:center">{{ course.name }}</h3>
          <p v-if="!startList">请使用谷歌浏览器进行视频播放,并开启flash(开启方法:浏览器右上角三个小点-设置-网站设置-flash-每次进行询问勾选打开即可)</p>
          <br>
          <p v-if="!startList">flash下载链接:https://www.flash.cn/cdm/latest/flashplayerpp_install_cn.exe</p>
          <br>
          <p style="text-align:center" v-if="course.creator">作者：{{ course.creator }}</p>
          <br />
          <p>{{ course.intro }}</p>
        </div>
        <div id="iframeData" v-show="startList" style="height:800px"></div>
        <div id="videoPlay" style="height:800px" v-show="!startList"></div>
      </a-card>
    </a-col>
    <a-modal :width="800" title="培训视频上传" @cancel="closeImage" @afterClose="closeImage" v-model="addImageVisible">
      <template slot="footer">
        <a-button key="back" @click="closeImage">取消</a-button>
        <a-button key="submit" type="primary" @click="handleOkImage" :loading="loadingImage" :disabled="fileUrl==''">
          确定
        </a-button>
      </template>
      <a-form :form="form">
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="培训上传方式">
          <a-radio-group buttonStyle="solid" v-model="typeUpload" @change="clear">
            <a-radio-button value="1">原有目录上传</a-radio-button>
            <a-radio-button value="2" :disabled="roleName!='admin'">新建目录上传</a-radio-button>
          </a-radio-group>
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="一级目录选择">
          <a-select
            v-decorator="['media', { rules: [{ required: true, message: '请选择一级目录' }], initialValue: '汇创视频培训'  }]"
            showSearch allowClear placeholder="选择模板" optionFilterProp="children" :filterOption="filterOption" disabled>
            <a-select-option value="汇创视频培训">
              汇创视频培训
            </a-select-option>
          </a-select>
        </a-form-item>
        <div v-if="typeUpload == '1'">
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="二级目录选择">
            <a-select v-decorator="['title', { rules: [{ required: true, message: '请选择二级目录' }]  }]" style="width: 100%"
              placeholder="请选择二级目录" @change="getTopic">
              <a-select-option v-for="(item,index) in titleList" :key="index" :value="item.value">
                {{item.label}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="三级目录选择">
            <a-select v-decorator="['topic', { rules: [{ required: true, message: '请选择三级目录' }]  }]" style="width: 100%"
              placeholder="请选择三级目录" :disabled="!getData('title')" @change="setOssDir">
              <a-select-option v-for="(item,index) in topicList" :key="index" :value="item.value">
                {{item.label}}
              </a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <div v-else>
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="二级目录">
            <!-- <a-input placeholder="请填写二级目录"
              v-decorator="['titleAll', { rules: [{ required: true, message: '二级目录必填' }]  }]" /> -->
            <a-select mode="tags" v-model="oneList" placeholder="请填写二级目录" @change="handleChange" autoClearSearchValue>
              <a-select-option v-for="(item,index) in titleList" :key="index" :value="item.value">
                {{item.label}}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="三级目录">
            <a-input placeholder="请填写三级目录"
              v-decorator="['topicAll', { rules: [{ required: true, message: '三级目录必填' }]  }]" />
          </a-form-item>
        </div>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="培训视频名称">
          <a-input placeholder="请填写培训视频名称"
            v-decorator="['name', { rules: [{ required: true,message:'培训视频名称不能为空'}] }]" />
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="培训视频简介">
          <a-input placeholder="请填写培训视频简介" v-decorator="['intro']" />
        </a-form-item>
        <a-form-item :label-col="labelCol" :wrapper-col="wrapperCol" label="文件上传"
          v-show="(getData('title') && getData('topic'))||(oneList.length>0 && getData('topicAll'))">
          <uploadFile :value.sync="fileUrl" :multiple='false':checkFile="file" :fileCount="1"
            uploadType="video" />
          <!-- <upload-to-ali v-model="fileUrl" :customDomain="customDomain" preview :region="region" :bucket="bucket"
            :accept="acceptVideo" :max="10" :size="1024000" :accessKeyId="accessKeyId"
            :accessKeySecret="accessKeySecret" :before-upload="file" :dir="dirVideo" @loaded="overUpload">
          </upload-to-ali> -->
        </a-form-item>

      </a-form>

    </a-modal>
  </a-row>
</template>

<script>
  import {
    getAction,
    postAction
  } from '@/api/manage'
  import {
    JeecgListMixin
  } from '@/mixins/JeecgListMixin'
  import moment from 'moment'
  import $ from 'jquery'
  import qs from 'qs'
  import UploadToAli from '@femessage/upload-to-ali'
  import uploadFile from '@/components/uploadFile.vue'
  // document.write(textDes('https://ctop-media.oss-cn-beijing.aliyuncs.com/video/2020-03-20/20网服-1584693978588.mp4'))
  // document.write('<br>' + desDecrypt('s4HMPbmUfZ0=', 'ckplayerDesKey'))
  function textDes(str) {
    var keyCode = 'ckplayerDesKey'
    var newText = encodeURI(desEncrypt(str, keyCode))
    newText = (keyCode == 'ckplayerDesKey' ? 'CK:' : 'CE:') + newText
    return newText
  }

  function desEncrypt(word, keyCode) {
    var key = CryptoJS.enc.Utf8.parse(keyCode)
    var iv = CryptoJS.enc.Utf8.parse(keyCode)
    var srcs = CryptoJS.enc.Utf8.parse(word)
    var encrypted = CryptoJS.DES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.ECB
    })
    return encrypted.toString()
  }

  function desDecrypt(word, keyCode) {
    var key = CryptoJS.enc.Utf8.parse(keyCode)
    var iv = CryptoJS.enc.Utf8.parse(keyCode)
    var decrypt = CryptoJS.DES.decrypt(word, key, {
      iv: iv,
      mode: CryptoJS.mode.ECB
    })
    return CryptoJS.enc.Utf8.stringify(decrypt).toString()
  }

  export default {
    name: 'online-training-list',
    mixins: [JeecgListMixin],
    data() {
      return {
        typeUpload: '1',
        titleList: [],
        topicList: [],
        oneList: [],
        fileUrl: '',
        customDomain: '',
        region: 'oss-cn-beijing',
        bucket: 'ctop-media',
        acceptVideo: 'video/mpeg,video/mp4',
        accessKeyId: 'LTAIbNbqWzSOklQV',
        accessKeySecret: '1rkPz7JNoXk8sJevPaeYHWqfkQXBGh',
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 12
          }
        },
        visibleDetail: false,
        srcList: '',
        loadingImage: false,
        addImageVisible: false,
        form: this.$form.createForm(this),
        treeData: [{
            title: '巨量引擎',
            key: '巨量引擎'
          },
          {
            title: '快手大学',
            key: '快手大学'
          },
          {
            title: '汇创视频培训',
            key: '汇创视频培训'
          }
        ],
        videoObject: {
          width: '20%', // 宽度，也可以支持百分比(不过父元素宽度要有)
          height: 180, // 高度，也可以支持百分比
          container: '#videoPlay', //“#”代表容器的ID，“.”或“”代表容器的class
          variable: 'player', //该属性必需设置，值等于下面的new chplayer()的对象
          autoplay: false, //自动播放
          flashplayer: true, //强制使用flashplayer
          live: false,
          debug: true,
          loadNext: 10,
          usehardwareeecoder: true, //硬件加速
          video: textDes() //视频地址(必填)
        },
        videoObjectNot: {
          container: '#videoPlay', //“#”代表容器的ID，“.”或“”代表容器的class
          variable: 'player', //该属性必需设置，值等于下面的new chplayer()的对象
          autoplay: false,
          html5m3u8: true,
          debug: true,
          video: "" //视频地址
        },
        active: 1,
        url: {
          list: '/ctop/materialInfo/list'
        },
        startList: true,
        simpleMode: false,
        course: null,
        dirVideo: "online/",
        roleName: localStorage.getItem('roleCode')
      }
    },
    components: {
      UploadToAli,
      uploadFile
    },
    methods: {
      clear() {
        this.form.setFieldsValue({
          topic: '',
          title: ''
        })
      },
      filterOption(input, option) {
        return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      },
      getTopic(e) {
        //    e.target.value 
        console.log(e)
        this.topicList = []
        this.form.setFieldsValue({
          topic: ''
        })
        getAction('/ctop/edu/system/topic', {
          title: e
        }).then(res => {
          if (res.success) {
            this.topicList = res.result.map(item => {
              return {
                value: item,
                label: item
              }
            })
          }
        })
      },
      setOssDir(e) {
        this.dirVideo = 'online/' + this.getData('title') + '/' + this.getData('topic')
      },
      setOssDirElse() {
        this.dirVideo = 'online/' + this.oneList[0] + '/' + this.getData('topicAll')
      },
      addList() {
        this.addImageVisible = true
        this.loadingImage = false
        this.typeUpload = '1'
        getAction("/ctop/edu/system/lesson").then(res => {
          console.log(res)
          if (res.success) {
            this.titleList = res.result.map(item => {
              return {
                value: item,
                label: item
              }
            })
          }
        })

      },
      handleChange(value) {
        console.log(value)
        if (value.length == 2) {
          this.oneList = [value.pop()]
        }

      },
      handleOkImage(e) {
        this.loadingImage = true
        this.form.validateFieldsAndScroll((err, values) => {
          if (err) {
            // 这里做逻辑处理
          } else {
            var params = {}
            if (this.typeUpload == '1') {
              params = {
                ...values,
                ossFileUrl: 'https:' + this.fileUrl,
                fileType: 1
              }
            } else {
              params = {
                ...values,
                ossFileUrl: 'https:' + this.fileUrl,
                fileType: 1,
                title: this.oneList[0],
                topic: values.topicAll
              }
            }
            postAction('/ctop/edu/lesson/upload', params).then(res => {
              if (res.success) {
                this.loadingImage = false
                this.closeImage()
                getAction("/ctop/edu/system/lesson").then(res => {

                })
              }
            })
          }
        })
      },
      closeImage() {
        this.addImageVisible = false
        this.form.resetFields()
        this.fileUrl = ""
        this.oneList = []
      },
      file(file) {
        if (this.typeUpload == '1') {
          this.dirVideo = 'online/' + this.getData('title') + '/' + this.getData('topic')
        } else {
          this.dirVideo = 'online/' + this.oneList[0] + '/' + this.getData('topicAll')
        }
        var that = this
        console.log(this.dirVideo)
        return new Promise(function (resolve, reject) {

          if (that.dirVideo.split('/').length == 3) {
            resolve()
          } else {
            reject()
          }

        })
      },
      overUpload() {

      },
      onLoadData(treeNode) {
        console.log(treeNode)
        return new Promise(resolve => {
          if (treeNode.eventKey == '巨量引擎') {
            getAction('/ctop/edu/ocean/lesson').then(res => {
              if (res.success) {
                treeNode.dataRef.children = res.result.map(item => {
                  if (item) {
                    return {
                      title: item,
                      key: item + '@juliang'
                    }
                  }
                })
                resolve()
                this.treeData = [...this.treeData]
              }
            })
          } else if (treeNode.eventKey == '快手大学') {
            getAction('/ctop/edu/kuaishou/lesson').then(res => {
              if (res.success) {
                treeNode.dataRef.children = res.result.map(item => {
                  if (item) {
                    return {
                      title: item,
                      key: item + '@kuaishou'
                    }
                  }
                })
                resolve()
                this.treeData = [...this.treeData]
              }
            })
          } else if (treeNode.eventKey == '汇创视频培训') {
            getAction('/ctop/edu/system/lesson').then(res => {
              if (res.success) {
                treeNode.dataRef.children = res.result.map(item => {
                  if (item) {
                    return {
                      title: item,
                      key: item + '@system'
                    }
                  }
                })
                resolve()
                this.treeData = [...this.treeData]
              }
            })
            return
          } else if (treeNode.eventKey.split('@').length == 2) {
            var data = treeNode.eventKey.split('@')
            if (data[1] == 'juliang') {
              getAction('/ctop/edu/ocean/topic', {
                title: data[0]
              }).then(res => {
                if (res.success) {
                  treeNode.dataRef.children = res.result.map(item => {
                    return {
                      title: item,
                      key: item + '@juliang@' + data[0]
                    }
                  })
                  resolve()
                  this.treeData = [...this.treeData]
                }
              })
            } else if (data[1] == 'kuaishou') {
              getAction('/ctop/edu/kuaishou/topic', {
                title: data[0]
              }).then(res => {
                if (res.success) {
                  treeNode.dataRef.children = res.result.map(item => {
                    return {
                      title: item,
                      key: item + '@kuaishou@' + data[0]
                    }
                  })
                  resolve()
                  this.treeData = [...this.treeData]
                }
              })
            } else if (data[1] == 'system') {
              getAction('/ctop/edu/system/topic', {
                title: data[0]
              }).then(res => {
                if (res.success) {
                  treeNode.dataRef.children = res.result.map(item => {
                    return {
                      title: item,
                      key: item + '@system@' + data[0]
                    }
                  })
                  resolve()
                  this.treeData = [...this.treeData]
                }
              })
            }
          } else if (treeNode.eventKey.split('@').length == 3) {
            var data = treeNode.eventKey.split('@')
            getAction('/ctop/edu/lesson/list', {
              media: data[1] == 'juliang' ? '巨量引擎' : data[1] == 'kuaishou' ? '快手大学' : '汇创视频培训',
              title: data[2],
              topic: data[0]
            }).then(res => {
              console.log(res)
              if (res.success) {
                treeNode.dataRef.children = res.result.map(item => {
                  return {
                    title: item.name,
                    key: item.id,
                    isLeaf: true
                  }
                })
                resolve()
                this.treeData = [...this.treeData]
              }
            })
          }
        })
      },
      onSelect(keys, event) {
        console.log(keys)
        if (event.node.isLeaf) {
          getAction('/ctop/edu/detail', {
            id: keys[0]
          }).then(res => {
            console.log(res)
            if (res.success) {
              this.course = res.result
              if (res.result.fileType == 1) {
                this.startList = false
                //   var videoObject = null
                //   var isChrome = window.navigator.userAgent.indexOf('Chrome') !== -1 //不同的浏览器显示方式不一样， 不是chrome的浏览器需要使用hls.js这个文件
                //   if (isChrome) {
                //     videoObject = this.videoObject
                //   } else {
                //     videoObject = this.videoObjectNot
                //   }
                if (res.result.fileId) {
                  this.videoObject.video = textDes('https://aweme.snssdk.com/aweme/v1/playwm/?video_id=' + res
                    .result.fileId + '&line=0')


                } else {
                  if (res.result.fileUrl) {
                    this.videoObject.video = textDes(res.result.fileUrl)
                  } else {
                    this.videoObject.video = textDes(res.result.ossFileUrl)
                  }

                }
                console.log(this.videoObject.video)

                let player = new ckplayer(this.videoObject)
                console.log(player)
              } else {
                this.startList = true
                getAction('http://www.ljserver.cn:8088/v1/api/file/getViewUrlWebPath', {
                  fileUrl: decodeURI(res.result.ossFileUrl)
                }).then(resF => {
                  console.log(resF)
                  let r = resF.data
                  sessionStorage.wpsUrl = r.wpsUrl
                  sessionStorage.token = r.token
                  this.openWps(r.wpsUrl, r.token, res.result.fileType)
                })
              }
            }
          })
        } else {
          return
        }
      },
      openWps(url, token, type) {
        let _this = this
        console.log(url)
        const wps = WebOfficeSDK.config({
          mode: _this.simpleMode ? 'simple' : 'normal',
          mount: document.querySelector('#iframeData'),
          wpsUrl: url,
          commonOptions: {
            isShowTopArea: false // 隐藏顶部区域(头部和工具栏)
          }
        })
        //   2：pdf
        //   3：ppt
        wps.setToken({
          token: token
        })
        if (type == 2) {
          wps.PPTApplication
        } else if (type == 3) {
          wps.PDFApplication
        } else {
          wps.Application
        }

        wps.iframe.height = '800px'
      },
      onExpand() {
        console.log('Trigger Expand')
      },
      getDataSource(page, pageSize) {
        this.ipagination.current = page
        this.loadData()
      },
      getData(className) {
        return this.form.getFieldValue(className)
      },
      getAdd(checked) {
        this.active = checked
        if (checked == 5) {
          this.data = []
        } else {
          this.data = [{
              title: 'Title 1'
            },
            {
              title: 'Title 2'
            },
            {
              title: 'Title 3'
            },
            {
              title: 'Title 4'
            }
          ]
        }
      },
      lookDetail(item) {
        this.visibleDetail = true
      },
      openFile() {
        getAction('http://www.ljserver.cn:8088/v1/api/file/getViewUrlWebPath', {
          fileUrl: 'https://ctop-media.oss-cn-beijing.aliyuncs.com/zixingche.docx'
        }).then(res => {
          console.log(res.data.wpsUrl)
          window.open(res.data.wpsUrl, '_blank')
        })
      },
      getDirectory() {
        getAction('/ctop/edu/kuaishou/lesson').then(res => {
          console.log(res)
        })
        getAction('/ctop/edu/kuaishou/topic', {
          title: '新代理入门培训'
        }).then(res => {
          console.log(res)
        })
        getAction('/ctop/edu/ocean/lesson').then(res => {
          console.log(res)
        })
        getAction('/ctop/edu/ocean/topic', {
          title: '初级认证I类课程'
        }).then(res => {
          console.log(res)
        })

        getAction('/ctop/edu/lesson/list', {
          media: '快手大学',
          title: '新代理入门培训',
          topic: '入门培训'
        }).then(
          res => {
            console.log(res)
          }
        )
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.videoObject.video =
          " CK:2OoC8kA6lhNFqCi2uVquDPpnuq9VcRji9nGXe5nqadA6Jey7YFFEP8pE99j58UBbLyb7YN7cpkw="

        let player = new ckplayer(this.videoObject)


      })

    },
    created() {
      // console.log(player)
      //   /modules/onlineTraining/onlineTrainingList
    }
  }
</script>