<template>
  <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible"
    @close="handlereset">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" label-width="80px">
      <el-form-item label="加密类型" prop="type">
        <el-select v-model="dataForm.type" filterable
              placeholder="请选择类型">
          <el-option v-for="item in typeList" :key="item.dictType" :label="item.dictValue" :value="item.dictType">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="视频" prop="video">
        <el-input v-model="dataForm.video" placeholder="视频"></el-input>
        <!-- <el-upload
          :limit="1"
          :on-preview="handlePictureCardPreview"
          class="el-uploadfeng"
          ref="files"
          action="#"
          :file-list="fileList"
          :on-change="changeData"
          accept=".mp3,.mp4,.gif,.mpeg,.mpg"
          :http-request="handleRequest"
          :before-remove="handleBeforeRemove"
          :on-remove="handleRemove"
        >
          <i
            class="el-icon-plus"
            v-if="fileList.length == 0 && !isUpload"
          ></i>
        </el-upload> -->
        <div class="newpro">
          <el-progress
            v-if="isUpload"
            :stroke-width="10"
            :percentage="progressPercent"
            style="width: 100%"
          ></el-progress>
        </div>
        <!-- <el-upload :action="baseUrl + '/oss/fileoss'" list-type="picture-card" :on-preview="handlePictureCardPreview"
          :file-list="fileList" :on-success="handlePicSuccess" :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible" :append-to-body="true">
          <img width="100%" :src="dataForm.video" alt="">
        </el-dialog> -->
      </el-form-item>
      <!-- <el-form-item label="内容" prop="content">
        <el-input v-model="dataForm.content" placeholder="内容"></el-input>
      </el-form-item> -->
      <el-form-item label="排序" prop="sort">
        <el-input v-model="dataForm.sort" placeholder="排序"></el-input>
      </el-form-item>

     
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handlereset">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>



