<template>
  <div>
    <div>
      <el-upload v-loading="loading" element-loading-text="正在上传中..." :disabled="disabled" :file-list="fileList" action="" :limit="maxNumber" :multiple="maxNumber > 0"
                 list-type="picture-card" :auto-upload="false"  :on-change="changeFinish" :accept="typeArray">
        <i slot="default" class="el-icon-plus"></i>
        <div slot="file" slot-scope="{file}">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePreview(file)">
              <i class="el-icon-zoom-in"></i>
            </span>
            <span v-if="!currentDisabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
              <i class="el-icon-download"></i>
            </span>
            <span v-if="!currentDisabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <i class="el-icon-delete"></i>
            </span>
          </span>
        </div>
        <div slot="tip" class="el-upload__tip">{{ placeholder }} {{ sizeTip }} {{ numberTip }}</div>
      </el-upload>
      <!-- <el-dialog :visible.sync="dialogVisible"> -->
          <el-image style="width: 0.5px; height: 0.5px" :src="dialogImageUrl" fit="contain" :preview-src-list="dialogImageUrlSrcList" ref="image__preview" />
      <!-- </el-dialog> -->
    </div>
  </div>
</template>

<script>
import uploadFile from '@/mixins/upload.js'
import { uuid } from "@/utils/index"
import { getUploadFilePath } from "@/config/index"
import {debounce} from '@/utils/index';
export default {
  mixins: [uploadFile],
  name: "ImageUpload",
  components: {},
  props: {
    disabled: {
        type: Boolean,
        default: false,
    },
    filePath: {
        type: String,
        default: 'imageUpload',
    },
    value:{
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '请选择图片'
    },
    maxSize: {
      type: Number,
      default: 5
    },
    maxNumber:{
      type: Number,
      default: 10
    },
    type: {
        type: Array,
        default: () => {
            return ['jpg', 'jpeg', 'png', 'gif', 'bmp']
        }
    },
  },
  mounted() {
    if(this. _fileList && this. _fileList.length) {
      this.fileList = JSON.parse(JSON.stringify(this. _fileList)) 
    }
  },
  watch: {
    value: {
        handler(newValue, oldValue) {
            this.aFileList();
        },
    },
    fileList: {
      // 监听数据 获取到数据里的数组数据
      handler(val) {
          if(val && val.length) {
            let dialogImageUrlSrcList = []
            val.forEach(item => {
               if(item.raw) {
                dialogImageUrlSrcList.push(this.previewImg(item.raw))
              }else {
                dialogImageUrlSrcList.push(item.url)
              }
            })
            this.dialogImageUrlSrcList = dialogImageUrlSrcList
          }
      },
      deep: true, // 深度监听
      immediate:true, //当 watch 一个变量的时候，初始化时并不会执行你需要在created的时候手动调用一次。添加immediate属性，这样初始化的时候也会触发
    },
  },
  computed: {
    typeArray () {
        return this.type.map(item => `.${item}`).join(",")//转换结果为.jpg,.png
    },
    sizeTip() {
      return this.maxSize > 0 ? `| 每张图不超过${this.maxSize}MB` : ''
    },
    numberTip() {
      return this.maxNumber > 0 ? `| 图片数量不得超过${this.maxNumber}张` : ''
    },
    _fileList() {
        let fileList = []
        if(this.value) {
          let value = this.value.split(",");
          value.forEach(item => {
            let itemArr = item.split('/');
            let name = itemArr[itemArr.length - 1];
            let i = {
              name: name,
              url: getUploadFilePath(item),
              value: item
            }
            fileList.push(i);
          })
        }
        return fileList
    },
  },
  data() {
    return {
      loading: false,
      currentDisabled: false,
      dialogImageUrl: '',
      dialogVisible: false,
      fileList:[],
      dialogImageUrlSrcList: []
    }
  },
  methods: {
    aFileList() {
        let fileList = [];
        if (this.value) {
            let value = this.value.split(',');
            value.forEach((item) => {
                let itemArr = item.split('/');
                let name = itemArr[itemArr.length - 1];
                let i = {
                    name: name,
                    url: getUploadFilePath(item),
                    value: item,
                };
                fileList.push(i);
            });
        }
        this.fileList = fileList;
    },
    beforeUpload(file){
      const alows = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg', 'image/bmp'];
      if (alows.indexOf(file.type) === -1){
        this.$message.warning("存在不支持的图片格式")
      }else if(this.maxSize > 0 && file.size / 1024 / 1024 > this.maxSize){
        this.$message.warning(`单张图片最大不超过 ${this.maxSize}MB`)
      }else {
        return true
      }
      return false
    },
    changeFinish: debounce(function (file, fileList){
      this.loading = true;
      let targetFileList = fileList;
      let originFileList = [];
      let originFileListArr = [];
      let upFileList = [];
      let originUpFileList = [];
      let namesArr = [];
      targetFileList.forEach(item => {
        if(item.status !== 'success') {
          upFileList.push(item.raw);
          // namesArr.push(`${item.name}`);
          let nameArr = item.name.split('.')
          let fileType = nameArr[nameArr.length - 1];
          let newName = `${uuid() + new Date().getTime() + '.' + fileType}`;
          namesArr.push(newName);
          item.newName = newName
          originUpFileList.push(item);
        }else {
          originFileList.push(item.value)
          originFileListArr.push(item)
        }
      })
      this.fileList = JSON.parse(JSON.stringify(originFileListArr));
      if(!this.beforeUpload(file.raw)) {
        this.loading = false;
        return false
      }
      if(upFileList.length) {
        this.uploadFileRemoteRename(upFileList, [`${this.filePath}/${Date.now()}`], namesArr)
             .then((res) => {
                let newList = [...originFileList,...res];
                res.forEach(item => {
                      let itemArr = item.split('/');
                      let name = itemArr[itemArr.length - 1];
                      let uidItem =  originUpFileList.find(o => o.newName && o.newName === name);
                      // let uidItem =  originUpFileList.find(o => o.name === name);
                      let i = {
                        name: uidItem.name,
                        url: getUploadFilePath(item),
                        value: item,
                        uid: uidItem.uid
                      }
                      this.fileList.push(i)
                })
                this.$emit("input", newList);
                this.loading = false;
            }).catch((err) => {
              this.$emit("input", originFileList);
              this.loading = false;
            })
      }else  {
        this.$emit("input", originFileList);
        this.loading = false;
      }
    },
			1000,
			false
		),
    getFileList(fileList) {
        let targetList = fileList.map(item => {
            if(item.raw) {
                return item.raw 
            }else {
                return item
            }
        })
        return targetList
    },
    handleRemove(file){
      if(!this.disabled) {
        let value = ''
        let valueArr = []
        this.fileList = this.fileList.filter(item => item.value !== file.value);
        let newFlie = JSON.parse(JSON.stringify(this.fileList));
        if(newFlie && newFlie.length) {
          newFlie.forEach(item => {
            valueArr.push(item.value)
          })
        //   value = valueArr.join(",")
        }
        this.$emit('remove', valueArr);
      }
    },
    handlePreview(file){
        let firstArr = [];
        let secondArr = [];
        let newFileList = [];
        let flag = false;
        this.fileList.forEach(item => {
          if(item.uid === file.uid) {
            flag = true
          }
          if(flag) {
            firstArr.push(item)
          }else {
            secondArr.push(item)
          }
        })
        newFileList = [...firstArr,...secondArr]
        if(newFileList && newFileList.length) {
          let dialogImageUrlSrcList = []
          newFileList.forEach(item => {
            if(item.raw) {
              dialogImageUrlSrcList.push(this.previewImg(item.raw))
            }else {
              dialogImageUrlSrcList.push(item.url)
            }
          })
          this.dialogImageUrlSrcList = dialogImageUrlSrcList
        }        
        this.$refs.image__preview.clickHandler();
        // if(file.raw) {
        //     this.previewImg(file.raw);
        // }else {
        //     this.dialogImageUrl = file.url;
        //     this.dialogVisible = true;
        // }
    },
    previewImg(file) {
        let reader = new FileReader(); //调用FileReader
        // reader.readAsDataURL(files[0]); //将文件读取为 DataURL(base64)
        reader.readAsDataURL(file); //将文件读取为 DataURL(base64)
        reader.onload = (evt) => {
            this.dialogImageUrl = evt.target.result;
            this.dialogVisible = true;
        };
    },
    handleDownload(file) {
        this.downs(file.url);
    },
    downloadIamge(imgsrc, name) {
      let image = new Image();
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d"); 
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png");
        let a = document.createElement("a"); 
        let event = new MouseEvent("click"); 
        a.download = name || "photo"; 
        a.href = url; 
        a.dispatchEvent(event);
      };
      image.src = imgsrc;  // 指定图片的来源，这是需要我们提供的
    },
    // 使用时，只需要修改downs函数
    // imageUrl是图片的地址
    downs(imageUrl) {
        // 默认以时间来命名图片，防止重名
      let name = new Date().getTime();
      this.downloadIamge(imageUrl, `${name}`);
    }
  },
  destroyed() {
    this.$emit("input", []);
  } 
}
</script>

<style lang="scss" scoped>
.design {
  i {
    padding: 10px;
    font-size: xx-large;
    background: white;
    border: 1px dashed #8c8c8c;
  }
}
::v-deep  .el-upload--picture-card{
  width: 80px;
  height: 80px;
  line-height: 87px;
}
::v-deep  .el-upload-list__item{
  width: 80px;
  height: 80px;
  .el-upload-list__item-actions{
    &> span+span{
      margin: 1px;
    }
  }
}
::v-deep .el-upload-list__item.is-ready {
    display: none;
}
</style>