<template>
  <div class="hae-img-picker">
    <flexbox :gutter="0" wrap="wrap">
      <flexbox-item :span="1 / rowLength" v-for="(img,index) in imgList" :key="index">
        <div class="img-item" :style="{'background-image':'url('+img+')'}"></div>
        <span @click="deleteImgByIndex(index)" class="hae-icon delete"></span>
      </flexbox-item>
      <flexbox-item :span="1 / rowLength" v-if="imgList.length < length">
        <div class="selct-item">
          <input accept="image/*" class="hae-upload-widget" ref="upload" @change="getUploadFile" type="file">
        </div>
      </flexbox-item>
    </flexbox>
    <toast v-model="toa" :text="errMsg" type="text"></toast>
  </div>
</template>
<script>
import Flexbox from '../flexbox/flexbox'
import FlexboxItem from '../flexbox/flexbox-item'
import Toast from '../toast'
export default {
  data () {
    return {
      imgList: [],
      errMsg: '',
      toa: false
    }
  },
  props: {
    // 1 row show img nums
    rowLength: {
      type: Number,
      default: 4
    },
    length: {
      type: Number,
      default: 4
    },
    // whether upload to server
    server: Boolean,
    url: {
      type: String,
      default: ''
    }
  },
  methods: {
    getUploadFile (e) {
      const file = e.target.files[0];
      const fileReader = new FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onload = (re) => {
        const img = new Image();
        img.imgType = file.type;
        img.src = re.target.result;
        img.onload = () => {
          if (this.server) {
            this.uploadImg(file);
            return;
          }
          this.compressImg(img, img.width, img.height, 1);
        }
      }
    },
    uploadImg (file) {
      const formData = new FormData();
      formData.append('url', file);
      this.$vux.loading.show({
        text: '正在上传'
      });
      this.$http.post(this.url, formData, {'Content-Type': 'multipart/form-data'}).then(res => {
        this.$vux.loading.hide();
        this.imgList.push(res.data.data);
        this.$emit('upload', {
          imgList: this.imgList
        });
      }).catch(err => {
        this.$vux.loading.hide();
        this.errMsg = 'Server Error:' + err.response.statusText;
        this.toa = true;
        this.$emit('fail', {
          imgList: this.imgList
        });
      });
    },
    deleteImgByIndex (index) {
      this.imgList.splice(index, 1);
      this.$emit('delete', {
        index: index,
        imgList: this.imgList
      });
    },
    compressImg (img, width, height, ratio) {
      const canvas = document.createElement('canvas');
      canvas.width = width;
      canvas.height = height;
      const ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
      const img64 = canvas.toDataURL(img.imgType, 1);
      this.imgList.push(img64);
      this.$refs.upload.value = '';
      this.$emit('get-file', {
        imgList: this.imgList
      })
    }
  },
  components: {
    Flexbox,
    FlexboxItem,
    Toast
  }
}
</script>
<style lang="less" scoped>
  .hae-img-picker {
    padding: 10px 15px;
  }
  .img-item, .selct-item{
    padding-bottom: 100%;
    background-repeat: no-repeat;
    background-size: cover;
    border-radius: 5px;
    position: relative;
  }
  .selct-item {
    border: 1px solid #CCCCCC;
  }
  .selct-item:active {
    background-color: #dbdbdb;
  }
  .selct-item::before {
    content: '';
    position: absolute;
    width: 50%;
    height: 1px;
    background: #CCC;
    top: 50%;
    left: 25%;
  }
  .selct-item::after {
    content: '';
    position: absolute;
    height: 50%;
    width: 1px;
    background: #CCC;
    top: 25%;
    left: 50%;
  }
  .vux-flexbox-item {
    padding: 3px;
    box-sizing: border-box;
    position: relative;
  }
  .hae-icon.delete {
    display: block;
    height: 18px;
    width: 18px;
    position: absolute;
    top: 7px;
    right: 7px;
    background: url(data:image/svg+xml;charset=utf-8;base64,PHN2ZyB3aWR0aD0nMTYnIGhlaWdodD0nMTYnIHZpZXdCb3g9JzAgMCAxNiAxNicgeG1sbnM9J2h0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnJz48ZyBmaWxsPSdub25lJyBmaWxsLXJ1bGU9J2V2ZW5vZGQnPjxjaXJjbGUgZmlsbC1vcGFjaXR5PScuNCcgZmlsbD0nIzQwNDA0MCcgY3g9JzgnIGN5PSc4JyByPSc4Jy8+PHBhdGggZD0nTTExLjg5OCA0LjEwMWEuMzQ1LjM0NSAwIDAgMC0uNDg4IDBMOCA3LjUxMWwtMy40MTEtMy40MWEuMzQ1LjM0NSAwIDAgMC0uNDg4LjQ4OGwzLjQxMSAzLjQxLTMuNDEgMy40MTJhLjM0NS4zNDUgMCAwIDAgLjQ4OC40ODhMOCA4LjQ4N2wzLjQxMSAzLjQxMWEuMzQ1LjM0NSAwIDAgMCAuNDg4LS40ODhMOC40ODggOGwzLjQxLTMuNDEyYS4zNDQuMzQ0IDAgMCAwIDAtLjQ4N3onIGZpbGw9JyNGRkYnLz48L2c+PC9zdmc+);
    background-repeat: no-repeat;
    background-position: center center;
  } 
  .hae-upload-widget {
    width: 100%;
    height: 100%;
    overflow: hidden;
    position: absolute;
    opacity: 0;
  }
</style>