<!--
 * @Descripttion: 当前组件信息
 * @version: 1.0.0
 * @Author: 无尘
 * @Date: 2019-02-21 14:40:12
 * @LastEditors: 无尘
 * @LastEditTime: 2019-09-25 17:12:38
 -->
<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">
            <a class="item-img" :href="item.url">
              <img :src="item.url" alt="上传图片" />
            </a>
            <!-- 预览和删除按钮 -->
            <div class="upload-icon__btn">
              <i class="el-icon-view" @click="previewImage(index)"></i>
              <i class="el-icon-delete" @click="deleteImage(index)"></i>
            </div>
          </div>
        </transition-group>
      </draggable>
      <!-- 上传进度条 -->
      <div :class="['img-content', 'img-progress', imageList.length >= 6 ? 'm-t-8' : '']" v-if="!pass && progress !== 0">
        <el-progress class="gic-img-progress" :width="102" :percentage="progress" :status="propStatus" style="line-height: 102px;"></el-progress>
      </div>
      <!-- 图片上传部分 -->
      <div :class="['img-upload', imageList.length >= 6 ? 'm-t-8' : '']" v-if="imageList && imageList.length < maxImageLength">
        <el-upload class="loader" accept="image/jpg,image/jpeg,image/png,image/gif" :action="uploadUrl()" list-type="picture-card" :on-change="uploadOnChange" :before-upload="beforeAvatarUpload" :on-success="uploadOnSuccess" :on-error="uploadOnError" :on-progress="uploadOnProgress">
          <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.url" />
        </el-carousel-item>
      </el-carousel>
    </el-dialog>
  </div>
</template>

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

  data() {
    return {
      dragImageList: this.imageList, // 传递的图片数据
      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';
      }
    }
  },
  /* eslint-disable */
  beforeMount() {
    // this.action = this.actionUrl;
  },
  methods: {
    // 获取 action 的 url
    uploadUrl() {
      let that = this;
      let host = window.location.origin;
      let baseUrl;
      let wxFlag;
      wxFlag = !!that.wxFlag && that.wxFlag != ''? 'wxFlag='+that.wxFlag + '&': '';
      if (host.indexOf('localhost') != '-1') {
        baseUrl = 'http://www.gicdev.com';
      }else {
        baseUrl = host;
      }
      that.upUrl = baseUrl + that.actionUrl +'?'+ wxFlag+ 'requestProject=' + that.projectName;
      return that.upUrl;
    },
    // 上传之前回调
    beforeAvatarUpload(file) {
      let that = this;
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/jpg';
      const isLt2M = file.size / 1024 / 1024 < 2;
      // if (!isJPG) {
      //   that.$message.error('上传图片只能是 JPG/JPEG 格式!');
      // }
      if (!isLt2M) {
        that.$message.error('上传图片大小不能超过 2MB!');
      }
      return isLt2M && 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);
              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);
      })
    },
    // 上传成功
    uploadOnSuccess(res, file) {
      let that = this;
      this.pass = true;
      if (res.errorCode == 1) {
        that.$message.success('上传成功');
        that.$emit('uploadOnSuccess',{res:res,file:file}, that.imageList);
      }else {
        that.$message.error(res.message);
      }

    },
    // 开始上传
    uploadOnProgress(e, file) {
      if (e && e.percent) {
        this.progress = Math.floor(e.percent);
      }
    },
    uploadOnChange(file) {
      if (file.status === 'ready') {
        this.pass = null;
        this.progress = 0;
      } else if (file.status === 'fail') {
        this.$message.error('图片上传失败，请重试！');
      }
    },
    /* eslint-disable */
    uploadOnError() {

    },
    // 预览图片
    previewImage(i) {
      this.isEnlargeImage = true;
      this.initialImg = i;
    },
    // 删除图片
    deleteImage(i) {
      let that = this;
      that.$emit('deleteImage', i);
      // this.imageList.splice(i, 1);
      let newList = JSON.parse(JSON.stringify(this.imageList));
      newList.splice(i, 1);
      that.$emit('update:imageList', newList);
    },

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

    // move end
    itemMoveEnd(evt) {
      let that = this;
      that.$emit('sortImg', that.dragImageList);
      that.$emit('update:imageList', that.dragImageList);
    }

  },
  watch: {
    imageList: function(newData,oldData){
      let that = this;
      that.dragImageList = newData;
    },
  },
  /* 接收数据 */
  /* eslint-disable */
  mounted() {
    let that = this;
    // that.dragImageList = that.imageList
  },
  components: {
    draggable
  },
};
</script>

<style type="text/scss" lang="scss">
.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, .5);
  transition: all .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;
}


.gic-upload__img {
  .el-upload--picture-card {
    width: 104px;
    height: 104px;
    line-height: 104px;
  }

  .el-upload-list--picture-card{
    display: none;
  }
}
.slide-fade-enter-active {
  transition: all .6s ease;
}
.slide-fade-leave-active {
  transition: all .6s cubic-bezier(.55, 0, .1, 1);
}
.slide-fade-enter, .slide-fade-leave-to {
  opacity: 0;
}
</style>
