<template>
  <div>
    <div class="upload-pic-thumb">
      <vuedraggable
        :list="uploadList"
        :disabled="!draggable||!multiple"
        :animation="200"
        class="list-group"
        ghost-class="thumb-ghost"
        @end="onEnd"
        draggable=".draggable"
      >
        <div class="upload-list draggable" :style="scaleClass" v-for="(item, index) in uploadList" :key="index">
          <div class="img-upload" :style="scaleClass" :class="item.url ? 'img-upload-fill' : ''" style="background-color: #fff;" v-if="item.status == 'finished'" >
            <img :src="item.url" :style="scaleImgClass"/>
            <Icon @click="handleRemove(item)" class="primary-close primary-icon" type="ios-close-circle"/>
          </div>
          <div class="img-upload-text wes" :style="{width:scaleClass.width}">{{ item.name }}</div>
        </div>
        <Upload
          slot="footer"
          class="upload-list"
          ref="upload"
          :multiple="multiple"
          :show-upload-list="false"
          :on-success="handleSuccess"
          :on-error="handleError"
          :format="['jpg','jpeg','png','gif','bmp']"
          accept=".jpg, .jpeg, .png, .gif, .bmp"
          :max-size="1024*3"
          :on-format-error="handleFormatError"
          :on-exceeded-size="handleMaxSize"
          :before-upload="handleBeforeUpload"
          type="drag"
          :action="uploadFileUrl"
          :headers="accessToken"
          :style="scaleClass"
        >
          <div class="img-upload" :style="scaleClass" style="border: none;line-height: 40px">
            <iconpark-icon width="20px" height="20px" name="common-add-img"></iconpark-icon>
            <div>上传图片</div>
          </div>
        </Upload>
      </vuedraggable>
    </div>
  </div>
</template>

<script>
import { uploadFile } from "@/api/index";
import vuedraggable from "vuedraggable";
export default {
  name: "uploadPicThumb",
  components: {
    vuedraggable
  },
  props: {
    value: {
      type: null,
      default:()=>{
        return []
      }
    },
    draggable: {
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    limit: {
      type: Number,
      default: 10
    },
    scaleNum: {
      type: Number,
      default: 1
    }
  },
  data() {
    return {
      accessToken: {}, // 验证token
      uploadFileUrl: uploadFile, // 上传地址
      uploadList: [], // 上传列表
      scaleList: [
        {
          id: 1,
          scale: '1:1',
          width: '108px',
          height: '108px',
          imgWidth: '100px',
          imgHeight: '100px'
        },
        {
          id: 2,
          scale: '3:4',
          width: '80px',
          height: '106px',
          imgWidth: '72px',
          imgHeight: '100px'
        },
        {
          id: 3,
          scale: '2:3',
          width: '80px',
          height: '120px',
          imgWidth: '72px',
          imgHeight: '114px'
        },{
          id: 4,
          scale: '1:1',
          width: '80px',
          height: '80px',
          imgWidth: '72px',
          imgHeight: '72px'
        }
      ]
    };
  },
  computed: {
    scaleClass() {
      return {
        width: this.scaleList[this.scaleNum-1].width,
        height: this.scaleList[this.scaleNum-1].height
      }
    },
    scaleImgClass() {
      return {
        width: this.scaleList[this.scaleNum-1].imgWidth,
        height: this.scaleList[this.scaleNum-1].imgHeight
      }
    },
  },
  watch: {
    value: {
      handler(val) {
        if(val.length == 0) {
          this.uploadList = []
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 拖拽结束事件
    onEnd() {
      this.returnValue();
    },
    // 初始化方法
    init() {
      if(this.$props.value.length>0) {
        this.$props.value.map(item => {
          this.uploadList.push({
            url: item.image,
            name: item.name,
            status: 'finished'
          })
        })
      }
      this.accessToken = {
        accessToken: this.getStore("accessToken")
      };
    },
    // 移除图片
    handleRemove(file) {
      this.uploadList = this.uploadList.filter(i => i.url !== file.url);
      this.returnValue();
    },
    // 上传成功
    handleSuccess(res, file) {
      if (res.success) {
        file.url = res.result;
        // 单张图片处理
        if (!this.multiple && this.uploadList.length > 0) {
          // 删除第一张
          this.uploadList.splice(0, 1);
        }
        if(this.limit === this.uploadList.length) {
          this.$Message.warning("最多只能上传" + this.limit + "张图片");
        } else {
          this.uploadList.push(file);
        }
        // 返回组件值
        this.returnValue();
      } else {
        this.$Message.error(res.message);
      }
    },
    // 上传失败
    handleError(error, file, fileList) {
      this.$Message.error(error.toString());
    },
    // 格式校验
    handleFormatError(file) {
      this.$Message.warning("所选文件格式不正确, 请选择.jpg, .jpeg, .png, .gif, .bmp图片格式文件");
    },
    // 上传文件大小校验
    handleMaxSize(file) {
      this.$Message.warning("所选文件大小过大，不能超过3M");
    },
    // 上传之前钩子
    handleBeforeUpload(v) {
      if (this.multiple && this.uploadList.length >= this.limit) {
        this.$Message.warning("最多只能上传" + this.limit + "张图片");
        return false;
      }
      return true;
    },
    // 返回组件值
    returnValue() {
      if (!this.uploadList || this.uploadList.length < 1) {
        if (!this.multiple) {
          this.$emit("input", "");
          this.$emit("on-change", "");
        } else {
          this.$emit("input", []);
          this.$emit("on-change", []);
        }
        return;
      }
      if (!this.multiple) {
        // 单张
        let v = this.uploadList[0].url;
        this.$emit("input", v);
        this.$emit("on-change", v);
      } else {
        let v = [];
        this.uploadList.forEach(e => {
          v.push({
            image: e.url,
            name: e.name
          });
        });
        this.$emit("input", v);
        this.$emit("on-change", v);
      }
    },
  },
  mounted() {
    this.init();
  }
};
</script>

<style lang="scss" scoped>
.upload-pic-thumb{
  display: flex;
}
.upload-list {
  display: inline-block;
  width: 80px;
  height: 80px;
  text-align: center;
  line-height: 80px;
  border-radius: 4px;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 16px;
  margin-bottom: 30px;
  vertical-align: middle;
}

.list-group {
  display: inline-block;
}
.thumb-ghost {
  opacity: 0.5;
  background: #c8ebfb;
}
</style>
