 //压缩图片  用在热点图片上传、截图等   by xzw 

 import logger from './logger'
 import scaleImg from "./scaleImg" //利用外部插件 缩小的同时抗锯齿
 import { base64ToBlob } from './file'

 var CompressImg = function(img, option) {
     var type, canvas, ctx, img2;

     var draw = function(image) {
         canvas.width = image.width;
         canvas.height = image.height;
         ctx.drawImage(image, 0, 0, image.width, image.height);
     }
     var init = function(image) {
         canvas = document.createElement('canvas');
         ctx = canvas.getContext('2d');
         draw(image);
         var data = ctx.getImageData(0, 0, image.width, image.height).data;
         type = option.oldType || HasAlpha(data);
         //oldType最好是确定才给，否则利用函数判断
     }
     var HasAlpha = function(data) {
         var has = false;
         for (var i = 3; i < data.length; i += 4) {
             if (data[i] != 255) {
                 has = true;
                 break;
             }
         }
         return has ? "png" : "jpeg";
     }
     init(img);


     var oldSize = img.width * img.height;
     var sizeRatio = option.maxSize * option.maxSize / oldSize;
     var weightRatio = option.maxWeight / option.weight;
     var compress = function(ratio) {
         img2 = scaleImg(Math.sqrt(ratio), canvas, type);
     }

     if (weightRatio < 1) {
         if (type == "jpeg") {
             //通常jpg只要控制size不超过，数据量就不大  因为质量压缩
             compress(sizeRatio < 1 ? sizeRatio : weightRatio / 0.9);
         } else {
             compress(Math.min(sizeRatio, weightRatio));
             //主要是这个小心
         }	
     } else if (sizeRatio < 1) {
         compress(sizeRatio);
     }

     var newImg = img2 || new Image;
     //img;  不能使用原来的img，因为修改原图会再次触发img.onload
     var use = img2 || img;

     if (!newImg.base64Src) {
         var blob = base64ToBlob(use.src);
         if (blob.size > option.maxWeight) {
             //已保证size不会超出，再检查weight  主要是png
             logger.info("reOverWeight " + (blob.size - option.maxWeight) / 1024 + "KB");
             /* draw(use);	
             compress(option.maxWeight/blob.size); //黑了？
             blob = common.dataURLtoBlob(img2.src); */
         }
         if (option.info) {
             option.info.size = blob.size;
         }
         newImg.base64Src = use.src;
         newImg.src = window.URL.createObjectURL(blob);
     }

     if (option.info && !option.info.size)
         option.info.size = option.oldSize;

     return newImg;
 }


 export default CompressImg;