<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2018-12-06 13:44:22
 * @LastEditors  : 无尘
 * @LastEditTime : 2019-12-25 14:55:35
 -->
<!--
  多个上传组件
   <mult-upload-image
    :imageList="imageList"
    :originList = "originList"
    :disabled="disabled"
    @deleteImage="deleteImage"
    @sortImg = "sortImg"
    @uploadOnSuccess="uploadOnSuccess">
  </mult-upload-image>
 -->
<template>
  <div class="gic-upload__img">
    <!-- 上传成功的图片展示 -->
    <div class="gic-upload__img__drag">
      <draggable :options="{ group: { name: 'people', pull: false, put: true }, sort: true }" v-model="dragImageList" @end="itemMoveEnd" class="drag-wrap" style="display: contents;">
        <transition-group name="slide-fade">
          <div v-for="(item, index) in imageList" :class="['img-content', index >= 6 ? 'm-t-8' : '']" :key="index + 'img'">
            <a class="item-img" :href="item.imgUrl">
              <img :src="item.imgUrl" alt="上传图片" />
            </a>
            <!-- 预览和删除按钮 -->
            <div class="upload-icon__btn">
              <i class="el-icon-view" @click="previewImage(index)"></i>
              <i v-if="!disabled" class="el-icon-delete" @click="deleteImage(index)"></i>
            </div>
          </div>
        </transition-group>
      </draggable>
      <!-- 上传进度条 -->
      <div v-if="!pass && progress !== 0" :class="['img-content', 'img-progress', imageList.length >= 6 ? 'm-t-8' : '']">
        <el-progress class="gic-img-progress" :width="102" :percentage="progress" :status="propStatus" style="line-height: 102px;"></el-progress>
      </div>
      <!-- 图片上传部分 -->
      <div v-if="imageList && imageList.length < maxImageLength" :class="['img-upload', imageList.length >= 6 ? 'm-t-8' : '']">
        <el-upload :disabled="disabled" multiple class="loader" accept="image/jpg,image/jpeg,image/png,image/gif,image/bmp" :file-list="fileDatas" :action="uploadUrl()" list-type="picture-card" :limit="9" :on-exceed="handleExceed" :on-change="uploadOnChange" :before-upload="beforeAvatarUpload" :on-error="uploadOnError" :on-progress="uploadOnProgress"
          ><!-- :file-list="fileDatas" -->
          <i class="el-icon-plus gic-upload-btn"></i>
        </el-upload>
      </div>
    </div>

    <el-dialog title="图片预览" :visible.sync="isEnlargeImage" :modal-append-to-body="false" :before-close="handleClose" width="520px">
      <el-carousel v-if="isEnlargeImage" trigger="click" :initial-index="initialImg" :autoplay="false" height="500px">
        <el-carousel-item v-for="(img, index) in imageList" :key="index" style="display: flex;align-items: center;justify-content: center;">
          <img @click="isEnlargeImage = false" style="max-width: 480px;max-height: 500px;" :src="img.imgUrl" />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>

<script>
/**
    放大预览
    删除
    添加到循环里面
    开始上传 上传失败 上传成功三个步骤
    上传图片的进度条是固定的样式大小、如果我这边修改的话
    会不会影响其他地方的样式
   */
