<template>
  <div>
    <el-upload ref="imgUpload" v-loading="loadding" class="avatar-uploader" :headers="accessToken" :action="uploadFile"
      :accept="accept" list-type="picture-card"  :file-list="files" :on-remove="removeImage"
      :on-preview="handlePictureCardPreview" :on-progress="uploadProgrees"
      :on-error="uploadError" :on-success="uploadImgSuccess_FuJian" :on-change="handleLimit">
      <i class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible" title="查看图片">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  export default {
    model: {
      prop: 'name',
      event: 'change'
    },
    props: {
      placeholder: {
        type: String,
        default: ''
      },
      bucket: {
        type: String,
        default: 'abc'
      },
      // 长度
      img: {
        type: String,
        default: ''
      },
      // limit: {
      //   type: Number,
      //   default: ''
      // },
      accept: {
        type: String,
        default: '.jpg,.jpeg,.png,.JPG,.JPEG,'
      },
      // 文件名称
      imgUrl: {
        type: Array,
        required: true
      },
      uploadData: {
        type: Object,
        default: {}
      }
    },
    data() {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        accessToken: null,
        fileList_FuJian: [],
        enclosure: '', 
        file_add: '',
        file_catch: '',
        files: [],
        files_list: [],
        filedUrl: '',
        isview: false,
        nameArr: '',
        loadding: false,
        uploadFile:
        "http://jianguan.yyundong.com/warehouseapi/v1/shstorehouse/upload",
      }
    },
    watch: {
      imgUrl: {
        deep: true,
        immediate: true,
        handler(newVal, oldVal) {
          if(newVal.url!=undefined){
            let copy = newVal.slice();

             this.files = copy
          }

        }
      }
    },
    mounted() {
      // this.$nextTick(() => {
      //   this.Init()
      // })
    },
    created() {

    },
    methods: {
      showImg(imgList) {
        this.files = imgList
      },
      view() {
        // window.open(this.filedUrl)
      },
      handleLimit(file, list) {
        if (list.length > 0) {
         this.files = [list[list.length - 1]]; // 这一步，是 展示最后一次选择的csv文件
        }
   },
      Init() {
        if (this.name !== undefined) {
          this.files = []
          for (var i = 0; i < this.name.length; i++) {
            this.files.push({
              name: this.name[i],
              url: this.name[i]
            })
          }
        }
      },
      handlePictureCardPreview(file) {
        this.dialogVisible = true
        this.dialogImageUrl = file.url
      },
      // 上传方案--成功后执行
      uploadImgSuccess_FuJian(response, file, fileList) {
        if (file.response.code === '200') {
          this.loadding = false
          // 返显图片
          this.filedUrl = file.response.data
          this.$emit('change', this.files)
          this.$emit('eett', this.files)
        }
      },

      removeImage(file, ImageFileList) {
        this.files.splice(this.files.indexOf(file), 1)
        const imgFiles = []
        this.files.forEach((o) => {
          imgFiles.push(o.url)
        })
        this.$emit('fileChange', this.files)
        this.$emit("passfunction",this.files)
      },
      handleRemove(file, fileList) {
        console.log('file:' + JSON.stringify(file))
        console.log('fileList:' + JSON.stringify(fileList))
        this.enclosure = ''
        // 1. 保存新增文件id(this.file_add)
        this.getNewFileId(fileList)
        // 2. 保存数据库读取的已有文件id(this.file_catch)
        this.getCatchFileId(file)
        // 3. 保存并拼接id
        this.getFileId()
        // 4. 返回拼接id
        this.$emit('change', this.enclosure)
      },
      // 返回this.file_add(新上传文件的id拼接集合)
      getNewFileId(fileList) {
        // debugger
        this.file_add = ''
        for (var i = 0; i < fileList.length; i++) {
          if (fileList[i].response && fileList[i].response.code === '200') {
            this.file_add = this.file_add + fileList[i].response.data + ','
          }
        }
        if (this.file_add !== '') {
          this.file_add = this.file_add.substring(0, this.file_add.length - 1)
        }
        // console.log('1. this.file_add: ' + this.file_add)
      },
      // 返回this.file_catch（数库一寸照的文件的id的拼接集合）
      getCatchFileId(file) {
        for (var i = 0; i < this.files_list.length; i++) {
          if (this.file_catch !== '') {
            // 1. 检查当前删除的文件是否是修改文件列表里面的，如果是，将修改列表里去除此id
            if (this.files_list[i].name === file.name) {
              // 2. 拆开file_catch到fils_arry
              var fils_arry = this.file_catch.split(',')
              // 3. 从fils_arry去除 this.files_list[i].id
              var arry = []
              fils_arry.forEach((element) => {
                // 不加载文件里面的
                if (element !== this.files_list[i].id) {
                  arry.push(element)
                }
              })
              // 4. 重新拼接成file_catch
              this.file_catch = arry.join(',')
            }
          }
        }
        // console.log('2. this.file_catch:' + this.file_catch)
      },
      // 保存并拼接id
      getFileId() {
        // console.log('3. this.file_catch:' + this.file_catch + ',this.file_add:' + this.file_add)
        if (this.file_catch !== '') {
          if (this.file_add !== '') {
            this.enclosure = this.file_catch + ',' + this.file_add
          } else {
            this.enclosure = this.file_catch
          }
        } else {
          this.enclosure = this.file_add
        }
      },
      // 上传失败
      uploadError() {
        this.loadding = false
      },
      uploadProgrees(event, file, fileList) {
        if (Number(event.percent) > 0) {
          this.loadding = true
        }
        //   console.log('event:', event)
      }
    }
  }
</script>

<style scoped></style>
