<template>
    <view :class="'weui-gallery ' + (showClone ? 'weui-gallery_show' : '') + ' ' + extClass">
        <view class="weui-gallery__info">{{ currentClone + 1 }}/{{ currentImgs.length }}</view>
        <swiper
            class="weui-gallery__img__wrp"
            @tap="hideGallery"
            :indicator-dots="false"
            @change="change"
            :current="currentClone"
            :autoplay="false"
            :duration="500"
            :circular="true"
        >
            <block v-for="(item, index) in currentImgs" :key="index">
                <swiper-item>
                    <image
                        mode="aspectFit"
                        :src="item"
                        @touchmove="touchmoveCallback"
                        @touchstart="touchstartCallback"
                        :style="'width:' + scaleWidth + ';height:' + scaleHeight"
                        @load="imgload"
                    ></image>
                </swiper-item>
            </block>
        </swiper>
        <view class="weui-gallery__opr" v-if="showDelete">
            <view @tap="deleteImg" class="weui-gallery__del">删除</view>
        </view>
    </view>
</template>

<script>
// pages/components/gallery/gallery.js
export default {
    data() {
        return {
            currentImgs: [],
            scaleHeight: '100%',
            scaleWidth: '100%',
            distance: 0,

            //手指移动的距离
            scale: 1,

            //图片的比例
            baseWidth: null,

            //图片真实宽度
            //图片真实高度
            baseHeight: null,

            diff: '',
            currentClone: 0,
            showClone: false
        };
    },
    options: {
        addGlobalClass: true
    },
    /**
     * 组件的属性列表
     */
    props: {
        imgUrls: {
            type: Array,
            default: () => []
        },
        showDelete: {
            // 是否显示delete按钮
            type: Boolean,
            default: true
        },
        show: {
            type: Boolean,
            default: true
        },
        current: {
            type: Number,
            default: 0
        },
        hideOnClick: {
            type: Boolean,
            default: true
        },
        extClass: {
            type: Boolean,
            default: ''
        }
    },
    mounted() {
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    /**
     * 组件的方法列表
     */
    methods: {
        ready() {
            const data = this;
            this.setData({
                currentImgs: data.imgUrls
            });
        },

        change(e) {
            this.setData({
                currentClone: e.detail.current
            });
            this.$emit(
                'change',
                {
                    detail: {
                        current: e.detail.current
                    }
                },
                {}
            );
        },

        deleteImg() {
            const data = this;
            const imgs = data.currentImgs;
            const url = imgs.splice(data.current, 1);
            this.$emit(
                'delete',
                {
                    detail: {
                        url: url[0],
                        index: data.current
                    }
                },
                {}
            );
            if (imgs.length === 0) {
                // @ts-ignore
                this.hideGallery();
                return;
            }
            this.setData({
                currentClone: 0,
                currentImgs: imgs
            });
        },

        hideGallery() {
            const data = this;
            if (data.hideOnClick) {
                this.setData({
                    showClone: false
                });
                this.$emit(
                    'hide',
                    {
                        detail: {}
                    },
                    {}
                );
            }
        },

        /**
         * 双手指触发开始 计算开始触发两个手指坐标的距离
         */
        touchstartCallback: function (e) {
            // 单手指缩放开始，不做任何处理
            if (e.touches.length == 1) {
                return;
            }
            // 当两根手指放上去的时候，将距离(distance)初始化。
            let xMove = e.touches[1].clientX - e.touches[0].clientX;
            let yMove = e.touches[1].clientY - e.touches[0].clientY;
            //计算开始触发两个手指坐标的距离
            let distance = Math.sqrt(xMove * xMove + yMove * yMove);
            console.log(distance);
            this.setData({
                distance: distance
            });
        },

        /**
         * 监听图片加载成功时触发
         */
        imgload: function (e) {
            console.log(e);
            this.setData({
                baseWidth: e.detail.width,
                //获取图片真实宽度
                baseHeight: e.detail.height,
                //获取图片真实高度
                scaleWidth: '100%',
                //给图片设置宽度
                scaleHeight: '100%' //给图片设置高度
            });
        },

        /**
         * 双手指移动   计算两个手指坐标和距离
         */
        touchmoveCallback: function (e) {
            // 单手指缩放不做任何操作
            if (e.touches.length == 1) {
                return;
            }
            //双手指运动 x移动后的坐标和y移动后的坐标
            let xMove = e.touches[1].clientX - e.touches[0].clientX;
            let yMove = e.touches[1].clientY - e.touches[0].clientY;
            //双手指运动新的 ditance
            let distance = Math.sqrt(xMove * xMove + yMove * yMove);
            //计算移动的过程中实际移动了多少的距离
            let distanceDiff = distance - this.distance;
            let newScale = this.scale + 0.005 * distanceDiff;
            // 为了防止缩放得太大，所以scale需要限制，同理最小值也是
            console.log(newScale, this.baseWidth, this.baseHeight);
            if (newScale >= 1) {
                let scaleWidth = Number(newScale * 100).toFixed(1);
                scaleWidth += '%';
                this.setData({
                    distance: distance,
                    scale: newScale,
                    scaleWidth: scaleWidth,
                    scaleHeight: scaleWidth,
                    diff: distanceDiff
                });
            }
            //为了防止缩放得太小，所以scale需要限制
            if (newScale <= 0.3) {
                newScale = 0.3;
                this.setData({
                    distance: distance,
                    scale: newScale,
                    scaleWidth: '100%',
                    scaleHeight: '100%',
                    diff: distanceDiff
                });
            }
        }
    },
    created: function () {},
    watch: {
        imgUrls: {
            handler: function (newVal) {
                this.setData({
                    currentImgs: newVal
                });
            },

            immediate: true,
            deep: true
        },

        current: {
            handler: function (newVal, oldVal) {
                this.currentClone = newVal;
            },

            immediate: true
        },

        show: {
            handler: function (newVal, oldVal) {
                this.showClone = newVal;
            },

            immediate: true
        }
    }
};
</script>
<style>
.wux-gallery {
    display: block;
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #000;
    z-index: 1000;
}
.wux-gallery__swiper {
    width: 100%;
    height: 100%;
}
.wux-gallery__item {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-direction: column;
    flex-direction: column;
    -ms-flex-pack: center;
    justify-content: center;
}
.wux-gallery__img {
    -ms-flex: none;
    flex: none;
    width: 100%;
    height: 100%;
}
.wux-gallery__remark {
    position: absolute;
    bottom: 120rpx;
    left: 0;
    right: 0;
    color: #fff;
    text-align: center;
    padding: 30rpx;
    font-size: 28rpx;
    z-index: 10;
    opacity: 0;
    transition: opacity 0.3s ease 0.5s;
}
.wux-gallery__remark--active {
    opacity: 1;
}
.wux-gallery__opr {
    position: absolute;
    right: 0;
    bottom: 0;
    left: 0;
    background-color: #0d0d0d;
    color: #fff;
    line-height: 120rpx;
    text-align: center;
}
.wux-gallery__del {
    display: -ms-flexbox;
    display: flex;
    -ms-flex-pack: center;
    justify-content: center;
    -ms-flex-align: center;
    align-items: center;
    padding: 36rpx 0;
}
.wux-gallery__del > image {
    width: 48rpx;
    height: 48rpx;
}
.wux-gallery__icon {
    background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAQAAAAAYLlVAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAAAmJLR0QAAKqNIzIAAAAHdElNRQfhAgcLJQQVEPJBAAAA9UlEQVRo3u2YwRGDIBBF1xTjeLAPW6AE27GQXKyJOvJz0DjGBHZZ9JDJf9xwgccCzoAIIYSQQtBiRp4Z7ZXD27hKYZv9I1nWLFwlsNBnIvolxNpjUyqwtEo3gwiUkDdunjw0zm9GAYT03nrlIYcaExRh+/p52S/PtyUIgq2sTlXl2IeWgc9sWDeUpw/XJjwTClDAJYBw/J3k63O4jmHqYJVFV2TgTChAAQpQgAIUoAAFKPCjAuF4xVTqM/BySgGTQM2bjdZWE4h2zewI0StwFxGRoUJg2PVTDjrj27BG554AxhOGHysyKIIOE6Jz6IipYvaE/AVPaUL1Zysou40AAAAldEVYdGRhdGU6Y3JlYXRlADIwMTctMDItMDdUMTE6Mzc6MDQrMDg6MDCcsdZ8AAAAJXRFWHRkYXRlOm1vZGlmeQAyMDE3LTAyLTA3VDExOjM3OjA0KzA4OjAw7exuwAAAAABJRU5ErkJggg==);
    background-position: center center;
    background-repeat: no-repeat;
    background-size: contain;
    color: #fff;
    width: 48rpx;
    height: 48rpx;
}
</style>
