/**
 * 获得base64
 * @param {Object} o
 * @param {Number} [o.width] 图片需要压缩的宽度
 * @param {Number} [o.height] 图片需要压缩的高度，为空则会跟随宽度调整
 * @param {Number} [o.quality=0.8] 压缩质量，不压缩为1
 * @param {Number} [o.mixsize] 上传图片大小限制
 * @param {Number} [o.type] 上传图片格式限制
 * @param {Function} [o.before(blob)] 处理前函数,this指向的是input:file
 * @param {Function} o.success(obj) 处理后函数
 * @param {Function} o.error(obj) 处理后函数
 * @example
 *
 * $('#test').UploadImg({
        url : '/upload.php',
        width : '320',
        //height : '200',
        quality : '0.8', //压缩率，默认值为0.8
        // 如果quality是1 宽和高都未设定 则上传原图
        mixsize : '1',
        //type : 'image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/bmp,image/x-png',
        before : function(blob){
            //上传前返回图片blob
            $('#img').attr('src',blob);
        },
        error : function(res){
            //上传出错处理
            $('#img').attr('src','');
            $('#error').html(res);
        },
        success : function(res){
            //上传成功处理
            $('#imgurl').val(res);
        }
    });
 */
/* 
    id上传标识 header_img等
    imgsrcs上传后需改变的src标签的id集合 array或者str类型  image_file_image_header或者['image_file_image_header','image_file_image_header']可传多个
    imgvals上传后需改变的val标签的id集合 array或者str类型  header_imgv或者['header_imgv','header_imgv']可传多个
    fnid 间接触发file的change事件，用来上传图片 
        moreid 是否为多图上传，用以改变回调值【晒图】
        moreval 要上传到服务端的标签的name标识
        morekey 要上传到服务端的标签的key标识

*/
//微信图片上传
if(!appId)appId='';
if(!signature)signature='';
var wxchooserimage=false;
if(appId && signature){
	wx.config({  
		debug: false,  
		appId: appId,  
		timestamp: timestamp,  
		nonceStr: nonceStr,  
		signature: signature,  
		jsApiList: [
			// 所有要调用的 API 都要加到这个列表中 
			'checkJsApi',
			'chooseImage',
            'uploadImage'
		]
	});
	wx.ready(function (){
	   wxchooserimage=true;
    });  
}
function HC_UPLOAD_IMG(obj){
    if(typeof(obj)!='object')return false;
    if(!obj.id)return false;
    if(!obj.upload_url)obj.upload_url=APP+'Home/File/upload';
    if(!obj.img_width)obj.img_width='500';
    if(!obj.img_height)obj.img_height='500';
    if(!obj.img_quality)obj.img_quality='0.9'; //压缩率，默认值为0.8
    
    var okfun=function(res){
        var imgsrcs = obj.imgsrcs;
        var imgvals = obj.imgvals;
        var moreid = obj.moreid;
        if(imgsrcs)set_img_info(imgsrcs,res.url,false);
        if(imgvals)set_img_info(imgvals,res.url,true);
        if(moreid){
            var moreval = obj.moreval;
            var morekey = obj.morekey;
            var d = new Date();
            var t = d.getTime();
            var i = $('#'+moreid+' img').length;							
            // $('#'+moreid).append("<dd><img src='" + res.url + "'><input type='hidden' name='"+moreval+"["+morekey+"]["+t+"n"+i+"]' value='"+res.url+"'></dd>");
            $('#'+moreid).append("<dd><img src='" + res.url + "' /><input type='hidden' name='"+moreval+"["+morekey+"]["+t+"n"+i+"]' value='"+res.url+"' /><i onclick='delete_img(this)'>-</i></dd>");
        }
    };
    
    
    if(obj.fnid){        
            $('#'+obj.fnid).click(function(){
                if(wxchooserimage){
                    wx.chooseImage({
                        count: 1, // 默认9
                        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
                        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
                        success: function(res) {
                            var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                            //$(obj).attr('src', localIds);
                            //console.log(localIds[0]);
                            // 上传照片
                            wx.uploadImage({
                                localId: localIds[0],
                                isShowProgressTips: 1,
                                success: function(res) {
                                    serverId = res.serverId;
                                    //console.log(serverId);
                                    $.ajax({
                                		url:APP + 'Home/File/upload',
                                		data:{'mediaid':serverId},
                                		type:"post",
                                		success:function(data){
                                			if(data.error==0) {
                                                okfun(data);
                    	            		}else{
                    	                		if(data.message)alert(data.message)
                    	            		}
                                		}
                                	})
                                    
                                }
                            });
                        },error: function(data, status, e) {
                            if(data.message)alert(data.message)
                		}
                    });
                }else{
                    $('#'+obj.id).click();
                }
            })
    }
    
    if(!wxchooserimage){
        $('#'+obj.id).UploadImg({
            id : obj.id,
            url : obj.upload_url,
            width : obj.img_width,
            height : obj.img_height,
            quality : obj.img_quality,
            mixsize : '10000000',
            before : function(blob){
                if(blob){
                    var imgsrcs = obj.imgsrcs;
                    if(imgsrcs)set_img_info(imgsrcs,blob,false);
                }else{ 
                    alert('暂不支持此浏览器');
                }
            },
            error : function(res){
                alert(res);
            },
            success :okfun
        });
    }
}
function set_img_info(obj,val,is_val){
    if(Object.prototype.toString.call(obj)=='[object Array]'){
        for(var i in obj){
            if(is_val){
                $('#'+obj[i]).val(val);
            }else{
                $('#'+obj[i]).attr('src',val);
            }
        }
    }else{
        if(is_val){
            $('#'+obj).val(val);
        }else{
            $('#'+obj).attr('src',val);
        }
    }
}
$.fn.UploadImg = function(o){
    $('#'+o.id).change(function() {
        var file = this.files['0'];
        // console.log(file);
        if(!o.type)o.type='image/png,image/jpg,image/jpeg,image/pjpeg,image/gif,image/bmp,image/x-png';
        if(file.size && file.size > o.mixsize){
            o.error('大小超过限制');
        }else if(o.type && o.type.indexOf(file.type) < 0){
            o.error('格式不正确');
        }else{
            if(typeof(URL)== "undefined" && typeof(webkitURL)== "undefined"){     
                if(window.FileReader) {
                    var fr = new FileReader();  
                    fr.onloadend = function(e) {  
                        var blob =e.target.result;  
                        o.before(blob);
                        _compress(blob,file);
                    };  
                    fr.readAsDataURL(file);  
                }                 
            }else{
                var URL = URL || webkitURL;
                var blob = URL.createObjectURL(file);
                o.before(blob);
                _compress(blob,file);
            }
        }
    });
    function _compress(blob,file){
        var img = new Image();
        img.src = blob;
        img.onload = function(){
            var canvas = document.createElement('canvas');
            var ctx = canvas.getContext('2d');
            if(!o.width && !o.height && o.quality == 1){
                var w = this.width;
                var h = this.height;
            }else{
                var w = o.width || this.width;
                var h = o.height || w/this.width*this.height;
            }
            $(canvas).attr({width : w, height : h});
            ctx.drawImage(this, 0, 0, w, h);
            var base64 = canvas.toDataURL(file.type, (o.quality || 0.8)*1 );
            if( navigator.userAgent.match(/iphone/i) ) {
                var mpImg = new MegaPixImage(img);
                mpImg.render(canvas, { maxWidth: w, maxHeight: h, quality: o.quality || 0.8, orientation: 6 });
                base64 = canvas.toDataURL(file.type, o.quality || 0.8 );
            }
            // 修复android
            if( navigator.userAgent.match(/Android/i) ) {
                var encoder = new JPEGEncoder();
                base64 = encoder.encode(ctx.getImageData(0,0,w,h), o.quality * 100 || 80 );
            }
            _ajaximg(base64,file.type);
        };
    }
    function _ajaximg(base64,type,file){
        $.post(o.url,{base64:base64,type:type},function(res){
            if(res.error == 1){
                o.error(res.message);
            }else{
                o.success(res);
            }
            // console.log(res);
        });
    }
};