/**
 * PullDelete
 */
(function(win, $) {
    let startX, 
        startY, 
        pullX, 
        pullY, 
        moveX, 
        moveY, 
        rem, 
        btn, 
        threshold; 
    let _this;

    /**
     *
     * @param $Dom
     * @param callback
     * @constructor
     */
    let PullDelete = function ($Dom, callback) {
        _this = this;
        rem = parseFloat($('html').css('font-size').replace('px', '')),
        btn = 2.5 * rem;
        threshold = btn / 2;
        if ($Dom instanceof jQuery && $Dom.hasClass('pull_delete')) {
            $Dom.append('<span class="pd_btn"></span>');
            _this.addPullListener($Dom, callback);
        }
    }


    PullDelete.prototype = {
        constructor: PullDelete,
        addPullListener: function($Dom, callback) {
            $Dom.on('touchstart', function (e) {
                startX = e.originalEvent.targetTouches[0].pageX;
                startY = e.originalEvent.targetTouches[0].pageY;
                $(this).removeClass('trans');
                $(this).siblings().addClass('trans').css({transform: 'translateX(0)'});
            });
            $Dom.on('touchmove', function (e) {
                pullX = e.originalEvent.targetTouches[0].pageX;
                pullY = e.originalEvent.targetTouches[0].pageY;
                moveX = (startX - pullX) * 0.8;
                moveY = (startY - pullY) * 0.8;
                if (Math.abs(moveY) > Math.abs(moveX)) {
                    return;
                }
                if (moveX <= btn) {
                    $(this).css({transform: 'translateX(-' + moveX + 'px)'});
                }
            });
            $Dom.on('touchend', function (e) {
                let trans = _this.transverseShift($(this)),
                    viewTrans = trans >= threshold && trans < btn ? btn : 0;
                $(this).addClass('trans').css({transform: 'translateX(-' + viewTrans + 'px)'});
                if (e.target.className == 'pd_btn') {
                    e.stopPropagation();
                    e.preventDefault();
                    if (callback) {
                        callback($Dom);
                    }
                }
            });
        },
        transverseShift: function($dom) {
            if (!$dom instanceof jQuery) {
                return;
            }
            let trans = $dom.css('transform');
            if (trans.indexOf('matrix') > -1) {
                return Math.abs(trans.split(',')[4]) || 0;
            } else {
                return Math.abs(trans.replace(/[^\d\.]/g, '')) || 0;
            }
        }
    }

    $.fn.extend({
        pulldelete: function(callback){
            this.each(function(){
                new PullDelete($(this), callback);
            });
            return this;
        }
    });

    win.PullDelete = PullDelete;
})(window, jQuery)
