<template>
  <div class="addCourse app-container">
    <el-form
      :model="setQuery"
      ref="setQuery"
      :rules="rules"
      label-width="130px"
      :disabled="mode == 'detail'"
    >
      <el-form-item label="课程名称：" prop="courseName">
        <el-input
          v-model="setQuery.courseName"
          class="item-width-300"
        ></el-input>
      </el-form-item>

     <el-form-item label="课程封面：" prop="courseImg">
        <Upload
          type="courseImg"
          id="courseImg"
          width="300px"
          height="200px"
          :disabled="mode == 'detail'"
          :imgUrl="setQuery.courseImg"
          @uploadEnd="uploadEnd"
        ></Upload>
      </el-form-item>
       <el-form-item label="所属栏目：" prop="columnId">
        <el-select
          v-model="setQuery.columnId"
          clearable
          class="item-width-300"
          placeholder="请选择栏目"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      
       <el-form-item label="课程简介：" prop="courseMsg">
        <el-input
            type="textarea"
            :rows="10"
            maxlength="100"
            show-word-limit
            class="item-width-300"
            placeholder="课程简介，限100字"
            v-model="setQuery.courseMsg">
        </el-input>
      </el-form-item>
      <el-form-item label="课程章节：">
        <el-table
      :data="setQuery.chapters"
      tooltip-effect="dark"
      border
      v-loading="loading"
      style="width: 100%"
    >
    <el-table-column
      align="center"
      type="index"
      label="序号"
      width="150">
    </el-table-column>
      <el-table-column
        prop="chapterName"
        align="center"
        label="章节名称"
        show-overflow-tooltip
      >
      </el-table-column>
      <el-table-column
        prop="courseMsg"
        align="center"
        label="视频名称"
        show-overflow-tooltip
      >
       <template slot-scope="scope">
        {{scope.row.chapterUrl | filterName}}
       </template>
      </el-table-column>
       <el-table-column prop="address" align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" class="red" size="small" @click="handleDel(scope.row.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
     <el-button size="small" type="primary" plain @click="handleAdd()">添加章节</el-button>
      </el-form-item>

    </el-form>

    <div class="btn-group" v-if="mode != 'detail'">
       <el-button>取 消</el-button>
     <el-button type="primary" :loading="loading"  @click="save(1)">保存</el-button>
     <el-button type="primary" :loading="loading"  @click="save(2)">保存并发布</el-button>
    </div>

<input type="file" accept='video/*' id="video" v-show="false" ref="video" @change="upload" />

    <el-dialog :title="title" width="550px" :close-on-press-escape="false" :close-on-click-modal="false" :visible.sync="dialogFormVisible">
        <el-form label-width="100px" :model="form"
        ref="form"
        :rules="rules1">
            <el-form-item label="章节名称:"  prop="chapterName">
                <el-input
                v-model="form.chapterName"
                class="item-width-400"
                ></el-input>
            </el-form-item>
            <el-form-item label="上传视频:"  prop="chapterUrl">
                <div class="video-box" v-show="form.videoSize">
                  <div class="name">{{videoName}}</div>
                  <div class="size">{{(form.videoSize/1024).toFixed(2)}}MB</div>
                  <el-button type="text" class="del-btn red" size="small" @click="delVideo()">删除</el-button>
                  <el-progress class="progress" :stroke-width="4" :percentage="percentage"></el-progress>
                </div>
               <el-button type="text" size="small" @click="handleUpload">{{form.chapterUrl?'重新上传':'上传视频'}}</el-button>
            </el-form-item>
        </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" :loading="btnLoading" @click="saveVideo">确 定</el-button>
    </div>
    </el-dialog>
    
  </div>
</template>

<script>
import Upload from '@/components/Upload'
import {addOrUpdateCourse,getAllColumn,courseDetail} from '@/api/study'
import { requestUploadImg, finishUploadImg } from '@/api/common';
import OSS from "ali-oss";
export default {
    components: {
        Upload,
    },
  data() {
    return {
      mode:'',
      percentage:0,
        index:0,
        title:'',
        tableData:[],
        loading:false,
        btnLoading:false,
        dialogFormVisible:false,
        videoName:'',
        form:{
            chapterName: "",
            chapterUrl: "",
            videoSize:0
          },
        setQuery: {
        "chapters": [
           
        ],
        "columnId": 0,
        "courseImg": "",
        "courseMsg": "",
        "courseName": "",
        "status": 1
        },
        rules:{
            columnId: [{ required: true, message: "请选择栏目", trigger: "change" }],
            courseImg: [{ required: true, message: "请上传课程封面", trigger: "change" }],
            courseName: [{ required: true, message: "请输入课程名称", trigger: "blur" }],
            courseMsg: [{ required: true, message: "请输入课程简介", trigger: "blur" }],
        },
        rules1:{
            chapterName: [{ required: true, message: "请输入章节名称", trigger: "blur" }],
            chapterUrl: [{ required: true, message: "请上传课程视频", trigger: "change" }],
        },
      options:[],
      client:null,
    };
  },
  filters: {
    filterName: function(value) {
      if(value){
        let arr = value.split('/')
         return arr[arr.length-2]
      }
    }
  },
  methods: {
    handleUpload(){
      document.getElementById('video').click()
    },
    upload(val){
      let that = this
      let files = val.target.files[0];
      this.videoName = files.name
      this.form.videoSize = (files.size/1024).toFixed(2)
       requestUploadImg(
          {
            "fineName": files.name,
            "operate": 'OTHER'
          }
        ).then(res=>{
          if(res.state == 'Success'){
            this.client = new OSS({
          // yourregion填写Bucket所在地域。以华东1（杭州）为例，Region填写为oss-cn-hangzhou。
          region: res.content.endPoint.split('.')[0],
          // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
          accessKeyId: res.content.token.accessKeyId,
          accessKeySecret: res.content.token.accessKeySecret,
          // 填写Bucket名称。
          bucket: res.content.bucket,
          stsToken:res.content.token.securityToken
        });

        this.client
          .multipartUpload(res.content.paths[0].join('/'), files,{
            progress:((p,t)=>{
              that.percentage = Number((p*100).toFixed(0))
            }),
            parallel: 6,
            partSize: 1024 * 1024
          })
          .then((r) => {
            // 上传完成
            finishUploadImg([{path:res.content.paths[0]}]).then(msg=>{
              if(msg.state == 'Success'){

                that.form.chapterUrl = 'http://' + res.content.bucket + '.'+ res.content.endPoint + '/' + res.content.paths[0].join('/')

                that.$refs.video.value = ''
              }
            })
        
          })
          .catch((err) => {
            console.log(err); //上传失败之后
          });
            
          }
        })
    },
    delVideo(){
      this.videoName = ''
      this.percentage = 0
      this.form.chapterUrl = "" 
      this.form.videoSize = 0 
      this.client.cancel()
    },
    handleAdd(){
      this.title = '添加章节'
      this.percentage = 0
      this.dialogFormVisible = true
      this.form = {
         chapterName: "",
         chapterUrl: "",
         videoSize:0
      }
     
    },
    handleEdit(row){
      this.title = '编辑章节'
      this.percentage = 100
      this.dialogFormVisible = true
      this.form = row
      let arr = this.form.chapterUrl.split('/')
      this.videoName = arr[arr.length-2]
    },
    handleDel(index){
       this.$confirm(`此操作将删除该数据, 是否继续?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
              this.setQuery.chapters.splice(index,1)
              this.$notify({
              title: '成功',
              message: '操作成功',
              type: 'success'
            });
        })
    },
    uploadEnd(val){
      this.setQuery[val.type] = val.url
    },
    // 获取栏目
    getAllColumn() {
      getAllColumn().then((res) => {
        if (res.state == "Success") {
          res.content.map((item) => {
            this.options.push({
              value: item.id,
              label: item.columnName,
            });
          });
        }
      });
    },
    // 取消
    cancel(){
      this.delVideo()
      this.dialogFormVisible = false
    },
    // 保存
    saveVideo(){
       this.$refs.form.validate((v) => {
        if (v) {
          if(this.title == '添加章节'){
            this.setQuery.chapters.push(this.form)
          }else{
            this.$set(this.setQuery.chapters,index,this.form)
          }
          this.dialogFormVisible = false
        }
       })
    },
   save(status) {
      this.$refs.setQuery.validate((v) => {
        if (v) {
          this.loading = true
          this.setQuery.status = status
          addOrUpdateCourse(this.setQuery).then(res=>{
            this.loading = false

            if(res.state == 'Success'){

              this.$notify({
                  title: '成功',
                  message: '操作成功',
                  type: 'success'
                });
               
              this.$router.push('/studyManage/courseManage/index')
            }
          })
              
        }
      });
    },
    courseDetail(){
        this.loading = true
        courseDetail({id:this.$route.query.id}).then(res=>{
            this.loading = false
            if(res.state == 'Success'){
                this.setQuery = res.content
            }
        })
    }
  },
  created () {
    this.getAllColumn()
    this.mode = this.$route.query.mode
    if(this.$route.query.mode == 'edit' || this.$route.query.mode == 'detail'){
        this.courseDetail()
    }
  },
};
</script>

<style lang="scss" scoped>
.addCourse {
  padding-bottom: 40px;
  .btn-group{
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .video-box{
    display: flex;
    align-items: center;
    padding: 0 40px 10px 10px;
    border-radius: 4px;
    background: #fafafa;
    position: relative;
    width: 400px;
    .name{
      font-size: 14px;
      color: #333;
      width: 270px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
    .size{
      font-size: 12px;
      color: #ccc;
      margin-left: 10px;
    }
    .del-btn{
      position: absolute;
      top: 50%;
      right: 10px;
      transform: translateY(-50%);
    }
    .progress{
      position: absolute;
      width: 100%;
      bottom: 0;
      left: 0;
    }
  }
}
</style>