<template>
  <!--选择课程文件,视频，音，文档-->
  <div style="min-height: 500px;">
    <div style="padding: 5px 5px 10px 5px;display: flex;justify-content: space-between;">
     <!-- <div>
        <el-button @click="save" type="primary" size="small">确定</el-button>
      </div> -->
    </div>
    <el-tabs type="border-card" style="min-height: 400px;">
      <el-tab-pane :label="'选择已有'+curComType.name" >
          <div style="display: flex;justify-content: flex-start;">
              <div>
                <el-input maxlength="50" v-model="keyword" placeholder="名称" size="small"></el-input>
              </div>
              <!-- <div><el-input maxlength="50" v-model="params.author" placeholder="上传人" size="small"></el-input></div> -->
              <div style="padding-left: 10px;">
                <el-button @click="findCourseFile()" type="primary" >搜索</el-button>
              </div>
          </div>
          <div v-if="findState==2" style="padding-top: 10px;">
             <el-table style="100%" :data="fileList" border stripe>
                <el-table-column label="类型" width="70" prop="author"><template slot-scope="scope">{{curComType.name}}</template></el-table-column>
                <el-table-column label="名称" prop="name"></el-table-column>
                <el-table-column label="创建" prop="sysCreateBy" width="100"></el-table-column>
                <el-table-column label="创建时间" prop="sysCreateTime" width="100"></el-table-column>
                <el-table-column label="选择" width="70" align="center">
                  <template slot-scope="scope">
                      <el-button size="mini" @click="chooseCourseFile(scope.row)" type="primary">选择</el-button>
                  </template>
                </el-table-column>
            </el-table>
          <div style="text-align: center">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageIndex"
              :page-sizes="[5, 10,20,50,100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="count">
              </el-pagination>
            </div>
          </div>
      </el-tab-pane>
      <el-tab-pane :label="'上传新'+curComType.name">
        <div v-if="!courseFile.id">
          <div v-if="resType>20" style="padding-bottom: 10px;">
            <span style="font-weight: 700;">内容时长（分）：</span>
            <span>
              <el-input-number v-model="duration" size="mini" :min="1" :max="100"></el-input-number>
            </span>
          </div>
          <el-upload class="upload-demo" :headers="headers" :data="data" drag :action="uploadFileUrl" :on-success="handleUploadSuccess" :before-upload="handleBeforeUpload">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">文件大小限制：{{curComType.maxSizeName}},支持的文件类型：{{curComType.fileTypes.join(',')}}</div>
          </el-upload>

        </div>
        <div v-else style="text-align: center;">
           <div style="padding: 20px;">{{courseFile.fileName}} <span style="color: green;">上传成功</span></div>
           <div><el-button @click="chooseCourseFile(courseFile)" type="primary"  size="mini">确定</el-button></div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
  import { getToken } from "@/utils/token";
  import apiCourseFile from '../../api/modules/courseFile';
  export default{
    props: {
      minHeight:{
        type: String,
        default:'500'
      },
      orgId:{
        type: String,
        default:''
      },
      orgName:{
        type: String,
        default:''
      },
      resType:{
        type: Number,
        default:0
      }
    },
    data(){
      return {
        uploadFileUrl: process.env.VUE_APP_BASE_API + "/xboe/sys/xuploader/file/upload", // 上传的图片服务器地址
        data:{
          dir:'course'
        },
        headers: {
          'XBOE-Access-Token': getToken(),
        },
        pageSize:10,
        pageIndex:1,
        count:0,
        keyword: '',
        duration:1,
        comTypes:[
            {id:'1',type:'video',name:'视频',img:'el-icon-video-camera',resType:10,maxSize:1024,maxSizeName:"1G",fileTypes:['mp4']},
            {id:'2',type:'sound',name:'音频',img:'el-icon-service',resType:20,maxSize:1024,maxSizeName:"1G",fileTypes:['mp3']},
            {id:'3',type:'image',name:'图片',img:'el-icon-picture-outline',resType:30,maxSize:10,maxSizeName:"10M",fileTypes:["png","jpg","gif","bmp"]},
            {id:'4',type:'doc',name:'文档',img:'el-icon-document',resType:40,maxSize:1024,maxSizeName:"1G",fileTypes:["doc", "xls", "ppt","docx", "xlsx", "pptx","txt","pdf"]},
            {id:'5',type:'scorm',name:'SCORM',img:'el-icon-suitcase',resType:50,maxSize:1024,maxSizeName:"1G",fileTypes:["zip"]}
        ],
        curComType:{id:'',type:'',name:'',maxSizeName:'',fileTypes:[]},
        findState:1,
        courseFile:{},
        fileList:[],
        radioId:'',
      }
    },
    mounted() {
      this.courseFile={};
      let $this=this;
      this.comTypes.some(ct=>{
        if(ct.resType==$this.resType){
          $this.curComType=ct;
          //this.findCourseFile();//
          return true;
        }else{
          return false;
        }
      });
      this.findCourseFile();
    },
    watch:{
       resType(newVal,oldVal){
          if(newVal!=oldVal){
            this.findCourseFile();
          }

       }
    },
    methods:{
      handleBeforeUpload(file) {
        if(file.name.lastIndexOf(".") ==-1) {
          this.$message({message:`文件格式不正确!`,type:'error',offset:100})
          return false;
        }
        let fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        fileExtension=fileExtension.toLowerCase();
        // 校检文件类型
        if(this.curComType.fileTypes.indexOf(fileExtension) == -1){
            this.$message({message:`文件格式不正确, 请上传正确格式的${this.curComType.name}文件!`,type:'error',offset:100})
            return false;
        }
        // 校检文件大小
        if(this.curComType.maxSize) {
          const isLt = file.size / 1024 / 1024 < this.curComType.maxSize;
          if (!isLt) {
            this.$message({message:`上传文件大小不能超过 ${this.curComType.maxSizeName} !`,type:'error',offset:100})
            return false;
          }
        }
        if(this.resType==50){
          this.data.dir='scorm';
        }else{
          this.data.dir='course';
        }
        return true;
      },
      // 上传失败
      handleUploadError(err) {
        this.$message({message:"上传失败, 请重试",type:'error',offset:100});
      },
      // 上传成功回调
      handleUploadSuccess(res, file) {
        //console.log(res);
        if(res.status == 200) {
          //上传到课件库
          //console.log(res.result);
          let courseWare={
            fileName:res.result.displayName,
            fileType:res.result.fileType,
            filePath:res.result.filePath,
            resType:this.resType,
            orgId:this.orgId,
            orgName:this.orgName,
            duration:this.duration,
            remark:'课程中直接上传'
          }
          apiCourseFile.saveUpload(courseWare).then(rs=>{
              if(rs.status==200){
                this.courseFile=rs.result;
                this.$message({message:"上传成功",type:'success',offset:100});
                // this.cware.content.contentRefId=rs.result.id;
                // this.cware.content.contentName=result.displayName;
                // this.cware.content.content=result.filePath;
              }else{
                this.$message.error(rs.message);
              }
          });
        }else{
           this.$message({message:"上传失败："+res.message,type:'error',offset:100});
        }

        //this.$emit("success", res);
      },
      // 删除文件
      handleDelete(index) {
        this.fileList.splice(index, 1);
        //注意删除处理
        //this.$emit("remove", '');
      },
      // 获取文件名称
      getFileName(name) {
        if (name.lastIndexOf("/") > -1) {
          return name.slice(name.lastIndexOf("/") + 1).toLowerCase();
        } else {
          return "";
        }
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.pageIndex = 1;
        this.findCourseFile();
      },
      handleCurrentChange(val) {
        this.pageIndex = val;
        this.findCourseFile();
      },
     findCourseFile(){
        this.findState=2;
         let data = {
          name: this.keyword,
          resOwner1: '',//this.params.resOwner1, //资源归属一级的id
          resOwner2: '',//this.params.resOwner2, // 资源归属二级的id
          resOwner3: '',//this.params.resOwner3, // 资源归属三级的id
          resType: this.resType, //this.params.type,
          pageSize: this.pageSize,
          pageIndex: this.pageIndex,
          self:true,//只是查询自己的
        }
        apiCourseFile.pageList(data).then(rs=>{
          if(rs.status === 200) {
            this.fileList = rs.result.list;
            this.count = rs.result.count;
          }else{
            this.$message.error(rs.message);
          }
        })

      },
      chooseCourseFile(ccfile){
        this.$emit('choose', ccfile);
      }
    }
  }
</script>

<style>
</style>
