<template>
  <div class="form-group">
    <div id="uploadAttachmentForm">
      <label class="control-label" for="uploadAttachmentForm">{{
        $t("lang.approveComment.attachment")
      }}</label>
      <div class="input-group">
        <div>
          <a-upload
            name="file"
            :file-list="fileList"
            :before-upload="beforeUpload"
            :show-upload-list="{ showDownloadIcon: false, showRemoveIcon: false }"
            @change="handleChange"
          >
            <a-button>
              <upload-outlined />
              {{ $t("lang.approveComment.chooseFile") }}
            </a-button>
          </a-upload>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import Common from '../common/Common.js';
import FileImage from '../widget/FileImage.vue';
import { message } from 'ant-design-vue';
import { UploadOutlined } from '@ant-design/icons-vue';


export default {
    
  components: {
    FileImage,
    UploadOutlined,
  },

  props: {
    taskId: {
      type: String,
      default: null,
    },
  },
  data: function () {
    return {
      fileList: [],
      headers: {
        token: localStorage.getItem('#token'),
      },
    };
  },

  methods: {
    beforeUpload: function(file){
      console.log(file);
      const _self = this;
      file.status = 'uploading';
      this.fileList = [...this.fileList, file];
      this.$nextTick(function(){
        _self.uploadFile(file, file.uid);
      });
      return false;
    },


    
    /**
     * 设置上传文件的状态
     */
    setFileStatus : function(uid, status){
      const _self = this;
      for(var i = 0; i < _self.fileList.length; i++){
        if(_self.fileList[i].uid === uid){
          _self.fileList[i].status = status;
          console.debug(JSON.stringify(_self.fileList[i]));
          break;
        }
      }
      this.fileList = [...this.fileList];
    },
    

    handleChange: function(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList);
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} file uploaded successfully`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} file upload failed.`);
      }
    },


    /**
     * 上传文件
     * @param file 文件
     * @param uid 文件唯一标识
     */
    uploadFile: function (file, uid) {
      var _self = this;
      const formData = new FormData();
      formData.append('file', file);
      formData.append('uid', uid);
      formData.append('taskId', _self.taskId);
      formData.append('attachmentType', 'FileAttachment');

      $.ajax({
        url: Common.getApiURL('WorkflowResource/addAttachment'),
        type: 'post',
        beforeSend: function (request) {
          Common.addTokenToRequest(request);
        },
        data: formData,
        contentType: false,
        processData: false,
        success: function (data) {
          if (data.errorCode == 0) {
            const fileUploadResponses = data.datas;
            if (fileUploadResponses != undefined && fileUploadResponses.length > 0) {
              fileUploadResponses.forEach(function (fileUploadResponse) {
                if(fileUploadResponse.errorCode == 0){
                  _self.setFileStatus(fileUploadResponse.uid, 'done');
                }else{
                  _self.setFileStatus(fileUploadResponse.uid, 'error');
                }
              });
            }
          } else {
            message.error(data.errorMessage);
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          Common.processException(XMLHttpRequest, textStatus, errorThrown);
        },
      });
    },
  },
};
</script>
