
export function packTime( mytime ){
    if( mytime < 0) mytime = -mytime;
    let obj = {'v': mytime};
    let h =  parseInt(mytime / 3600);
    let m =  parseInt( (mytime %3600)/60);
    let s = mytime % 60;
    obj.h = h<10?"0"+h:h;
    obj.m = m<10?"0"+m:m;
    obj.s = s<10?"0"+s:s;
    return obj;
}

export function time2str( mt ){
    let  timestamp4 = new Date( mt*1000 );
    return timestamp4.toLocaleDateString().replace(/\//g, "-") + " " + timestamp4.toTimeString().substr(0, 8);
}


export function timeinfo( mt ){
    let  timestamp4 = new Date( mt*1000 );
    return timestamp4.toTimeString().substr(0, 8);
}


export function getTime(){
    return parseInt( Date.now()/1000);
}

export function sec2Time( mtime ){
    let res = "";
    let divTime = 30*86400;
    if( mtime > divTime ){
        res+= parseInt(mtime/divTime)+'月';
        mtime %= divTime
    }
    divTime = 7*86400;
    if( mtime > divTime ){
        res+= parseInt(mtime/divTime)+'周';
        mtime %= divTime
    }
    divTime = 86400;
    if( mtime > divTime ){
        res+= parseInt(mtime/divTime)+'天';
        mtime %= divTime
    }

    divTime = 3600;
    if( mtime > divTime ){
        res+= parseInt(mtime/divTime)+'小';
        mtime %= divTime
    }

    divTime = 60;
    if( mtime > divTime ){
        res+= parseInt(mtime/divTime)+'分';
        mtime %= divTime
    }
    return res+= mtime +'秒';
}


var dataURLtoFile = function(dataurl) {
  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 File([u8arr], { type: mime });

}
//压缩图片 k 为单位
export function compressImg(file, needSize ){
  var src;
  var files;
  var fileSize = parseInt(file['size'])/1024;
  var rate = 1
  if( fileSize > 10 * needSize ){
    rate = 0.3;
  }else if( fileSize> 2*needSize) {
    rate = 0.5
  }else{
    rate = 1
  }
  var read = new FileReader();
  read.readAsDataURL(file);
  return new Promise(function(resolve, reject){
   read.onload = function (e) {
     var img = new Image();
     img.src = e.target.result;
     img.onload = function(){
       //默认按比例压缩
       var w = this.width,
         h = this.height;

       var nw = 300
       var nh = h * nw/w
       //生成canvas
       var canvas = document.createElement('canvas');
       var ctx = canvas.getContext('2d');
       var base64;
       // 创建属性节点
       canvas.setAttribute("width", nw);
       canvas.setAttribute("height", nh);
       ctx.drawImage(this, 0, 0, nw, nh);
       base64 = canvas.toDataURL(file['type'], rate);

       // 回调函数返回file的值（将base64编码转成file）
       files = dataURLtoFile(base64); //如果后台接收类型为base64的话这一步可以省略

       resolve(files)
     };
   };
  })
};
