var windowHeight = document.documentElement.clientHeight,
    windowWidth = document.documentElement.clientWidth,
    footerHeight = $("nav").height(),
    headerHeight = $("#header").height(),
    contentHeight = windowHeight - footerHeight - headerHeight,
    canvas = document.getElementById('clipImg'),
    imgWidth ,
    imgHeight,
    clickCount = 0;
    

var Clip = {
    size: 200, //表示正方形的边长，乘上一个基数就是当前的像素值
    range: {}, //用来控制正方形的边界值
    topCss: (windowHeight - this.size) / 2,
    leftCss: (windowWidth - this.size) / 2,
    touchX: 0,
    touchY: 0,
    timer: null,
    imgUrl:"",
    init: function(){
        //等比例缩放图片(如果图片宽高都比容器小，则绘制的图片宽高 = 原图片的宽高。)
        //如果图片的宽度或者高度比容器大，则宽度或者高度 = 容器的宽度或者高度，另一高度或者宽度则等比例缩放
        var cxt = canvas.getContext('2d');
        var img = new Image();
        img.src = this.imgUrl;
//      img.src = "../images/xing.jpeg";
        
        img.onload = function(){
            if ( img.width < windowWidth && img.height < contentHeight) {
              imgWidth = img.width;
              imgHeight = img.height;
          
            } else {
              var pWidth = img.width / (img.height / contentHeight);
              var pHeight = img.height / (img.width / windowWidth);
              imgWidth = pWidth > windowWidth ? windowWidth : pWidth;
              imgHeight = pHeight > contentHeight ? contentHeight : pHeight;
            }
            
            canvas.height = imgHeight;
            canvas.width = imgWidth;
            canvas.style.left = (windowWidth - imgWidth) / 2 + 'px';;
            canvas.style.top = (contentHeight - imgHeight) / 2 + headerHeight + 'px';
            
            cxt.drawImage(img,0,0,imgWidth,imgHeight);
            
            Clip.changeBase(0);
            bindClipEvent();
        }
        
        
    },
    changeBase: function(index) {
        //这个函数用来改变正方形的边长
        this.size += index * 5 ;
        if(this.size > imgHeight || this.size > imgWidth){
            this.size = imgHeight>imgWidth ? imgWidth : imgHeight;
        }
        if((this.size + this.leftCss) > (parseFloat(canvas.style.left) + imgWidth)){
            var left = (this.size + this.leftCss) - (parseFloat(canvas.style.left) + imgWidth);
            this.leftCss = this.leftCss - left;
        }
        
        if((this.size + this.topCss) > (parseFloat(canvas.style.top) + imgHeight)){
            var top = (this.size + this.topCss) - (parseFloat(canvas.style.top) + imgHeight);
            this.topCss = this.topCss - top;
        }
        $("#clip").css({
            height: this.size + 'px',
            width: this.size + 'px',
            lineHeight: this.size + 'px'
        });

        this.changeRange();
    },
    changeRange: function() {
        //这个方法用来计算初始top，left以及边界值。相对clipContent而言
        if(isNaN(this.topCss)) {
            this.topCss = (contentHeight - this.size) / 2 + headerHeight;
        }
        if(isNaN(this.leftCss)) {
            this.leftCss = (windowWidth - this.size) / 2;
        }
        this.changeClipStyle(this.leftCss, this.topCss);

        //极限值，需控制不超出图片区域
        var minTop = (contentHeight - imgHeight)/2 + headerHeight;
        var maxTop = (contentHeight - imgHeight)/2+ headerHeight+ imgHeight - this.size;

        var minLeft = (windowWidth - imgWidth)/2;
        var maxLeft = (windowWidth - imgWidth)/2 + imgWidth - this.size;
        this.range = {
            minTop: minTop,
            maxTop: maxTop,
            minLeft: minLeft,
            maxLeft: maxLeft
        };
    },
    //设置新的样式，并改变当前的top和left值
    changeClipStyle: function(leftCss, topCss) {
        $('#clip').css({
            left: leftCss + 'px',
            top: topCss + 'px'
        });
        Clip.leftCss = leftCss;
        Clip.topCss = topCss;
    }
};

