import { get } from './db.js'
// 检验手机号格式
export const checkPhone = (mobile)=> {
   // return /^1[345678]\d{9}$/.test(mobile);
   if (mobile.length == 0) {
      return false;
   }
   if (mobile.length != 11) {
      return false;
   }
   // var myreg = /^0?(13[0-9]|15[0-9]|17[013678]|18[0-9]|14[57]|19[0-9]|18[0-9])[0-9]{8}$/;
   var myreg = /^1(3|4|5|6|7|8|9)\d{9}$/ ;
   if (!myreg.test(mobile)) {
      return false;
   }
   return true;
}
// 密码验证格式
export const checkPwd = (pwd)=> {
   if (pwd.length == 0) {
      return false;
   }
   var reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/
   var re = new RegExp(reg)
   if (re.test(pwd)) {
      return true;
   } else {
      return false;
   }
}
//不足位数前面补0
export const PrefixInteger = (num, length)=> {
	return (Array(length).join('0') + num).slice(-length)
}
/**
 *
 *  判断是否在微信浏览器 true是
 */
export const isWeiXinBrowser = ()=> {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase()
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == 'micromessenger') {
		return true
	} else {
		return false
	}
	// #endif

	return false
}
//深拷贝
export const deepCopy = (newobj, obj)=> {
	if (typeof obj != 'object') {
		return obj
	}
	for (var attr in obj) {
		var a = {}
		if (newobj[attr]) {
			a = newobj[attr]
		}
		newobj[attr] = deepCopy(a, obj[attr])
	}
	return newobj
}
//轻提示
export const toast = (msg = '', callback = function() {})=> {
	uni.showToast({
		title: msg,
		icon: 'none',
		duration: 1000,
		success() {
			setTimeout(function() {
				callback()
			}, 1500)
		}
	})

}
/* 弹窗 */
export const modal = (title='',content,callback = function() {}) => {
	uni.showModal({
	   title: title,
	    content: content,
		 confirmColor:'#3385FF',
	    success: function (res) {
	        if (res.confirm) {
	            callback()
	        } else if (res.cancel) {
	            // console.log('用户点击取消');
	        }
	    }
	});
}

/* 处理时间格式 */
export const dateFormatter = (str,bol=false,bol2=false) => { //默认返回yyyy-MM-dd HH-mm-ss
    var dateStr = String(str);
    if(!(dateStr.indexOf('-')>-1 && dateStr.indexOf('T')>-1)){
        dateStr = dateStr.replace(/\-/g,'/');
    }
	var d = new Date(dateStr);
	var year = d.getFullYear();
	var month = (d.getMonth() + 1) < 10 ? '0' + (d.getMonth() + 1) : (d.getMonth() + 1);
	var day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
	var hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours();
	var minute = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes();
	var second = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds();
	if(bol) {
        if(bol2){
            return `${month}月${day}日 ${hour}时${minute}分${second}秒`; 
        }
        return [year, month, day].join('-') + " " + [hour, minute, second].join(':');
	} else {
        if(bol2){
            return `${month}月${day}日`; 
        }
		return [year, month, day].join('-');
	}
}
//加载显示
export const loading = (msg = '加载中')=> {
	uni.showToast({
		title: msg,
		icon: 'loading'
	})
}

//加载隐藏
export const loadHide = ()=> {
	uni.hideToast();
}

/**
 * 函数防抖 (只执行最后一次点击)
 * @param fn
 * @param delay
 * @returns {Function}
 * @constructor
 */
export const Debounce = (fn, t=300) => {
  let timer;
  return function () {
    let args = arguments;
    if(timer){
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, t);
  }
};
/**
 * 函数节流
 * @param fn
 * @param interval
 * @returns {Function}
 * @constructor
 */
export const Throttle = (fn, t=500) => {
  let last;
  let timer;
  return function () {
    let args = arguments;
    let now = +new Date();
    if (last && now - last < t) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        last = now;
        fn.apply(this, args);
      }, t);
    } else {
      last = now;
      fn.apply(this, args);
    }
  }
}

// 上传图片封装
export const upload = ({
	/* 单张上传 */
   Single: function (Funurl, fn) {
		// 获取用户token和用户信息
		let token = get("access_token");
		let authHeader = token || '';
      uni.chooseImage({
         count: 1, ///最多可以选择一张图片
         sizeType: ['original', 'compressed'],//原图或压缩图
         sourceType: ['album', 'camera'],//图片来源
         success: function (res) {
            const tempFilePaths = res.tempFilePaths;//相当于src路径
            //console.log(tempFilePaths);
            uni.showToast({
               title: '正在上传...',
               icon: 'loading',
               mask: true,
               duration: 10000
            })
            uni.uploadFile({
               header: {
                  "Content-Type": "multipart/form-data",
						'Authorization':authHeader
               },
               name: 'file',
               url: Funurl,
               filePath: tempFilePaths[0],
               success(res) {
                  fn(res);
                  uni.hideToast();
                  uni.showToast({
                     title: '上传成功',
                     icon: 'none',
                     mark: true,
                  })
               },
               fail(err) {
                  uni.hideToast();
                  uni.showModal({
                     title: '错误提示',
                     content: '上传图片失败'+err,
                     showCancel: false,
                     success: function (res) { }
                  })
               }
            })
         },
      })
   },
   //上传多张图片
   Much: function (Funurl, fn, count) {
		// 获取用户token和用户信息
		let token = get("access_token");
		let authHeader = token || '';
      var list = new Array();
      uni.chooseImage({
         count: count,//最多可以选择3张图
         sizeType: ['original', 'compressed'],
         sourceType: ['album', 'camera'],
         success: function (res) {
            const tempFilePaths = res.tempFilePaths;
				console.log(tempFilePaths)
            let uploadImgCount = 0;
            uni.showToast({
               title: '正在上传...',
               icon: 'loading',
               mask: true,
               duration: 10000
            })
            for (var i = 0; i < tempFilePaths.length; i++) {
               uni.uploadFile({
                  url: Funurl,
                  name: 'file',
                  filePath: tempFilePaths[i],//第几张图片
                  header: {
                     "Content-Type": "multipart/form-data",
							'Authorization':authHeader
                  },
                  success(res) {
                     uploadImgCount++;
								fn(res);
                      //如果是最后一张,则隐藏等待中  
                     if (uploadImgCount === tempFilePaths.length) {
                        uni.hideToast();
                        // uni.showToast({
                        //    title: '上传图片成功',
                        //    icon: 'none',
                        //    mark: true,
                        // })
                     }else {
								that.upload(imgs)
							}
                  },
                  fail(res) {
                     uni.hideToast();
                     uni.showModal({
                        title: '错误提示',
                        content: '上传图片失败',
                        showCancel: false,
                        success: function (res) { }
                     })
                  }
               })
            }
         },
      })
   }
})