<script>
  import global from '../../common/common.vue' //引入共用组间
  import axios from "axios";
  export default {
    data() {
      return {
        baseUrl: global.baseUrl,
        progressPercent: 0,
        curPercentage: 0,
        isUpload: false,
        uploadTimer: null,
        visible: false,
        typeList: [ //类型0普通1加密
            
          {
            dictType: 0,
            dictValue: "普通"
          },
          {
            dictType: 1,
            dictValue: "加密"
          },
          {
            dictType: 2,
            dictValue: "mp3"
          }
        ],
        props: {
          dictType: '',
          dictValue: ''
        },
        gushuList:[],
        authorList: [],
        restaurants: [],
        author: '',
        publisherList: [],
        fileList: [],
        fileListNovel: [],
        dialogImageUrl: '',
        dialogVisible: false,
        dataForm: {
          "id": 0,
          "chapterId": 0,
          "type": "",
          "video": "",
          // "content": "",
          "sort": 1,
        },
        splitsTypeList: [],
        dataRule: {
          video: [
            { required: true, message: '请填写本项', trigger: 'blur' }
          ],
        }
      }
    },
    created() {
    },
    mounted() {
    },
    watch: {
      isUpload: {
        handler(val, oldVal) {
          if (this.isUpload) {
            this.uploadTimer = setInterval(async () => {
              //需要定时执行的代码
              this.progressPercent = await this.getProgress(this.currentFile);
            }, 1000);
          } else {
            //this.uploadTimer = null;
            clearInterval(this.uploadTimer);
            this.currentFile = {};
          }
          // this.getGoodsTypeList()
        },
        deep: true,
      },
    },
    methods: {
      init(row, chapter_id) {
        console.log('row2', row)
        this.dataForm = row || {
          type:1
        }
        this.dataForm.chapterId = chapter_id || ''
        this.visible = true
        if (this.dataForm.video && this.dataForm.video != "") {
          var img = {
            name: this.dataForm.video,
            url: this.dataForm.video
          }
          var attr = []
          attr.push(img)
          this.fileList = attr
        }else{
          this.fileList = []
        }
      
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`${!this.dataForm.id ? '/master/course/addCourseCatalogueChapterVideo' : '/master/course/editCourseCatalogueChapterVideo'}`),
              method: 'post',
              data: this.$http.adornData({
                "id": this.dataForm.id || undefined,
                'chapterId': this.dataForm.chapterId || undefined,
                'type': this.dataForm.type,
                "video": this.dataForm.video,
                // "content": this.dataForm.content, 
                "sort": this.dataForm.sort,
              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      async getProgress(file) {
        var that = this;

        console.log("🚀 ~ handleRequest ~ data222:", file.uid);
        var progress = 0;
        // const config = {
        //   onUploadProgress: (progressEvent) => {
        //     // progressEvent.loaded:已上传文件大小
        //     // progressEvent.total:被上传文件的总大小
        //     this.progressPercent = Number(
        //       ((progressEvent.loaded / progressEvent.total) * 100).toFixed(2)
        //     );
        //   },
        // };
        await axios
          .get(this.$http.adornUrl(`/oss/fileoss/getSchedule?uid=${file.uid}`))
          .then(async (res) => {
            console.log("🚀 ~ this.$axios.post ~ res999:", res.data.percent);
            progress = Number(res.data.percent);
            if (progress == 100) {
              this.isUpload = false;
              clearInterval(this.uploadTimer);
              that.uploadTimer = null;
              await that.handlePicSuccess(res.data, file);
              this.currentFile = {};
              this.$forceUpdate();
            }
          });
        console.log("🚀 ~ .then ~ progress888:", progress);
        return progress;
      },
      handleRequest(option) {
        var that = this;
        const { onProgress, onSuccess, onError } = option;
        this.progressPercent = 0;

        this.currentFile = option.file;
        let formdata = new FormData();
        formdata.append("file", option.file);
        formdata.append("fileName", option.file.fileNamee);
        formdata.append("uid", option.file.uid);
        console.log("🚀 ~ handleRequest ~ formdata:", formdata);

        this.isUpload = true;

        axios
          .post(this.baseUrl + "/oss/fileoss/uploadFileSchedule", formdata)
          .then((res) => {
            console.log("🚀 ~ this.$axios.post ~ res111:", res);
            if (res.data.code == 0) {
              that.fileList[that.fileList.length - 1].status = "done";
              // clearInterval(that.uploadTimer);
              // that.isUpload = false;
              // that.currentFile = {};
              // await that.handlePicSuccess(res.data, data.file);
              onSuccess();
            } else {
              that.fileList[that.fileList.length - 1].ststus = "error";
              onError();
            }
          });
        // var prom = new Promise((resolve, reject) => {});
        //   prom.abort = () => {};
        //   return prom;
      },
      handlePictureCardPreview(file) {
        this.dataForm.video = file.url;
        this.dialogVisible = true;
      },
      handlePicSuccess(res, file) {
        console.log(res, file, "999999999");
        if (res.msg == "success") {
          this.dataForm.video = res.url;
          this.fileList.push({
            name: file.name,
            url: res.url,
          });
          this.$message.success("上传成功");
          this.isUpload = false;
        } else {
          this.$message.error("上传失败");
        }
      },
      handlePicSuccess(res, file) {
        if (res.msg == "success") {
          this.dataForm.video = res.url;
          this.$message.success("上传成功");
        } else {
          this.$message.error("上传失败");
        }
      },
      changeData(file, fileList) {
        // 数据小于0.1M的时候按KB显示
        const size =
          file.size / 1024 / 1024 > 0.1
            ? `(${(file.size / 1024 / 1024).toFixed(1)}M)`
            : `(${(file.size / 1024).toFixed(1)}KB)`;
        file.name.indexOf("M") > -1 || file.name.indexOf("KB") > -1
          ? file.name
          : (file.name += size);
      },
      handleBeforeRemove(file, fileList) {
        console.log(file, fileList, "file, fileListfile, fileListfile, fileList");
        this.$refs.files.clearFiles();
        clearInterval(this.uploadTimer);
        this.isUpload = false;

        this.currentFile = {};
        this.$forceUpdate();
      },
      handleRemove(file, fileList) {
        this.dataForm.video = "";
        this.fileList = fileList;
        //this.uploadTimer = null;
        clearInterval(this.uploadTimer);
        this.isUpload = false;

        this.currentFile = {};
        this.$forceUpdate();

        // this.dataForm.noneBtnImg = fileList.length >= this.dataForm.limitCountImg;
      },
      handleDownload(file) {
        console.log(file)
      },
      handlereset() {
        this.fileList = [],
          this.fileListNovel = [],
          this.visible = false
      },
      // handlePreview(file) {
      //   console.log(file);
      // },
      // handleExceed(files, fileList) {
      //   this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      // },
      // beforeRemove(file, fileList) {
      //   return this.$confirm(`确定移除 ${ file.name }？`);
      // },
      // handleRemoveNovel(file) {
      //   this.dataForm.novel = '';
      // },
      // handleNovelSuccess(file) {
      //   this.dataForm.novel = file.url
      // },
      // querySearch(queryString, cb) {
      //     var restaurants = this.restaurants;
      //     var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      //     // 调用 callback 返回建议列表的数据
      //     console.log(results)
      //     cb(results);
      // },
      // createFilter(queryString) {
      //     return (restaurant) => {
      //       return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      //     };
      // },
      // handleSelect(item) {
      //   this.dataForm.authorId = item.id
      //     console.log(item);
      //   }
    },
    beforeDestroy() {
      clearInterval(this.uploadTimer);
    },

  }
</script>
