<template>
  <div class="dropzone-wrapper dataset-files">
    <div
      id="dataset"
      class="dropzone"
    />

    <p class="upload-info">
      {{ file_status_text }}
      <span class="success">{{ status }}</span>
    </p>
  </div> 
</template>

<script>
/* eslint-disable eqeqeq */
// import Dropzone from 'dropzone/dist/dropzone.js';
// import 'dropzone/dist/dropzone.css'
import SparkMD5 from 'spark-md5';
import axios from 'axios';
import qs from 'qs';
// import esdk-obs-nodejs from 'esdk-obs-nodejs';
// import * as ObsClient from 'esdk-obs-nodejs'
import createDropzone from '../features/dropzone.js';
import * as ObsClient from '../features/esdk-obs-browserjs-3.19.5.min.js';

const {_AppSubUrl, _StaticUrlPrefix, csrf} = window.config;

export default {
  data() {
    return {
      dropzoneUploader: null,
      maxFiles: 1,
      maxFilesize: 1 * 1024 * 1024 * 1024 * 1024,
      acceptedFiles: '*/*',
      progress: 0,
      status: '',
      dropzoneParams: {},
      file_status_text: ''
    };
  },

  async mounted() {
    this.dropzoneParams = $('div#minioUploader-params');
    this.file_status_text = this.dropzoneParams.data('file-status');
    this.status = this.dropzoneParams.data('file-init-status');

    let previewTemplate = '';
    previewTemplate += '<div class="dz-preview dz-file-preview">\n ';
    previewTemplate += '    <div class="dz-details">\n ';
    previewTemplate += '        <div class="dz-filename">';
    previewTemplate +=
      '            <span data-dz-name data-dz-thumbnail></span>';
    previewTemplate += '        </div>\n    ';
    previewTemplate += '        <div class="dz-size" data-dz-size></div>\n  ';
    previewTemplate += '    </div>\n  ';
    previewTemplate += '    <div class="dz-progress ui active progress">';
    previewTemplate +=
      '        <div class="dz-upload bar" data-dz-uploadprogress><div class="progress"></div></div>\n  ';
    previewTemplate += '    </div>\n  ';
    previewTemplate += '    <div class="dz-success-mark">';
    previewTemplate += '        <span>上传成功</span>';
    previewTemplate += '    </div>\n  ';
    previewTemplate += '    <div class="dz-error-mark">';
    previewTemplate += '        <span>上传失败</span>';
    previewTemplate += '    </div>\n  ';
    previewTemplate += '    <div class="dz-error-message">';
    previewTemplate += '        <span data-dz-errormessage></span>';
    previewTemplate += '    </div>\n';
    previewTemplate += '</div>';

    const $dropzone = $('div#dataset');
    console.log('createDropzone');

    const dropzoneUploader = await createDropzone($dropzone[0], {
      url: '/todouploader',
      maxFiles: this.maxFiles,
      maxFilesize: this.maxFileSize,
      timeout: 0,
      autoQueue: false,
      dictDefaultMessage: this.dropzoneParams.data('default-message'),
      dictInvalidFileType: this.dropzoneParams.data('invalid-input-type'),
      dictFileTooBig: this.dropzoneParams.data('file-too-big'),
      dictRemoveFile: this.dropzoneParams.data('remove-file'),
      previewTemplate,
    });

    // 文件发送前调用
    // dropzoneUploader.on('sending', (file, xhr, formData) => {
    //   console.log(xhr)
    //   console.log(formData)
    // });

    // 文件复制后触发
    dropzoneUploader.on('addedfile', (file) => {
      if(file.status == 'added'){
        this.onFileAdded(file)
      } 
    });

    dropzoneUploader.on('success', (file, res) => {
      this.emitDropzoneSuccess(file)
    });

    // dropzoneUploader.on('totaluploadprogress', function(file, progress){
    //   this.updateProgress(file, progress)
    // });

    dropzoneUploader.on('maxfilesexceeded', function (file) {
      if (this.files[0].status !== 'success') {
        alert(this.dropzoneParams.data('waitting-uploading'));
        this.removeFile(file);
        return;
      }
      this.removeAllFiles();
      this.addFile(file);
    });

    this.dropzoneUploader = dropzoneUploader;
  },

  methods: {
    resetStatus() {
      this.progress = 0;
      this.status = '';
    },
    updateProgress(file, progress) {
      file.previewTemplate.querySelector(
        '.dz-upload'
      ).style.width = `${progress}%`;
    },
    emitDropzoneSuccess(file) {
      file.status = 'success';
      this.dropzoneUploader.emit('success', file);
      this.dropzoneUploader.emit('complete', file);
      this.finishUpload(file)
    },
    emitDropzoneFailed(file) {
      this.status = this.dropzoneParams.data('falied');
      file.status = 'error';
      this.dropzoneUploader.emit('error', file);
      // this.dropzoneUploader.emit('complete', file);
    },

    onFileAdded(file) {
      // file.datasetId = document
      //   .getElementById('datasetId')
      //   .getAttribute('datasetId');
      console.log("执行到我了")
      this.resetStatus();
      var file = document.getElementsByClassName('dropzone').files[0]
      console.log("file", file)
      
    // 创建ObsClient实例
    var obsClient = new ObsClient({
      access_key_id: 'FDP3LRMHLB9S77VWEHE3',       
      secret_access_key: 'LyM82Wk80pgjhs2z7AdDcsdpCWhbsJtSzQ7hkESN',       
      server : 'https://112.95.163.82'
    });

    var cp;
    var hook;
    obsClient.uploadFile({
      Bucket : 'mybucket',
      Key : this.get_result().key,
      SourceFile : document.getElementsByClassName('dropzone').files[0],
      PartSize : 64 * 1024 * 1024,
      ProgressCallback : function(transferredAmount, totalAmount, totalSeconds){
          console.log(transferredAmount * 1.0 / totalSeconds / 1024);
          console.log(transferredAmount * 100.0 / totalAmount);
          if(hook && (transferredAmount / totalAmount) > 0.5){
              // 暂停断点续传任务
              hook.cancel();
          }
      },
      EventCallback : function(eventType, eventParam, eventResult){
          // 处理事件响应
          console.log("1", eventType)
             console.log("2",eventParam)
             console.log("3",eventResult)
      },
      ResumeCallback : function(resumeHook, uploadCheckpoint){
          // 获取取消断点续传上传任务控制参数
          hook = resumeHook;
          // 记录断点
          cp = uploadCheckpoint;
      }
}, function(err, result){
    console.error('Error-->' + err);
    // 出现错误，再次调用断点续传接口，继续上传任务
    if(err){
       obsClient.uploadFile({
          UploadCheckpoint : cp,
          ProgressCallback : function(transferredAmount, totalAmount, totalSeconds){
              console.log(transferredAmount * 1.0 / totalSeconds / 1024);
              console.log(transferredAmount * 100.0 / totalAmount);
          },
          EventCallback : function(eventType, eventParam, eventResult){
             // 处理事件响应
             console.log(eventType)
             console.log(eventParam)
             console.log(eventResult)
          },
        }, function(err, result){
          if(err){
              console.error('Error-->' + err);
          }else{
              if(result.CommonMsg.Status < 300){
                 console.log('RequestId-->' + result.InterfaceResult.RequestId);
                 console.log('Bucket-->' + result.InterfaceResult.Bucket);
                 console.log('Key-->' + result.InterfaceResult.Key);
                 console.log('Location-->' + result.InterfaceResult.Location);
              }else{
                 console.log('Code-->' + result.CommonMsg.Code);
                 console.log('Message-->' + result.CommonMsg.Message);
              }
        }
      });
    }else {
         console.log('Status-->' + result.CommonMsg.Status);
         if (result.CommonMsg.Status < 300 && result.InterfaceResult) {
                console.log('RequestId-->' + result.InterfaceResult.RequestId);
         }
    }
});
    },

    get_result(){
      var res
      $.ajax({
        url: '/attachments/get_obs_key',
        type: 'GET',
        async: false,
        success: function(result){
          res = result
        }
      });
      console.log("res=", res)
      return res
    },  

    finishUpload(file) {
      $.ajax({
        url: '/attachments/add',
        type: 'POST',
        data: {
          'uuid': get_result().uuid,
          'file_name': filepath.split('/')[-1],
          'size': file.size,
          'dataset_id': file.datasetId,
          '_csrf': csrf,
          'type': 1
        },
        async: false,
        success: function (data) {
          console.log(data)
        }
      })
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    }

  }
};
</script>

<style>
.dropzone-wrapper {
  margin: 2em auto;
}
.ui .dropzone {
  border: 2px dashed #0087f5;
  box-shadow: none !important;
  padding: 0;
  min-height: 5rem;
  border-radius: 4px;
}
.dataset .dataset-files #dataset .dz-preview.dz-file-preview,
.dataset .dataset-files #dataset .dz-preview.dz-processing {
  display: flex;
  align-items: center;
}
.dataset .dataset-files #dataset .dz-preview {
  border-bottom: 1px solid #dadce0;
  min-height: 0;
}
</style>