import draggable from 'vuedraggable';
export default {
  name: 'mult-upload-image',
  props: {
    projectName: {
      type: String,
      default: 'haoban-manage-web'
    },
    disabled: {
      type: Boolean,
      default: false
    },
    wxFlag: {
      type: String,
      default: '1'
    },
    imgRate: {
      type: String
    },
    // 上传地址
    actionUrl: {
      type: String,
      default: '/haoban-manage-web/upload-img'
    },
    // 图片限制 不能超过 超过隐藏上传按钮
    maxImageLength: {
      type: Number,
      default: 9
    },
    limitW: {
      type: Number
    },
    limitH: {
      type: Number
    },
    imageList: {
      type: Array,
      default() {
        return [];
      }
    },
    originList: {
      type: Array,
      default() {
        return [];
      }
    }
  },

  data() {
    return {
      dragImageList: JSON.parse(JSON.stringify(this.imageList)), // 传递的图片数据
      fileDatas: JSON.parse(JSON.stringify(this.originList)),
      initialImg: 0, // 初始索引
      progress: 0, // 上传进度
      pass: null, // 是否上传成功
      isEnlargeImage: false, // 放大图片
      enlargeImage: '' // 放大的图片的地址
    };
  },
  computed: {
    propStatus() {
      if (this.pass) {
        return 'success';
      } else if (this.pass === false) {
        return 'exception';
      } else {
        return 'text';
      }
    }
  },
  beforeMount() {
    // this.action = this.actionUrl;
  },
  methods: {
    // 获取 action 的 url
    uploadUrl() {
      const that = this;
      const host = window.location.origin;
      let baseUrl;
      let wxFlag;
      wxFlag = !!that.wxFlag && that.wxFlag != '' ? 'wxFlag=' + that.wxFlag + '&' : '';
      if (host.indexOf('localhost') != '-1') {
        baseUrl = 'https://www.gicdev.com';
      } else {
        baseUrl = host;
      }
      that.upUrl = baseUrl + that.actionUrl + '?' + wxFlag + 'requestProject=' + that.projectName;
      return that.upUrl;
    },
    // 上传之前回调
    beforeAvatarUpload(file) {
      const that = this;
      // const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/jpg';
      const isLt5M = file.size / 1024 / 1024 < 5;

      // if (!isJPG) {
      //   that.$message.error('上传图片只能是 JPG/JPEG 格式!');
      // }
      if (!isLt5M) {
        that.$message.error('上传图片大小不能超过 5MB!');
      }
      return (
        isLt5M &&
        new Promise(function(resolve, reject) {
          let reader = new FileReader();
          reader.onload = function(event) {
            let image = new Image();
            image.onload = function() {
              let width = this.width;
              let height = this.height;

              // console.log(width,height,!that.imgRate)
              if (!!that.imgRate && that.imgRate !== '') {
                let limitRate = Number(that.imgRate.split(':')[0]) / Number(that.imgRate.split(':')[1]);
                let realRate = Number(width) / Number(height);
                // console.log(limitRate, realRate);
                if (limitRate != realRate) {
                  that.$message.error('上传图片比例不正确!');
                  reject();
                }
              }
              if ((!that.imgRate || that.imgRate == '') && !!that.limitW && that.limitH && width !== that.limitW && height !== that.limitH) {
                that.$message.error('上传图片尺寸不正确!');
                reject();
              }
              resolve();
            };
            image.src = event.target.result;
          };
          reader.readAsDataURL(file);
        })
      );
    },
    // 开始上传
    uploadOnProgress(e, file) {
      const that = this;
      if (e && e.percent) {
        that.progress = Math.floor(e.percent);
      }
    },
    uploadOnChange(file, fileList) {
      const that = this;
      if (file.status === 'ready') {
        that.pass = null;
        that.progress = 0;
      } else if (file.status === 'fail') {
        that.$message.error('图片上传失败，请重试！');
      }
      /* eslint-disable */
        that.fileDatas = fileList;
        console.log('fileList:', fileList, that.fileDatas)
        that.$nextTick(() => {
          let list = [];
          if (fileList.length) {
            fileList.forEach(ele => {
              list.push({
                imgUrl: ele.response.result[0].qcloudImageUrl
              })
            })
          }
          that.$emit('uploadOnSuccess', list, fileList);
          that.pass = null;
          that.progress = 0;
        })


      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 9 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
      },
      uploadOnError() {
        this.$message.error('图片上传失败，请重试！');
      },
      // 预览图片
      previewImage(i) {
        this.isEnlargeImage = true;
        this.initialImg = i;
      },
      // 删除图片
      deleteImage(i) {
        /* eslint-disable */
        const that = this;
        if (that.disabled) {
          return false;
        }
        this.$emit('deleteImage', i);
        // this.imageList.splice(i, 1);
      },

      // 关闭弹层
      handleClose(done) {
        done();
      },

      // move end
      itemMoveEnd(evt) {
        const that = this;
        for (let index = 0; index < that.dragImageList.length; index++) {
          that.fileDatas[index].response.result[0].qcloudImageUrl = that.dragImageList[index].imgUrl;
        }
        that.$emit('sortImg', that.dragImageList, that.fileDatas);
      }
    },
    watch: {
      imageList: function(newData, oldData) {
        const that = this;
        that.dragImageList = JSON.parse(JSON.stringify(newData));
      },
      originList: function(newData, oldData) {
        const that = this;
        that.fileDatas = JSON.parse(JSON.stringify(newData));
      }
    },
    /* 接收数据 */
    mounted() {
      const that = this;
      that.dragImageList = JSON.parse(JSON.stringify(that.imageList));
      that.fileDatas = JSON.parse(JSON.stringify(that.originList));
    },
    components: {
      draggable
    }
  };
</script>

<style>
  .el-upload-dragger {
    height: 104px;
    line-height: 104px;
    width: 104px;
    background-color: transparent;
  }
  
  .gic-upload__img {
    display: inline-block;
  }
  
  .gic-upload__img__drag {
    max-width: 680px;
    display: inline-block;
    font-size: 0;
  }
  
  .gic-upload__img .img-content {
    position: relative;
    display: inline-block;
    vertical-align: middle;
    margin-right: 8px;
    width: 104px;
    height: 104px;
    box-sizing: border-box;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
  }
  
  .img-content.m-t-8 {
    margin-top: 8px;
  }
  
  .gic-upload__img .img-content .upload-icon__btn {
    position: absolute;
    font-size: 16px;
    display: none;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
  
  .gic-upload__img .img-content .item-img {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 8px;
    height: 86px;
    width: 86px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    /*border: 1px solid #dcdfe6;*/
    border-radius: 0;
  }
  
  .gic-upload__img .img-content .item-img img {
    position: static;
    display: block;
    max-width: 86px;
    max-height: 86px;
  }
  
  .gic-upload__img .img-content::after {
    position: absolute;
    top: 8px;
    left: 8px;
    z-index: 1;
    content: ' ';
    display: block;
    height: 86px;
    width: 86px;
    background-color: rgba(0, 0, 0, 0.5);
    transition: all 0.3s;
    opacity: 0;
  }
  
  .gic-upload__img .img-content:hover::after {
    opacity: 1;
  }
  
  .gic-upload__img .img-content:hover .upload-icon__btn {
    display: block;
    z-index: 100;
    color: #fff;
  }
  
  .gic-upload__img .img-upload {
    display: inline-block;
    vertical-align: middle;
    font-size: 28px;
  }
  
  .img-upload.m-t-8 {
    margin-top: 8px;
  }
  
  .el-upload-list--picture-card {
    display: none;
  }
  
  .el-upload--picture-card {
    width: 104px;
    height: 104px;
    line-height: 104px;
  }
  
  .slide-fade-enter-active {
    transition: all 0.6s ease;
  }
  
  .slide-fade-leave-active {
    transition: all 0.6s cubic-bezier(0.55, 0, 0.1, 1);
  }
  
  .slide-fade-enter,
  .slide-fade-leave-to {
    opacity: 0;
  }
</style>