//简单多张图片排列显示模块
var image_builder = function(option, success) {
    var object = new ImageBuilder(option);
    success();
    return object;
}

function ImageBuilder(option) {
    this.markControl = option.markControl;
    this.init();
}

ImageBuilder.prototype.init = function() {
    this.container = getDom(this.canvas_dom, this.markControl).appendTo(this.markControl.container);
    this.container.hide();
    this.canvas = document.getElementById('image-builder-canvas');
    this.ctx = this.canvas.getContext("2d");
}

ImageBuilder.prototype.build = function(task, callback) {
    var self = this;
    //调用图片预加载函数，实现回调函数
    var imageObjects = [];
    this.loadImages(imageObjects, task.pictureUrls, 0, function(images) {
        var maxWidth = 0;
        var totalHeight = 0;
        for (var i = 0; i < images.length; i++) {
            //计算最大宽度与合计高度
            var image = images[i];
            maxWidth = Math.max(maxWidth, image.width);
            totalHeight += image.height;
        }
        if (maxWidth > 0 && totalHeight > 0) {
            //设置画布大小及背景颜色
            self.canvas.width = maxWidth;
            self.canvas.height = totalHeight;
            self.ctx.fillStyle = "#FFFFFF";
            self.ctx.fillRect(0, 0, maxWidth, totalHeight);
            //绘画到画布
            var height = 0;
            for (var i = 0; i < images.length; i++) {
                var image = images[i];
                self.ctx.drawImage(image, 0, 0, image.width, image.height, 0, height, image.width, image.height);
                height += image.height;
            }
            //生成合并后的图像数据
            task.imageData = this.canvas.toDataURL("image/jpeg");
            self.ctx.clearRect(0, 0, self.canvas.width, self.canvas.height);
        }
        callback();
    }, function(error) {
        if (error) {
            console.log(error);
        }
        callback('image load error');
    });
}

/*
实现一系列图片的预加载
参数urls:图片实际URL数组
参数number:array数组遍历下标
参数callback:回调函数——图片预加载完成后立即执行此函数
*/
ImageBuilder.prototype.loadImages = function(images, urls, number, callback, exception) {
    var self = this;
    var imageServer = this.markControl.context.imageServer;
    var defaultServer = this.markControl.option.imageServer;
    if (urls != undefined && number < urls.length) {
        var img = new Image();
        img.onload = function() {
            images.push(img);
            self.loadImages(images, urls, number + 1, callback, exception);
        }
        img.onerror = function() {
            img.onerror = undefined;
            //self.loadImages(images, urls, number + 1, callback);
            exception('load error for: ' + img.src);
        }
        img.crossOrigin = '';
        img.src = imageServer + urls[number] + '?' + new Date().getTime();
    } else {
        callback.call(this, images);
    }
}

ImageBuilder.prototype.canvas_dom = '<div><canvas id="image-builder-canvas"></canvas></div>';