<template>
  <div class="upload-image-wrapper">
    <ul class="image-list">
      <li class="image-item" v-for="(item, index) of imgList" :key="index">
        <a
          href="javascript:;"
          class="image-wrapper"
          :style="{ backgroundImage: `url(${fileDomain}${item.msrc})` }"
          @click="show(index)"
        ></a>
        <i
          class="icon1 delete-item"
          v-if="ableDelete"
          @click="handleDeleteImage(item.objectKey, index)"
        >&#xe827;</i>
      </li>
      <li class="image-item" v-if="!isShowUploadBtn">
        <a href="javascript:;" class="upload-image-btn" @click="handleUploadImageClick">
          <i class="icon1 icon-iconfontadd"></i>
        </a>
      </li>
    </ul>
    <div v-transfer-dom>
      <previewer :list="previewImgList" ref="previewer"></previewer>
    </div>
  </div>
</template>

<script>
import { Previewer, TransferDom } from 'vux'
import ossHandle from '@/assets/ossHandle'
export default {
    name: 'UploadImage',
    directives: {
        TransferDom
    },
    components: {
        Previewer
    },
    props: {
    /**
     *  图片路径src
     *  类型 Array 默认[]
     *  [{src: '元素数组路径'， msrc: '缩放数组路径', objecKey: '文件objectKey'}]
     *
     * */
        imgList: {
            type: Array,
            default () {
                return []
            }
        },
        /**
     *  是否允许删除
     *  类型 Boolean 默认 true（允许删除）
     *
     * */
        ableDelete: {
            type: Boolean,
            default: true
        },
        /**
     *  oss的基础配置
     *  类型 Obeject
     *
     * */
        ossBaseConfig: {
            type: Object,
            default () {
                return {
                    limit: 9,
                    ossCof: {
                        endpoint: 'oss-cn-shenzhen.aliyuncs.com',
                        bucket: 'vschool-solution',
                        region: 'oss-cn-shenzhen.aliyuncs.com'
                    },
                    filePath: '10086/TestUpload',
                    sourceType: 2
                }
            }
        },
        /**
     * 图片域名
     * 类型 String 必传
     *
     * */
        fileDomain: {
            type: String,
            default: 'https://vschool-solution.oss-cn-shenzhen.aliyuncs.com'
        }
    },
    computed: {
        isShowUploadBtn () {
            return this.imgList.length === this.ossBaseConfig.imgLength
        }
    },
    watch: {
        imgList: {
            deep: true,
            immediate: true,
            handler (newVal) {
                if (newVal) {
                    let imgList = JSON.parse(JSON.stringify(newVal))
                    this.previewImgList = imgList.map(item => {
                        item.src = `${this.fileDomain}${item.src}`
                        item.msrc = `${this.fileDomain}${item.msrc}`
                        return item
                    })
                }
            }
        }
    },
    data () {
        return {
            // options: {
            //   getThumbBoundsFn(index) {
            //     // find thumbnail element
            //     let thumbnail = document.querySelectorAll('.image-item')[index];
            //     // get window scroll Y
            //     let pageYScroll = window.pageYOffset || document.documentElement.scrollTop;
            //     // optionally get horizontal scroll
            //     // get position of element relative to viewport
            //     let rect = thumbnail.getBoundingClientRect();
            //     // w = width
            //     return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
            //     // Good guide on how to get element coordinates:
            //     // http://javascript.info/tutorial/coordinates
            //   }
            // },
            currentImageIndex: 0,
            previewImgList: []
        }
    },
    mounted () {
        this.$nextTick(() => {
            this.ossBaseConfig.imgLength = this.ossBaseConfig.limit
        })
    },
    methods: {
        show (index) {
            this.$nextTick(() => {
                this.$refs.previewer.show(index)
            })
        },
        // 选择图片
        handleUploadImageClick () {
            this.ossBaseConfig.limit = this.ossBaseConfig.imgLength - this.imgList.length
            ossHandle.businessParams = this.ossBaseConfig
            setTimeout(() => {
                ossHandle.getWxConfig(this.upLoadSucc)
            }, 0)
        },
        // 上传图片成功
        upLoadSucc (params) {
            // let obj = {
            //   src: `${this.fileDomain}${params.fileUrl}`,
            //   msrc: `${this.fileDomain}${params.fileUrl}?x-oss-process=image/resize,p_50`,
            //   objectKey: params.objectKey
            // };
            let obj = {
                src: `${params.fileUrl}`,
                msrc: `${params.fileUrl}?x-oss-process=image/resize,p_50`,
                objectKey: params.objectKey,
                fileName: params.filename,
                fileSize: params.filesize
                // fileSuffix: params.filesuffix,
                // fileUrl: params.fileUrl
            }
            this.$emit('upLoadSucc', obj)
        },
        // 删除图片
        handleDeleteImage (objectKey, index) {
            this.$vux.confirm.show({
                // 组件除show外的属性
                title: '提示',
                content: '确认删除图片吗？',
                onCancel: () => { },
                onConfirm: () => {
                    this.currentImageIndex = index
                    ossHandle.handleDelete(this.handleDeleteImageSucc, objectKey)
                }
            })
        },
        // 删除图片成功
        handleDeleteImageSucc () {
            let index = this.currentImageIndex
            this.$emit('deleteImageSucc', index)
        }
    }
}
</script>

<style lang="less" scoped>
.upload-image-wrapper {
  position: relative;
  .image-list {
    position: relative;
    display: flex;
    flex-wrap: wrap;
    // padding-left: 10px;
    .image-item {
      position: relative;
      flex: 0 0 33.333333%;
      height: 33.333333vw;
      margin-right: .2rem;
      margin-bottom: .2rem;
      .image-wrapper {
        display: block;
        width: 100%;
        height: 100%;
        background-repeat: no-repeat;
        background-size: cover;
      }
      .upload-image-btn {
        position: relative;
        display: flex;
        height: 100%;
        height: 100%;
        justify-content: center;
        align-items: center;
        border: 1px dashed #ddd;
        border-radius: 4px;
        .icon1 {
          font-size: 50px;
          color: #999;
        }
      }
      .delete-item {
        position: absolute;
        top: -8px;
        right: -8px;
        width: 16px;
        height: 16px;
        display: flex;
        justify-content: center;
        align-items: center;
        background-color: #ff0000;
        color: #fff;
        border-radius: 50%;
        &.icon1 {
          font-size: 12px;
          transform: scale(0.85);
        }
      }
    }
  }
}
</style>
