var onePageOrder=[];var pageOrder=[];var pageNum=[];var sortNum=0;var fileLength=0;
function BubbleSort(obj,arr,numI){
    var len = arr.length;
    for (var i = 0; i < len - 1; i++) {
        for (var j = 0; j < len - 1 - i; j++) {
            if (arr[j] > arr[j+1]) {        // 相邻元素两两对比
                var temp = arr[j+1];        // 元素交换
                arr[j+1] = arr[j];
                arr[j] = temp;
                obj.find("p[data-index="+numI+"]").find("img").eq(j).before(obj.find("p[data-index="+numI+"]").find("img").eq(j+1));
            }
        }
    }
    return true;
}

function dataURLtoBlob(dataurl) {//将base64编码转换为Blob
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}
function getAjax($that,formData){
	var returnFlag;
	$.ajax({
        url : '/fileStorage/imgUpload',
        type : "POST",
        async : false,
        data : formData,
        dataType:"text",
        contentType: false,  
        processData: false,
        success:function(data){
        	console.log(data);
//        	for(var iii=0;iii<){
        		$that.append('<img src='+JSON.parse(data).url+'/>');
//        	}
        	sortNum++;
        	returnFlag=sortNum
        },
        error:function(){
        	sortNum++;
        	returnFlag.sortNum=sortNum;
        	returnFlag.flag="文件上传发生错误"
        },
        xhr:function(){            //在jquery函数中直接使用ajax的XMLHttpRequest对象
            var xhr = new XMLHttpRequest();
            
            xhr.upload.addEventListener("progress", function(evt){
                if (evt.lengthComputable) {
                    var percentComplete = Math.round(evt.loaded * 100 / evt.total);  
                    console.log("正在提交."+percentComplete.toString() + '%');        //在控制台打印上传进度
                }
            }, false);
            
            return xhr;
        }
        
    });
	return returnFlag
}

function openPage(pdfFile, pageNumber, context,numI) {
    var scale = 1;
    pdfFile.getPage(pageNumber).then(function(page) {
        viewport = page.getViewport(scale); // reference canvas via context
        var canvas = context.canvas;
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        canvas.style.width = "100%";
        canvas.style.height = "100%";
        var renderContext = {
            canvasContext: context,
            viewport: viewport
        };
        var renderTask = page.render(renderContext);//渲染完毕会返回一个回调函数
        renderTask.then(function () {
            onePageOrder.push(pageNumber);
            var image = new Image();
            image.src = canvas.toDataURL("image/png");
            $('#imgDiv').find("p[data-index="+numI+"]").append(image);
            var pN=0;
            for(var ii=0;ii<pageNum.length;ii++){
            	if(pageNum[ii].ind==numI){
            		pN=pageNum[ii].num
            	}
            }
            if($('#imgDiv').find("p[data-index="+numI+"] img").length===pN){//判断某个文件(一个文件被一个p包裹着,一个p标签可能有多张图片)是否已全部转换
                //此时渲染完毕，需要将img重新排序
            	
                var flag=BubbleSort($("#imgDiv"),onePageOrder,numI);
                if(flag){
                    onePageOrder.length=0;
                    var formData = new FormData();
                    $('#imgDiv').find("p[data-index="+numI+"]").find("img").each(function(i){
        				
                    	var base=$(this).attr("src");
        				
        				var base64Codes = dataURLtoBlob(base);
        			    
        				formData.append("myfile"+i, base64Codes, "filename1.png");
        				
            		})
            		$('#imgDiv').find("p[data-index="+numI+"]").empty();//先清空
            		//ajax 提交form
        			var ajaxFlag=getAjax($('#imgDiv').find("p[data-index="+numI+"]"),formData);
                    if(typeof ajaxFlag!="object"){
                    	if(ajaxFlag==fileLength){
                			$("#pdfDialog_info").text('确认成功');
                		}
                    }else {
                    	alert(ajaxFlag.flag);
                    }
            		
                    return true;
                }
            }
        }); 
    });
};

function getCanvas(j,pdf,i){
    var canvas = document.createElement('canvas');
    canvas.id = "pageNum" + j;
    //  $("#imgDiv").append(canvas);
    var context = canvas.getContext('2d');
    openPage(pdf, j, context, i);
}

function onLoad(file,i,editor){
    /*pdf.js无法直接打开本地文件,所以利用FileReader转换*/
    var reader = new FileReader();
    reader.readAsArrayBuffer(file);
    reader.onload = function (e) {
        var myData = new Uint8Array(e.target.result)
        var docInitParams = {
            data: myData
        };
        var typedarray = new Uint8Array(this.result);
        PDFJS.getDocument(typedarray).then(function (pdf) { //PDF转换为canvas
            $("#imgDiv").css("border", "0").append('<p data-index='+i+'></p>'); //清除文本、边框
            if (pdf) {
            	var temp={};
            	temp.ind=i;
            	temp.num=pdf.numPages
                pageNum.push(temp);
                for (var j = 1; j <= pdf.numPages; j++) {
                    getCanvas(j,pdf,i);
                }
            }
        });
    };
}

$(function(){
	var dialogData=[];
	
	$(".dialog_body").delegate(".cancel","click",function(){
		var index=$(this).parents('li').attr("data-fileIndex");
		for(var i=0;i<dialogData.length;i++){
			if(dialogData[i].lastModified==index){
				dialogData.splice(i,1);
				fileLength=dialogData.length;
			}
		}
		$(this).parents('li').remove();
	})
	$('#pdf').change(function () {
		var files = $('#pdf').prop('files'); //获取到文件
		var fl=files.length;
		$(".filelist").find(".filePickerBlock").remove();//先删除
        for(var i=0;i<fl;i++){
            var file=files[i];
            console.log(file);
            var fileSize = file.size;
            if (fileSize) {
	            mb = fileSize / 1048576;
	            if (mb > 10) {
	                alert("文件大小不能>10M");
	                return; 
	            }
	        }
            
            $(".filelist").append('<li data-fileIndex='+file.lastModified+'><p class="title" id="pdfName">'+file.name+'</p><div class="file-panel"><span class="cancel">删除</span></div><div class="file_background"></div></li>');
            
            dialogData.push(file);
            fileLength=dialogData.length;
            if(i+1==fl){
            	if(!$(".add").length){//如果还没有确认按钮
            		$(".upload_pdf-pick").before('<button class="add">确认</button>');
            	}
            	if(!$("#filePickerBlock").length){
            		$(".filelist").append('<li id="filePickerBlock" class="filePickerBlock webuploader-container"><div class="webuploader-pick"></div><div class="fileloader_contain" style=""><label for="pdf" class="upload_pdf_label"></label></div></li>');
            	}
        	}
        }
	})
	$(".dialog_max").delegate(".add","click",function(){
		var fl=dialogData.length;
		$("#dialog_body").empty().append('<div id="pdfName"></div><div id="sizeText"></div><div id="pagesText"></div><div id="imgDiv"></div>');
        for(var i=0;i<fl;i++){
            var file=dialogData[i];
            // $("#sizeText").text(mb.toFixed(2) + "Mb");
            onLoad(file,i); 
        }
        $(this).remove();
	})
	
})