;
(function() {
    var Crop = function(options) {
        options = options || {}
        this.url = options.url || '';
        this.confirm = options.confirm || function(res) {};
        this.crop = document.createElement('div');
        this.crop.addEventListener("touchstart", this.touchstart.bind(this));
        this.crop.addEventListener("touchmove", this.touchmove.bind(this));
        this.crop.addEventListener("touchend", this.touchend.bind(this));
        this.crop.addEventListener("touchcancel", this.touchcancel.bind(this));

        this.imgCvs = document.createElement('canvas');
        this.imgCvs.width = window.innerWidth;
        this.imgCvs.height = window.innerHeight;
        this.coverCvs = document.createElement("canvas");
        this.coverCvs.width = window.innerWidth;
        this.coverCvs.height = window.innerHeight;

        this.cropCvs = document.createElement("canvas");
        this.cropCvs.width = options.width || 200;
        this.cropCvs.height = options.height || 200;
        this.image = new Image();
        this.image.onload = this.init.bind(this);

        this.okBtn = document.createElement('div');
        this.okBtn.innerText = '确定';
        this.okBtn.addEventListener('click', this.ok.bind(this));

        this.cancelBtn = document.createElement('div');
        this.cancelBtn.innerText = '取消';
        this.cancelBtn.addEventListener('click', this.cancel.bind(this));


        this.crop.appendChild(this.imgCvs);
        this.crop.appendChild(this.coverCvs);
        this.crop.appendChild(this.okBtn);
        this.crop.appendChild(this.cancelBtn);

        // this.input = document.createElement('input');
        // this.input.setAttribute("type", "file");
        // this.input.setAttribute("accept", "image/*");

        // this.input.style.display = 'none';
        // this.input.addEventListener("change", this.onchange.bind(this));
        // this.input.click();
        this.image.src = options.src;

    };
    Crop.prototype = {
        init: function() {
            if (this.image.width / this.image.height > this.cropCvs.width / this.cropCvs.height) {
                this.scale = this.cropCvs.height / this.image.height;
                this.minScale = this.cropCvs.height / this.image.height;
            } else {
                this.scale = this.cropCvs.width / this.image.width;
                this.minScale = this.cropCvs.width / this.image.width;
            }
            this.x = (this.imgCvs.width - this.scale * this.image.width) / 2;
            this.y = (this.imgCvs.height - this.scale * this.image.height) / 2;

            this.setStyle();
            document.body.appendChild(this.crop);
            this.drawCover();
            this.drawImg();
        },
        onchange: function() {
            alert('onchange');
            var reader = new FileReader();
            reader.onload = function() {
                this.image.src = reader.result;
            }.bind(this);
            reader.readAsDataURL(this.input.files[0]);
        },
        touchstart: function(evt) {
            if (evt.touches.length > 1) {
                this.pinchStartScale = this.scale;
                this.pinchStartLen = Math.sqrt(Math.pow(evt.touches[0].pageX - evt.touches[1].pageX, 2) + Math.pow(evt.touches[0].pageY - evt.touches[1].pageY, 2));
            } else {
                this.lastX = evt.touches[0].pageX;
                this.lastY = evt.touches[0].pageY;
            }
        },
        touchmove: function(evt) {
            if (evt.touches.length > 1) {
                var pinchLen = Math.sqrt(Math.pow(evt.touches[0].pageX - evt.touches[1].pageX, 2) + Math.pow(evt.touches[0].pageY - evt.touches[1].pageY, 2));
                this.scale = pinchLen / this.pinchStartLen * this.pinchStartScale;
                if (this.scale < this.minScale) {
                    this.scale = this.minScale;
                }

            } else {
                var dx = evt.touches[0].pageX - this.lastX;
                var dy = evt.touches[0].pageY - this.lastY;
                this.x += dx;
                this.y += dy;
                this.lastX = evt.touches[0].pageX;
                this.lastY = evt.touches[0].pageY;
            }
            this.drawImg();
            evt.stopPropagation();
        },
        touchend: function(evt) {
            if (evt.touches.length > 1) {

            } else {

            }
        },
        touchcancel: function(evt) {},
        setStyle: function() {
            this._css(this.crop, {
                position: 'fixed',
                left: 0,
                top: 0,
                width: '100%',
                height: '100%',
                zIndex: '20'
            });
            this._css(this.imgCvs, {
                position: 'fixed',
                left: 0,
                top: 0,
                width: '100%',
                height: '100%'
            });
            this._css(this.coverCvs, {
                position: 'fixed',
                left: 0,
                top: 0,
                width: '100%',
                height: '100%'
            });
            this._css(this.cancelBtn, {
                position: 'fixed',
                left: '0.4rem',
                bottom: '0.4rem',
                color: '#fff',
                width: '1.28rem',
                height: '0.64rem',
                lineHeight: '0.64rem',
                textAlign: 'center',
                borderRadius: '0.08rem',
                fontSize: '0.28rem',
                background: '#15A8AA'
            });
            this._css(this.okBtn, {
                position: 'fixed',
                right: '0.4rem',
                bottom: '0.4rem',
                color: '#fff',
                width: '1.28rem',
                height: '0.64rem',
                lineHeight: '0.64rem',
                textAlign: 'center',
                borderRadius: '0.08rem',
                fontSize: '0.28rem',
                background: '#15A8AA'
            });
        },
        drawCover: function() {
            var ctx = this.coverCvs.getContext("2d"),
                w = this.coverCvs.width,
                h = this.coverCvs.height,
                cw = this.cropCvs.width,
                ch = this.cropCvs.height;
            ctx.save();
            ctx.fillStyle = "black";
            ctx.globalAlpha = 0.7;
            ctx.fillRect(0, 0, w, h);
            ctx.restore();
            ctx.save();
            ctx.globalCompositeOperation = "destination-out";
            ctx.beginPath();
            if (this.circle) {
                ctx.arc(w / 2, h / 2, cw / 2 - 4, 0, Math.PI * 2, false);
            } else {
                ctx.rect(w / 2 - cw / 2, h / 2 - ch / 2, cw, ch)
            }
            ctx.fill();
            ctx.restore();
            ctx.save();
            ctx.beginPath();
            ctx.strokeStyle = "white";
            if (this.circle) {
                ctx.arc(w / 2, h / 2, cw / 2 - 4, 0, Math.PI * 2, false);
            } else {
                ctx.rect(w / 2 - cw / 2, h / 2 - ch / 2, cw, ch)
            }
            ctx.stroke();
        },
        drawImg: function() {
            var ctx = this.imgCvs.getContext('2d');
            ctx.clearRect(0, 0, this.imgCvs.width, this.imgCvs.height);
            if (this.x + this.image.width * this.scale < (this.imgCvs.width + this.cropCvs.width) / 2) {
                this.x = (this.imgCvs.width + this.cropCvs.width) / 2 - this.image.width * this.scale;
            } else if (this.x > (this.imgCvs.width - this.cropCvs.width) / 2) {
                this.x = (this.imgCvs.width - this.cropCvs.width) / 2;
            }
            if (this.y + this.image.height * this.scale < (this.imgCvs.height + this.cropCvs.height) / 2) {
                this.y = (this.imgCvs.height + this.cropCvs.height) / 2 - this.image.height * this.scale;
            } else if (this.y > (this.imgCvs.height - this.cropCvs.height) / 2) {
                this.y = (this.imgCvs.height - this.cropCvs.height) / 2;
            }
            ctx.drawImage(this.image, 0, 0, this.image.width, this.image.height, this.x, this.y, this.image.width * this.scale, this.image.height * this.scale);
        },
        ok: function() {
            var ctx = this.cropCvs.getContext('2d');
            ctx.drawImage(this.image, 0, 0, this.image.width, this.image.height, this.x - (this.imgCvs.width - this.cropCvs.width) / 2, this.y - (this.imgCvs.height - this.cropCvs.height) / 2, this.image.width * this.scale, this.image.height * this.scale);
            document.body.removeChild(this.crop);

            var formData = new FormData();
            // 建立一个upload表单项，值为上传的文件
            formData.append('base64', this.cropCvs.toDataURL("image/png"));
            var xhr = new XMLHttpRequest();
            xhr.open('POST', this.url);
            // 定义上传完成后的回调函数
            xhr.onload = function() {
                if (xhr.status === 200) {
                    var res = JSON.parse(xhr.response);
                    this.confirm(res)
                }
            }.bind(this);
            xhr.send(formData);
        },
        cancel: function() {
            document.body.removeChild(this.crop);
        },
        _css: function(el, obj) {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    el.style[key] = obj[key];
                }
            }
        }
    };

    if (typeof module !== 'undefined' && typeof exports === 'object') {
        module.exports = Crop;
    } else {
        window.Crop = Crop;
    }
})();