<template>
  <div class="bml-uploader">
    <div class="bml-uploader_hd">
      <div class="bml-uploader_title">{{title}}</div>
    </div>
    <div class="bml-uploader_tips" v-if="tips">{{tips}}</div>
    <div v-else><slot name="tips"></slot></div>
    <div class="bml-uploader_bd">
      <div class="bml-uploader_file" @click="previewImage(index)" v-for="(item,index) in currentFiles">
        <image class="bml-uploader_img" :src="item" resize="cover" />
      </div>
      <div class="bml-uploader_input-box" @click="chooseImage" v-if="enabled">
        <bml-icon class="bml-upload-icon" color="#cecece" name="ion-ios-plus-empty" size="160" @click="chooseImage"></bml-icon>
      </div>
    </div>
  </div>
</template>
<script>
import bmlIcon from './bml-icon.vue';

export default {
  name: 'bml-uploader',
  components: {bmlIcon},
  props: {
    title: {
      type: String,
      default: '图片上传'
    },
    maxCount: {
      type: Number,
      default: 1
    },
    files: {
      type: Array,
      default: []
    },
    tips: {
      type: String,
      default: ''
    },
    extClass: {
      type: String,
      default: ''
    },
    uploadUrl: {
      type: String,
      default: ''
    },
    enabled: {
      type: Boolean,
      default: false
    },
    params:{
      type: Object,
      default: {}
    },
    header:{
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      currentFiles: [],
    }
  },
  created() {
    if(this.files){
        for(var key in this.files){
          this.currentFiles.push(this.files[key])
        }
        
      }
  },
  methods: {

    previewImage(index){
      let imageList = []

      if(this.currentFiles){
        for(var key in this.currentFiles){
          imageList.push(this.currentFiles[key])
        }
      }

      this.$image.preview({index:index,images:imageList}).then(res => {})

    },

    chooseImage(event){
      let that = this
      this.$image.pickAndUpload({maxCount:this.maxCount,imageWidth:1080,url:this.uploadUrl + '/image/upload',params:this.params,header:this.header}).then(res=>{
        for(var index in res){
          let result = res[index]
          if(result.errcode===0){
            let filename = result.data
            let timestamp =Date.parse(new Date())
            let fileUrl = that.uploadUrl + '/image/fetch?file=' + that.params.path + '/' + filename + '&time='+ timestamp
            that.currentFiles.push(fileUrl)
            if(that.files){
              that.files.push(fileUrl)
            }
          }
        }
      })
     
    }
  }
}
</script>
<style lang="scss" src="../css/uploader.scss"/>