<template>
  <div
    class="el-upload-multiple"
    :class="{'el-upload--disabled': disabled}"
  >
    <Draggable
      class="el-upload-list"
      v-model="imgUrls"
      v-bind="{draggable: '.el-upload-item', disabled: showDraggable}"
      @update="updateImgSort"
    >
    <!-- 图片展示 -->
    <div
      class="el-upload-list__item--space el-upload-item"
      :style="{ width: `${width}px`, height: `${height}px`}"
      v-for="(url, index) in imgUrls"
      :key="index"
    >
      <img
        class="el-upload-item__img"
        :src="url">
      <div class="el-upload-item__hover">
        <div
          v-if="showDelete && !disabled"
          class="el-upload-item__del"
          :class="`el-upload-item__del--${delPosition}`"
          @click="delMultImg(index)"
        >
          <i class="el-icon-close"></i>
        </div>
        <div class="el-upload-item__btn">
          <div
            v-if="showEdit && !disabled"
            class="el-upload-item__btn-text el-upload-item__btn-text--edit"
            @click="editMultImg(index)"
          >
            {{ editText }}
          </div>
          <div
            v-if="showCropper && !disabled"
            class="el-upload-item__btn-text el-upload-item__btn-text--cropper"
            @click="cropperMultImg(index, url)"
          >
            {{ cropperText }}
          </div>
        </div>
      </div>
    </div>
    <!-- 多图片上传按钮 -->
    <div
      class="el-upload-btn"
      :class="{'el-upload-btn--none': showUploadBtn}"
      :style="{ width: `${width}px`, height: `${height}px`, 'background-image':  `url(${baseImg})`}"
      @click="uploadTrigger(-1)"
    >
      <i class="el-icon-plus text-20 text-primary"></i>
      <span class="el-upload-btn__text">{{ btnText }}</span>
      <input
        type="file"
        :accept="accept"
        :multiple="currentImgIndex === -1"
        @change.stop="changeMultiUpload($event)"
        @click.stop
        ref="fileInput"
        class="el-upload-btn__input"
      >
    </div>
    </Draggable>
    <!-- 图片剪切 -->
    <Cropper
      :visible.sync="isShowCropper"
      :file="file"
      @cropUploadSuccess="uploadSuccess"
    />
  </div>
</template>
<script>
import uploadMixin from './mixin/uploadMixin';
import Draggable from 'vuedraggable';
import Cropper from './cropper';
export default {
  mixins: [uploadMixin],
  data() {
    return {
      imgUrls: this.defaultImg || [],
      files: [],
      currentImgIndex: -1, // 当前选中index 不等于-1时，为图片替换
      isChangeOriginUrl: false, // 原图片是否更换
      originUrl: [] // 原图地址
    };
  },
  computed: {
    showUploadBtn() {
      // 已上传图片数量和最大图片数量是否相等，不相等上传图片按钮显示，否则隐藏
      return this.imgUrls.length >= this.limit;
    },
    imgUrlsLength() {
      return this.imgUrls.length;
    }
  },
  watch: {
    defaultImg(newVal) {
      this.imgUrls = newVal || [];
    },
    imgUrlsLength(newVal) {
      if (!newVal) {
        this.files = [];
      }
    }
  },
  components: {
    Draggable,
    Cropper
  },
  created() {
    this.originUrl = JSON.parse(JSON.stringify(this.imgUrls));
  },
  methods: {
    // 图片上传
    changeMultiUpload(e) {
      const imgMaxNum = this.currentImgIndex === -1 ? Number(this.limit - this.imgUrls.length) : 1; // 图片还可以上传的图片数量
      const files = e.target.files;
      let formData = new FormData();
      let count = 0;
      let flag = true;
      while (count < imgMaxNum) {
        const file = files[count];
        if (file) {
          if (!this.isCheckout(file)) {
            flag = false;
            break;
          }
          formData.append('file', file);
          count += 1;
        } else {
          break;
        }
      }
      if (flag) {
        this.uploadSuccess(formData, files);
      }
    },
    // 上传接口api
    uploadSuccess(file, files) {
      this.http(this.action, file).then(res => {
        const urls = res.list.map(e => e.raw);
        // this.currentImgIndex不等于-1时表示替换图片
        if (this.currentImgIndex === -1) {
          this.imgUrls.push(...urls);
          this.originUrl.push(...urls);
          this.files.push(...files);
        } else {
          this.imgUrls.splice(this.currentImgIndex, 1, urls[0]);
          this.files.splice(this.currentImgIndex, 1, files[0]);
          this.currentImgIndex = -1;
          if (this.isChangeOriginUrl) {
            this.originUrl.splice(this.currentImgIndex, 1, urls[0]);
          }
        }
        this.emitMultImgUrl(this.currentImgIndex, urls);
      });
    },
    // 触发图片上传
    uploadTrigger(restIndex) {
      if (this.disabled) {
        return;
      }
      // 初始化当前index，当不是编辑时
      if (restIndex === -1) {
        this.currentImgIndex = -1;
      }
      // 加nextTick原因是，编辑后,不能多张上传的问题
      this.$nextTick(() => {
        this.$refs.fileInput.value = '';
        this.$refs.fileInput.click();
      });
    },
    // 删除
    delMultImg(index) {
      this.imgUrls.splice(index, 1);
      this.originUrl.splice(index, 1);
      this.files.splice(index, 1);
      this.emitMultImgUrl(index);
    },
    // 替换图片
    editMultImg(index) {
      this.isChangeOriginUrl = true;
      this.currentImgIndex = index;
      this.uploadTrigger();
    },
    // 图片剪裁
    cropperMultImg(index, url) {
      this.isChangeOriginUrl = false;
      this.currentImgIndex = index;
      this.isShowCropper = true;
      this.file = this.originUrl[index];
    },
    // 改变图片顺序
    updateImgSort() {
      this.emitMultImgUrl();
    },
    // 图片更改传出
    emitMultImgUrl(index, changeImgUrl) {
      // 返回值图片列表 更改的index 被更改的urls
      this.$emit('changeImgUrl', this.imgUrls, index, changeImgUrl);
      this.$emit('changeFile', this.files);
    }
  }
};
</script>
