<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 createDropzone from '../features/dropzone.js';
import ObsClient from 'esdk-obs-browserjs';

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('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) {
      this.resetStatus();
      this.status = this.dropzoneParams.data('obs-connecting');
      this.do_multi_uploader(file) 
    },

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

    // 构建ObsClient
    getObsClient(){
      return new ObsClient({
        access_key_id: 'FDP3LRMHLB9S77VWEHE3',       
        secret_access_key: 'LyM82Wk80pgjhs2z7AdDcsdpCWhbsJtSzQ7hkESN',       
        server : 'https://obs.cn-south-222.ai.pcl.cn'
      });
    },

    // 断点续传
    do_multi_uploader(file){
      console.log("file = ", file)
      const result = this.get_result()
      const _this = this
      const upload_datasetId = document
        .getElementById('datasetId')
        .getAttribute('datasetId');
      const obsClient = this.getObsClient()
      var cp;
      var hook;

      obsClient.uploadFile({
        Bucket : 'testopendata',
        Key : result.key,
        SourceFile : file,
        PartSize : 64 * 1024 * 1024,

        // 更新进度条
        ProgressCallback : function(transferredAmount, totalAmount, totalSeconds){
          _this.updateProgress(file, ((transferredAmount / totalAmount) * 100).toFixed(2))
          _this.status = `${_this.dropzoneParams.data('uploading')} ${(
            (transferredAmount / totalAmount) *
            100
          ).toFixed(2)}%`;
        },

        // 监听文件上传结果
        EventCallback : function(eventType, eventParam, eventResult){

          // 文件上传成功
          if(eventType == 'completeMultipartUploadSucceed'){
            $.ajax({
              url: '/attachments/add',
              type: 'POST',
              data: {
                'uuid': result.uuid,
                'file_name': file.name,
                'size': file.size,
                'dataset_id': upload_datasetId,
                '_csrf': csrf,
                'type': 1
              },
              async: false,
              success: function (data) {
                _this.progress = 100;
                _this.status = this.dropzoneParams.data('upload-complete');
                _this.emitDropzoneSuccess(file)
              },
              error: function(){
                console.log("发送/attachments/add的post错误1")
                _this.emitDropzoneFailed(file)
              }
            });
            
          }
        },
        ResumeCallback : function(resumeHook, uploadCheckpoint){
          hook = resumeHook;
          cp = uploadCheckpoint;
        }
      }, function(err, result){     
          // 出现错误，再次调用断点续传接口，继续上传任务
          if(err){
            obsClient.uploadFile({
              UploadCheckpoint : cp,

              // 断点续传后继续更新进度条
              ProgressCallback : function(transferredAmount, totalAmount, totalSeconds){
                _this.updateProgress(file, ((transferredAmount / totalAmount) * 100).toFixed(2))
                _this.status = `${_this.dropzoneParams.data('uploading')} ${(
                  (transferredAmount / totalAmount) *
                  100
                ).toFixed(2)}%`;
              },

              // 监听断点续传的结果
              EventCallback : function(eventType, eventParam, eventResult){
                // 文件断点续传成功
                if(eventType == 'completeMultipartUploadSucceed'){
                  $.ajax({
                    url: '/attachments/add',
                    type: 'POST',
                    data: {
                      'uuid': result.uuid,
                      'file_name': file.name,
                      'size': file.size,
                      'dataset_id': upload_datasetId,
                      '_csrf': csrf,
                      'type': 1
                    },
                    async: false,
                    success: function (data) {
                      _this.progress = 100;
                      _this.status = this.dropzoneParams.data('upload-complete');
                      _this.emitDropzoneSuccess(file)
                    },
                    error: function(){
                      _this.emitDropzoneFailed(file)
                      console.log("发送/attachments/add的post错误2")
                    }
                  });
                }else if (eventType == 'uploadPartFailed'){
                  _this.emitDropzoneFailed(file)
                  console.log("经过断点上传之后还是不能上传成功，该分段上传失败")
                }
              }
            });   
          }
      });
    },
  }
};
</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>