
/**
 * 显示加载动画
 * @export
 * @param {string} [title="加载中..."]
 * @param {boolean} [mask=true]
 */
export function showLoading(title = "加载中...", mask = true) {
	uni.showLoading({
		title,
		mask
	})
}
/**
 * 关闭加载动画
 * @export
 */
export function hideLoading() {
	uni.hideLoading()
}
/**
 * 轻提示框
 * @export
 * @param {*} title
 * @param {*} duration
 */
export function toast(title = "", icon = "none", duration = 2000, cb) {
	uni.showToast({
		title,
		icon: icon,
		mask: false,
		duration,
		success: function() {
			cb && cb()
		}
	})
}

/**
 * 动态设置当前页面的标题
 * @export
 */
export function setNavigationBarTitle(title = '') {
	uni.setNavigationBarTitle({
		title
	});
}

/**
 * 图片预览
 * @export
 * @param {*} current
 * @param {*} [urls=[]]
 */
export function previewImage(current, urls = [],callback= () => {}) {
	uni.previewImage({
		current, // 当前显示图片的http链接
		urls ,// 需要预览的图片http链接列表,
		complete: function(e){
			callback(e)
		}
	})
}
/**
 * 从本地相册选择图片或使用相机拍照
 * @export
 * @param {string} [sourceType=['album', 'camera']]
 * @param {*} cb
 */
export function chooseImage(count = 9, success = () => {}, err = () => {}) {
	uni.chooseImage({
		count,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success(res) {
			// tempFilePath可以作为img标签的src属性显示图片
			const tempFilePaths = res.tempFilePaths;
			success(tempFilePaths)
		},
		fail() {
			err()
		}
	})
}
/**
 * 从本地相册选择图片或使用相机拍照
 * @export
 * @param {string} [sourceType=['album', 'camera']]
 * @param {*} cb
 */
export function chooseVideo(success = () => {},err = () => {},sourceType = ['album', 'camera']) {
	uni.chooseVideo({
		sourceType: sourceType,
		success(res) {
			// tempFilePath可以作为img标签的src属性显示图片
			console.log(res);
			const tempFilePath = res.tempFilePath;
			success(tempFilePath,res)
		},
		fail() {
			err()
		}
	})
}
/**
 * 图片预览跟视频
 * @export
 * @param {*} current
 * @param {*} [urls=[]]
 */
export function previewMedia(current, sources = [],callback= () => {}) {
	uni.previewMedia({
		current, // 当前显示index
		sources ,// 需要预览的http链接列表,
		complete: function(e){
			callback(e)
		}
	})
}
/**
 * 压缩图片接口，可选压缩质量
 * @export
 * @param {*} src
 * @param {*} [success=()=> {}]
 * @param {*} [err=()=> {}]
 */
export function compressImage(src, quality = 80, cb = () => {}, err = () => {}) {
	console.log(src, '|');
	uni.compressImage({
		src: src,
		quality: quality,
		success: res => {
			console.log(res.tempFilePath)
			cb(res.tempFilePath)
		},
		fail(e) {
			console.log("失败")
			err(e)
		}
	})
}
/**
 * setStorage 的同步版本
 * @export
 * @param {*} key
 * @param {*} val
 */
export function setStorageSync(key, val) {
	try {
		uni.setStorageSync(key, val)
	} catch (e) {

	}
}
export function setStorage(key, val) {
	try {
		uni.setStorage({
			key:key,
			data:val
		})
	} catch (e) {

	}
}
/**
 * getStorage 的同步版本
 * @export
 * @param {*} key
 * @returns
 */
export function getStorageSync(key) {
	try {
		return uni.getStorageSync(key)
	} catch (e) {

	}
}
/**
 * removeStorage 的同步版本
 * @export
 * @param {*} key
 */
export function removeStorageSync(key) {
	try {
		uni.removeStorageSync(key)
	} catch (e) {

	}
}


/**
 * clearStorage 的同步版本
 * @export
 */
export function clearStorageSync() {
	try {
		uni.clearStorageSync()
	} catch (e) {

	}
}
/**
 * 显示小红点
 * @export
 * @param {*} index
 */
export function showTabBarRedDot(index) {
	uni.showTabBarRedDot({
		index
	})
}

/**
 * 隐藏小红点
 * @export
 * @param {*} index
 */
export function hideTabBarRedDot(index) {
	uni.hideTabBarRedDot({
		index
	})
}

/**
 * 返回上一页
 * @export
 * @param
 */
export function navigateBack() {
	let pages = getCurrentPages();
	let page = pages[pages.length - 2];
	console.log(pages,page)
	if(page){
		uni.navigateBack();
	}else{
		uni.switchTab({
			url: '/pages/index/index'
		});
	}
}

