<template>
<div>
    <!-- :before-upload="_beforeUpload" -->
  <el-upload
    ref="upload_com"
    :headers="headers"
    :action="action"
    :show-file-list="showFileList"
    :file-list="fileList"
    :on-success="_onSuccess"
    :on-preview="_onPreview"
    :http-request="oss_upload"
    :on-remove="_onRemove" 
    :before-remove="_onBeforeRemove"
    :before-upload="_beforeUpload"
    :on-exceed="_onExceed"
    :limit="limit"
    :on-change="handleChange"
    :multiple="multiple">
    <slot></slot>
    <slot name="tip"></slot>
  </el-upload>
  <el-progress v-show="showProcess" :percentage="processLength" :stroke-width="2"></el-progress>
</div>
</template>

<script>
  function noop() {}
  import moment from 'moment'
  import axios from 'axios'
  export default {
    props: {
      action: {
        type: String,
        required: true
      },
      headers: {
        type: Object,
        default() {
          return {};
        }
      },
      data: Object,
      multiple: Boolean,
      name: {
        type: String,
        default: 'file'
      },
      drag: Boolean,
      dragger: Boolean,
      withCredentials: Boolean,
      showFileList: {
        type: Boolean,
        default: false
      },
      accept: String,
      type: {
        type: String,
        default: 'select'
      },
      beforeUpload: Function,
      beforeRemove: Function,
      onRemove: {
        type: Function,
        default: noop
      },
      onBeforeRemove:{
        type: Function,
        default: noop
      },
      onChange: {
        type: Function,
        default: noop
      },
      onPreview: {
        type: Function
      },
      onSuccess: {
        type: Function,
        default: noop
      },
      onProgress: {
        type: Function,
        default: noop
      },
      onError: {
        type: Function,
        default: noop
      },
      fileList: {
        type: Array,
        default() {
          return [];
        }
      },
      autoUpload: {
        type: Boolean,
        default: true
      },
      listType: {
        type: String,
        default: 'text' // text,picture,picture-card
      },
      httpRequest: Function,
      disabled: Boolean,
      limit: {
        type: Number,
        default: ()=>{
          return 1
        }
      },
      onExceed: {
        type: Function,
        default: noop
      }
    },
    name: "upload",
    data() {
      return {
        processLength:0,
        showProcess:false,
        files:{},
        config: null
      }
    },
    methods: {
      handleChange(file,fileList){
        this.files = file
      },
      handleChanges(file){
        if(file.status === 'ready'){
          this.processLength = 0 
          this.showProcess = true
          const interval = setInterval(() => {
            if(this.processLength >= 99){
            clearInterval(interval) 
            return
            }
            this.processLength += 1
          },20)
        }
        if(file.status === 'success'){
          this.processLength =100
          this.showProcess = false
        }
      },
      get_sign(callback) {
        // 测试添加 'https://intesys.cms.g107.com'
        axios.get('https://intesys.cms.g107.com'+'/integral.php/Api/get_signature',{
            headers: {
              'Content-Type': 'application/json; charset=utf-8',
			  'A-Token': this.$getToken()
            }
          }).then(res => {
          this.config = res.data.data
          callback()
        })
      },
      _beforeUpload(file) {
        if(!this.beforeUpload(file)){
          return false
        }else{
          this.handleChanges(this.files)
        }

      },
      oss_upload(upload_obj){
        let self = this
        this.get_sign(function () {
          self.upload(upload_obj.file)
        })
      },
      _onExceed(files, fileList){
        this.$message.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
      },
      _onSuccess(response, file, fileList) {
        this.onSuccess(response, file, fileList)
      },
      _onPreview(file) {
        this.onPreview(file)
      },
      _onRemove(file, fileList) {
        this.onRemove(file, fileList)
      },
      _onBeforeRemove(file, fileList){
        if(file.status == "success"){
          return this.$confirm(`确定移除此项？`)
        }
      },
      random_string(len) {
        len = len || 32
        var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
        var maxPos = chars.length
        var pwd = ''
        for (let i = 0; i < len; i++) {
          pwd += chars.charAt(Math.floor(Math.random() * maxPos))
        }
        return pwd
      },
      upload(item) {
        let self = this
        const photo = item // 获取图片对象
        const photoName = item.name // 原图片的名称
        const url = 'https://integralsys.oss-cn-shenzhen.aliyuncs.com'
        let date = moment().format('YYYY/MM/DD')
        let param = new FormData()
        let randomStr = this.random_string(32)
        let key = 'intesys/dd/' + this.$getUserData().site_id+ '/' + date + '/' + randomStr + '.png'
        param.append('Filename', photoName)
        param.append('key', key)
        param.append('policy', this.config.policy)
        param.append('OSSAccessKeyId', this.config.accessid)
        param.append('success_action_status', '200') // 不要问为什么，照做
        param.append('callback', this.config.callback)
        param.append('signature', this.config.signature)
        param.append('file', photo) // 这个**切记**一定要放到最后去 append ，不然阿里云会一直报 key 的错误
        axios.post(url, param, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }).then(response => {
            if(response.data.Status == 'Ok'){
                this.processLength = 100
                this.showProcess = false
              setTimeout(()=>{
                this.processLength = 0
              },200)
              self.fileList.push({name: randomStr + photoName, url: 'https://integralsys.oss-cn-shenzhen.aliyuncs.com/' + key, name: item.name, response:{
                  url: 'https://integralsys.oss-cn-shenzhen.aliyuncs.com/' + key
                }})
              self._onSuccess({status: 1, url: 'https://integralsys.oss-cn-shenzhen.aliyuncs.com/' + key, file_name: randomStr + photoName}, item, self.fileList)
            }
          }).catch(err => {
            console.log('err == ', err)
            this.showProcess = false
          })
      },
    }
  }
</script>

<style scoped>

</style>
