import CONFIG from '@/config'
export const formatTime = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

export const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};
export function  resetNum(num, type = 'first', fixNum = 6) {
	const pow = Math.pow(10, fixNum);
	if (type === 'end') {
		return (Number(num) / pow).toFixed(4)
	}
	return Number(num) * pow
	  
  }
export function setTabBarBadge (num, index = 1) {
	if (num < 1) {
		uni.removeTabBarBadge({
			index
		})
		return
	}
	uni.setTabBarBadge({
	  //给tabBar添加角标
	  index,
	  text: String(num)
	});
}
export function toast(message = 'message', duration = 2000) {
	uni.showToast({
		title: message,
		icon: 'none',
		duration
	})
}
export function getFileList (url) {
	
	const imgType = ['.png', '.jpeg', '.jpg','.xbm','.tif','.ico','.tiff','.gif','.svg','.webp','.bmp','.pjp','.apng','.pjpeg','.avif']
	const urls = url ? url.split(',') : []
	return urls.map(v => {
		const isImg = imgType.some(item => v.includes(item))
		const type = isImg ? 'img' : 'video'
		console.Console
		return {
			type,
			_url: v,
			url: CONFIG.imgUrl + v
		}
	})
	 
}
export const debounce = (() => {
  let timer = null
  return (callback, wait = 800) => {
    timer&&clearTimeout(timer)
    timer = setTimeout(callback, wait)
  }
})();

// 图片旋转处理 => output(base64)
export const rotateBase64Img = (src, edg, callback) => {
  try {
    const canvas = document.createElement('canvas')
    const ctx = canvas.getContext('2d')

    let imgW = 0 // 图片宽度
    let imgH = 0 // 图片高度
    let size = 0 // canvas初始大小

    if (edg % 90 !== 0) {
      throw new Error('旋转角度必须是90的倍数!')
    }

    (edg < 0) && (edg = (edg % 360) + 360)
    const quadrant = (edg / 90) % 4 // 旋转象限
    const cutCoor = { sx: 0, sy: 0, ex: 0, ey: 0 } // 裁剪坐标

    const image = new Image()
    image.src = src
    image.crossOrigin = 'anonymous'

    image.onload = function () {
      imgW = image.width
      imgH = image.height
      size = imgW > imgH ? imgW : imgH

      canvas.width = size * 2
      canvas.height = size * 2
      switch (quadrant) {
        case 0:
          cutCoor.sx = size
          cutCoor.sy = size
          cutCoor.ex = size + imgW
          cutCoor.ey = size + imgH
          break
        case 1:
          cutCoor.sx = size - imgH
          cutCoor.sy = size
          cutCoor.ex = size
          cutCoor.ey = size + imgW
          break
        case 2:
          cutCoor.sx = size - imgW
          cutCoor.sy = size - imgH
          cutCoor.ex = size
          cutCoor.ey = size
          break
        case 3:
          cutCoor.sx = size
          cutCoor.sy = size - imgW
          cutCoor.ex = size + imgH
          cutCoor.ey = size + imgW
          break
      }

      ctx.translate(size, size)
      ctx.rotate(edg * Math.PI / 180)
      ctx.drawImage(image, 0, 0)

      const imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey)
      if (quadrant % 2 === 0) {
        canvas.width = imgW
        canvas.height = imgH
      } else {
        canvas.width = imgH
        canvas.height = imgW
      }
      ctx.putImageData(imgData, 0, 0)

      if (typeof callback === 'function') {
		  const blob = base64ImgtoFile(canvas.toDataURL('image/png', 0.7))
			const blobUrl = window.URL.createObjectURL(blob);
			callback(blobUrl)
      }
    }
  } catch (e) {
    console.log(e)
  }
}

function base64ImgtoFile (dataurl, filename = 'file') {
        //将base64格式分割：['data:image/png;base64','XXXX']
        const arr = dataurl.split(',')
        // .*？ 表示匹配任意字符到下一个符合条件的字符 刚好匹配到：
        // image/png
        const mime = arr[0].match(/:(.*?);/)[1]  //image/png
        //[image,png] 获取图片类型后缀
        const suffix = mime.split('/')[1] //png
        const bstr = atob(arr[1])   //atob() 方法用于解码使用 base-64 编码的字符串
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {
            type: mime
        })
    }