export function formatDate(time, fmt) {
	if (!time) {
		return ''
	}
  let _date = new Date(time);
  let o = {
    'M+': _date.getMonth() + 1, // 月份
    'd+': _date.getDate(), // 日
    'h+': _date.getHours(), // 小时
    'm+': _date.getMinutes(), // 分
    's+': _date.getSeconds(), // 秒
    'q+': Math.floor((_date.getMonth() + 3) / 3), // 季度
    'S': _date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (_date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
  }
  return fmt;
}
//验证手机
export function isPhoneNumber(val){
	let rt = /^1\d{10}$/
	if(rt.test(val)){
		return true
	}else{
		return false
	} 
}

export function arrayKeyGroup(array,key='id'){
	let newArray = [];
	console.log(key)
	array.map(item=>{
		return [item]
	}).forEach(([{...item}])=>{
		const flag = newArray.find(([{...o}])=>o[key] === item[key]);
		if(!flag) {
			newArray.push([{...item}])
		} else {
			newArray.forEach(([{...y}], index)=>{
				if(y[key] === item[key]) {
				  newArray[index].push(item)
				}
			})
		}
	})
	return newArray
}

export function stringHide(string,start,end){
	let th = ''
	let xlen = end - start;
	for(let i =0;i < xlen;i++) {
		th += '*'
	}
	return string.substring(0,start) + th + string.substring(end,string.length)
}

export function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  const len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (let i = 0; i < len; i++) {
    const num1 = parseInt(v1[i])
    const num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

/**
 * 路由跳转
 * 
 * @param Object target {type, way, url}
 */
export function Target(target) {
	if (target.type === 'mini-program') {
		const way = target.way || 'navigateTo'
		const params = { url: target.url }
		switch (way) {
			case 'navigateTo':
				uni.navigateTo(params)
				break;
			case 'redirectTo':
				uni.redirectTo(params)
				break;
			case 'reLaunch':
				uni.reLaunch(params)
				break;
			case 'switchTab':
				uni.switchTab(params)
				break;
			case 'navigateBack':
				navigateBack()
				break;
		}
	}
}

// 判断是否为空
export function isEmpty(obj){
	if(typeof obj == "undefined" || obj == null || obj == ''){
			return true;
	}else{
			return false;
	}
}

export function getQueryName(str,name){
	let query = str.split('?')[1];
	let vars = query.split("&");
	for (let i=0;i<vars.length;i++) {
	   let pair = vars[i].split("=");
	   if(pair[0] == name){return pair[1];}
	}
	return(false);
}
//指定位置插入字符
export function insertStr(soure, start, newStr){
   return soure.slice(0, start) + newStr + soure.slice(start);
}
export function getSubscribeMessage(tmplIds,callback= () => {}){
	let _tmplIds = tmplIds;
	wx.requestSubscribeMessage({
	  tmplIds: _tmplIds,
	  success: (res)=> {
		  console.log(res,'成功')
		  let acceptnum = 0;
		  for(let vk of _tmplIds){
			  if(res[vk]==='accept'){//同意
				  acceptnum += 1
			  }
		  }
		  if(acceptnum==0){
			  
		  }else{
			  
			  callback(res)
		  }
	  },
	  fail:(err)=>{
		if (err.errCode == 20004) {
		  console.log('用户拒绝了',err)
		}else{
			callback(res)
		}
		
	  }
	})
}

export function testIdCard(id) {
   // 1 "验证通过!", 0 //校验不通过 // id为身份证号码
    var format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
    //号码规则校验
    if(!format.test(id)){
      return {'status':0,'msg':'身份证号码不合规'};
    }
    //区位码校验
    //出生年月日校验  前正则限制起始年份为1900;
    var year = id.substr(6,4),//身份证年
      month = id.substr(10,2),//身份证月
      date = id.substr(12,2),//身份证日
      time = Date.parse(month+'-'+date+'-'+year),//身份证日期时间戳date
      now_time = Date.parse(new Date()),//当前时间戳
      dates = (new Date(year,month,0)).getDate();//身份证当月天数
    if(time>now_time||date>dates){
      return {'status':0,'msg':'出生日期不合规'}
    }
    //校验码判断
    var c = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);  //系数
    var b = new Array('1','0','X','9','8','7','6','5','4','3','2'); //校验码对照表
    var id_array = id.split("");
    var sum = 0;
    for(var k=0;k<17;k++){
      sum+=parseInt(id_array[k])*parseInt(c[k]);
    }
    if(id_array[17].toUpperCase() != b[sum%11].toUpperCase()){
      return {'status':0,'msg':'身份证校验码不合规'}
    }
    return {'status':1,'msg':'校验通过'}
}
export function testEmail(email){
	let regEmail = new RegExp("^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$"); 
	return regEmail.test(email)
}
export function testBank(bank){
	let reg = /[1-9]\d{12,18}/;
	return reg.test(bank)
}
export function testPhone(phone){
	let reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
	return reg.test(phone)
}

// 获取近一周的日期范围
export function getLastWeekRange() {
  // 获取当前日期
  let currentDate = new Date();
  let lastWeekStartDate = new Date(currentDate);
  lastWeekStartDate.setDate(currentDate.getDate() - 7);
  let lastWeekEndDate = new Date(currentDate);
  lastWeekEndDate.setDate(currentDate.getDate() - 1);
  return {
    startDate: lastWeekStartDate,
    endDate: lastWeekEndDate,
  };
}

// 获取近一月的日期范围
export function getLastMonthRange() {
  let currentDate = new Date();
  let lastMonthStartDate = new Date(currentDate);
  lastMonthStartDate.setMonth(currentDate.getMonth() - 1);
  let lastMonthEndDate = new Date(currentDate);
  lastMonthEndDate.setDate(currentDate.getDate() - 1);
  return {
    startDate: lastMonthStartDate,
    endDate: lastMonthEndDate,
  };
}