var bindClipEvent = function(){
    var clip = document.getElementById('clip');

    clip.addEventListener('touchstart', function(event) {
        event.preventDefault();
        var x = event.touches ? event.touches[0].clientX : event.screenX;
        var y = event.touches ? event.touches[0].clientY : event.screenY;

        Clip.touchX = x;
        Clip.touchY = y;
    });
    clip.addEventListener('touchmove', function(event) {
        if(Clip.timer != null) {
            return;
        }
        Clip.timer = setTimeout(function() {
            var x = event.touches ? event.touches[0].clientX : event.screenX;
            var y = event.touches ? event.touches[0].clientY : event.screenY;

            var disX = x - Clip.touchX;
            var disY = y - Clip.touchY;

            var nowLeft = Clip.leftCss + disX;
            var nowTop = Clip.topCss + disY;

            if(nowLeft < Clip.range.minLeft) {
                nowLeft = Clip.range.minLeft;
            }
            if(nowLeft > Clip.range.maxLeft) {
                nowLeft = Clip.range.maxLeft;
            }

            if(nowTop < Clip.range.minTop) {
                nowTop = Clip.range.minTop;
            }
            if(nowTop > Clip.range.maxTop) {
                nowTop = Clip.range.maxTop;
            }

            Clip.changeClipStyle(nowLeft, nowTop);

            Clip.touchX = x;
            Clip.touchY = y;
            Clip.timer = null;
        }, 20);
    });
    
    //按钮的事件
    $("#reduce").on('tap', function(){
        Clip.changeBase(-1);
    });
    
    $("#enlarge").on('tap', function(){
        Clip.changeBase(1);
    });
    
    $("#saveBtn").on('click', function(){
        if(clickCount == 0){
            clickCount ++;
            saveImage();
        }
        
    });
    
    $("#cancelBtn").on('click', function(){
        $("#clipPanel").addClass("c-hide");
        clearFile();
        $("#content").removeClass("c-hide");
    });
};

var clearFile = function(){
    var str ='<input type="file" class="c-hide" id="file_head" accept="image/*;capture=camera" onchange="clip_photo()">';
    $("#file_head").remove();
    $("#chooseImage").append(str);
}

var saveImage = function(){
    var width = Clip.size,
        height = Clip.size,
        x = Clip.leftCss - Clip.range.minLeft,
        y = Clip.topCss - Clip.range.minTop;
        
    var canvas2=$('<canvas width="'+width+'" height="'+height+'"></canvas>')[0],
        ctx=canvas2.getContext('2d');
        
    var image = new Image();
    image.src = Clip.imgUrl;
    image.onload = function(){
        var widthPix = imgWidth/image.width,
            heightPix = imgHeight / image.height;
        ctx.drawImage(image,x/widthPix,y/heightPix,width/widthPix,height/heightPix,0,0,width,height);
        
        var data=canvas2.toDataURL();
        data=data.split(',')[1];
        data=window.atob(data);
        var ia = new Uint8Array(data.length);
        for (var i = 0; i < data.length; i++) {
            ia[i] = data.charCodeAt(i);
        }
        var blob=new Blob([ia],{type:"image/png",endings:'transparent'});
        var fd=new FormData();
        fd.append('file',blob,'image.png');
        
        var new_url = URL.createObjectURL(blob);
        appendFile(new_url);
        $.ajax(server + 'upload/image', {
            data: fd,
            dataType: 'json',
            contentType: false,
            cache: false,
            processData: false,
            beforeSend: function(request) {
                request.setRequestHeader("userAgent", userAgent);
            },
            type: 'post',
            error: function(res) {
                if(res.status == 999 || res.status == 998 || res.status == 997){
                    loginUrl(res.status);
                    return;
                }
                clickCount = 0;
            },
            success: function(res) {
                if(res.status == 999 || res.status == 998 || res.status == 997){
                    loginUrl(res.status);
                    return;
                }
                var params = {};
                params.photo = res.urls;
                var patientUrl = res.urls;
                sendPost('patient/save', params, 'json', 'post', submitFailed, submitSuccess);
                clickCount = 0;
                clearFile();
            }
        });
    };
};
