
import env from "@/http/config/config.js"
/**
 * 判断字符串是否为空
 * @param obj
 * @returns {boolean}
 */

export const isStringEmpty = (obj) => {
	if (typeof obj == "undefined" || obj == null || obj === "") {
		return true;
	} else {
		return false;
	}
}

/**
 * 判断对象、字符串是否为空
 * @param obj
 * @returns {boolean}
 */
export const isObjStringEmpty = (obj) => {
	if (typeof obj == "object" && JSON.stringify(obj) == "{}") {
		return true;
	} else {
		return isStringEmpty(obj);
	}
}

/**
 * 判断字符串是否非空
 * @param obj
 * @returns {boolean}
 */
export const isStringNotEmpty = (obj) => {
	return !isStringEmpty(obj);
}

/**
 * 判断对象、字符串是否非空
 * @param obj
 * @returns {boolean}
 */
export const isObjStringNotEmpty = (obj) => {
	return !isObjStringEmpty(obj);
}

/**
 * 字符串如果为空，转换字符串为null
 * @param obj
 * @returns {boolean}
 */
export const changeStringEmptyToNull = (obj) => {
	if (isStringEmpty(obj)) {
		obj = null;
	}
	return obj;
}

/**
 * 字符串如果为空，转换字符串为""
 * @param obj
 * @returns {boolean}
 */
export const changeStringNullToEmpty = (obj) => {
	if (typeof obj == "undefined" || obj == null) {
		obj = "";
	}
	return obj;
}

/**
 * 字符串如果为空，转换字符串为""
 * @param obj
 * @returns {boolean}
 */
export const stringEndWith = (str) => {
	if (str == null || str == "" || this.length == 0 || str.length > this.length)
		return false;
	if (this.substring(this.length - str.length) == str)
		return true;
	else
		return false;
};


export const formatDate = (shijianchuo) => {
	//shijianchuo是整数，否则要parseInt转换
	function add0(m) {
		return m < 10 ? '0' + m : m
	}
	var time = new Date(shijianchuo);
	var y = time.getFullYear();
	var m = time.getMonth() + 1;
	var d = time.getDate();
	var h = time.getHours();
	var mm = time.getMinutes();
	var s = time.getSeconds();
	return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s);
}
/**
 * 格式化时间对象
 * @param {string}  fmt Date对象的格式化格式：如yyyy-MM-dd HH:mm:ss
 * @param {date}  date 需要格式化的时间对象
 * @return {string} 返回格式化后的字符串，如2020-0101 00:00:00
 * */
export const formatDateToStr = function (fmt, date) {
	fmt = fmt.replace("hh", "HH")
	let ret;
	// debugger
	const opt = {
		"y+": date.getFullYear().toString(),
		"M+": (date.getMonth() + 1).toString(),
		"d+": date.getDate().toString(),
		"H+": date.getHours().toString(),
		"m+": date.getMinutes().toString(),
		"s+": date.getSeconds().toString(),
	};
	for (let k in opt) {
		ret = new RegExp(`(${k})`).exec(fmt);
		if (ret) {
			fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, "0"))
		}
	}
	return fmt
}
/**
 * 格式化时间对象
 * @param {string}  str 要转换成时间对象的字符串，如2020-0101 00:00:00
 * @return {date} 转换后的时间对象
 * */
export function formatStrToDate(str) {
	return new Date(Date.parse(str.replace(/-/g, "/")));
}


//数字校验
export const digits = (str, bol) => {
	var regexp = /^[0-9]*$/;

	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}
};

//校验只能输入大于0的正整数
export const checkNum0 = (str, bol) => {
	var regexp = /^[1-9]\d*$/;
	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}
};

//校验只能输入大于1的正整数
export const checkNum1 = (str) => {
	var regexp = /^[2-9]\d*$/;
	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}
};

//校验金额（精确到小数点2位）
export const moneyvalid = (str, bol) => {
	var reg = /^^\d+(\.\d{2})+$/;
	if (bol) {
		if (reg.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (reg.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}
};

//校验只能输入字母
export const english = (str, bol) => {
	var regexp = /^[A-Za-z]+$/;
	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}
};

//检验只能输入汉字
export const chinese = (str, bol) => {
	var regexp = /^[\u4e00-\u9fa5]{0,}$/;
	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}
};


//校验数字和字母
export const letterOrNumberonly = (str, bol) => {
	var regexp = /^[A-Za-z0-9]+$/;
	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}


};

//校验数字、字母及下划线
export const letterOrNumberOrUnderline = (str, bol) => {
	var regexp = /^\w+$/;
	if (bol) {
		if (regexp.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}
	}

};
//邮箱校验
export const email = (str, bol) => {
	var regexp = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
	var regexp2 = /^[A-Za-z0-9._%-]+@([A-Za-z0-9-]+\.)+[A-Za-z]{2,4}$/;
	if (bol) {
		if (regexp.test(str) || regexp2.test(str)) {
			return false;
		}
		return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (regexp.test(str) || regexp2.test(str)) {
				return false;
			}
			return true;
		} else {
			return false
		}

	}

};

//校验手机号码
export const mobile = (str, bol) => {
	var isMobile = /^1(3|4|5|6|7|8|9)\d{9}$/;
	if (bol) {
		if (isMobile.test(str))
			return false
		else
			return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (isMobile.test(str))
				return false
			else
				return true;
		} else {
			return false
		}

	}

};

//校验固定电话
export const phone = (str, bol) => {
	var homeMobile = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
	if (bol) {
		if (homeMobile.test(str))
			return false
		else
			return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (homeMobile.test(str))
				return false
			else
				return true;
		} else {
			return false
		}

	}

};

//校验电话号码
export const mobileOrPhone = (str, bol) => {
	var homeMobile = /^((0\d{2,3})-)(\d{7,8})(-(\d{3,}))?$/;
	var isMobile = /^1(3|4|5|6|7|8|9)\d{9}$/;
	if (bol) {
		if (homeMobile.test(str) || isMobile.test(str))
			return false
		else
			return true;
	} else {
		if (typeof str != "undefined" && str.length > 0) {
			if (homeMobile.test(str) || isMobile.test(str))
				return false
			else
				return true;
		} else {
			return false
		}

	}

};

//校验身份证号
export const idcard = (str) => {
	var idcard1 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
	var idcard2 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
	if (idcard1.test(str) || idcard2.test(str))
		return false
	else
		return true;
};

//获取本周
export const getCurrentWeek = (str) => {
	//获取当前时间
	const currentDate = new Date(str)
	//返回date是一周中的某一天
	const week = currentDate.getDay()
	//一天的毫秒数
	const millisecond = 1000 * 60 * 60 * 24
	//减去的天数
	const minusDay = week != 0 ? week - 1 : 6
	//本周 周一
	const monday = new Date(currentDate.getTime() - minusDay * millisecond)
	//本周 周日
	const sunday = new Date(monday.getTime() + 6 * millisecond)
	return [monday, sunday]
};

//获取上一周
export const handleGetPrevWeek = (str) => {
	const Time = new Date(str)
	let weekNum = Time.getDay()
	weekNum = weekNum == 0 ? 7 : weekNum
	let lastDate = new Date(Time.getTime() - weekNum * 24 * 60 * 60 * 1000)
	let fitstDate = new Date(
		Time.getTime() - (weekNum + 6) * 24 * 60 * 60 * 1000
	)
	let startDate =
		`${fitstDate.getFullYear()}-${fitstDate.getMonth() + 1 < 10
			? '0' + (fitstDate.getMonth() + 1)
			: fitstDate.getMonth() + 1
		}-${fitstDate.getDate() < 10
			? '0' + fitstDate.getDate()
			: fitstDate.getDate()
		}`
	let endDate =
		`${lastDate.getFullYear()}-${lastDate.getMonth() + 1 < 10
			? '0' + (lastDate.getMonth() + 1)
			: lastDate.getMonth() + 1
		}-${lastDate.getDate() < 10 ? '0' + lastDate.getDate() : lastDate.getDate()
		}`
	return [startDate, endDate]
};


//获取下一周
export const handleGetNextvWeek = (str) => {
	const Time = new Date(str)
	let weekNum = Time.getDay()
	weekNum = weekNum == 0 ? 7 : weekNum

	let fitstDate = new Date(
		Time.getTime() + (7 - weekNum + 1) * 24 * 60 * 60 * 1000
	)
	let lastDate = new Date(
		Time.getTime() + (7 - weekNum + 7) * 24 * 60 * 60 * 1000
	)
	let startDate =
		`${fitstDate.getFullYear()}-${fitstDate.getMonth() + 1 < 10
			? '0' + (fitstDate.getMonth() + 1)
			: fitstDate.getMonth() + 1
		}-${fitstDate.getDate() < 10
			? '0' + fitstDate.getDate()
			: fitstDate.getDate()
		}`
	let endDate =
		`${lastDate.getFullYear()}-${lastDate.getMonth() + 1 < 10
			? '0' + (lastDate.getMonth() + 1)
			: lastDate.getMonth() + 1
		}-${lastDate.getDate() < 10 ? '0' + lastDate.getDate() : lastDate.getDate()
		}`
	return [startDate, endDate]
}

// url参数解析
export const getUrlkey = (url) => {
	var params = {};
	var urls = url.split("?");
	var arr = urls[1].split("&");
	for (var i = 0, l = arr.length; i < l; i++) {
		var a = arr[i].split("=");
		params[a[0]] = a[1];
	}
	return params;
}

//获取上一个年月
export const getPreMonth = () => {
	var date = new Date();
	var year = date.getFullYear();
	var month = date.getMonth()
	if (month == 0) {
		year = year - 1;
		month = 12;
	}
	month = month <= 9 ? "0" + month : month
	return year + '年' + month + '月'
}

//解决IOS日期显示问题
export const formateIOS = (str, pattern) => {
	var format = str.replace(/\-/g, "/"); //把“-”，替换成‘/’
	var date = new Date(format),
		y = date.getFullYear(),
		m = (date.getMonth() + 1).toString().padStart(2, 0),
		d = date.getDate().toString().padStart(2, 0),
		h = date.getHours().toString().padStart(2, 0),
		mi = date.getMinutes().toString().padStart(2, 0),
		se = date.getSeconds().toString().padStart(2, 0);
	if (pattern == "yyyy.mm.dd") {
		return `${y}.${m}.${d}`;
	} else {
		return y + '-' + m + '-' + d;
	}
}

//小写金额转大写
export const DX = (n) => {
	var newchar = "";
	var Num = n;
	if (Num == "") {
		//输入框删减为空时，将大写金额的内容值设为原始状态，当然也可以根据需求进行修改
		newchar = "零元整";
		return newchar;
	}
	var part = String(Num).split(".");
	for (let i = part[0].length - 1; i >= 0; i--) {
		if (part[0].length > 10) {
			newchar = "位数过大，无法计算"; //前面如果有验证位数的，此处判断可去掉
			return newchar;
		}
		var tmpnewchar = ""
		var perchar = part[0].charAt(i);
		switch (perchar) {
			case "0":
				tmpnewchar = "零" + tmpnewchar;
				break;
			case "1":
				tmpnewchar = "壹" + tmpnewchar;
				break;
			case "2":
				tmpnewchar = "贰" + tmpnewchar;
				break;
			case "3":
				tmpnewchar = "叁" + tmpnewchar;
				break;
			case "4":
				tmpnewchar = "肆" + tmpnewchar;
				break;
			case "5":
				tmpnewchar = "伍" + tmpnewchar;
				break;
			case "6":
				tmpnewchar = "陆" + tmpnewchar;
				break;
			case "7":
				tmpnewchar = "柒" + tmpnewchar;
				break;
			case "8":
				tmpnewchar = "捌" + tmpnewchar;
				break;
			case "9":
				tmpnewchar = "玖" + tmpnewchar;
				break;
		}
		switch (part[0].length - i - 1) {
			case 0:
				tmpnewchar = tmpnewchar + "元";
				break;
			case 1:
				if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
				break;
			case 2:
				if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
				break;
			case 3:
				if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
				break;
			case 4:
				tmpnewchar = tmpnewchar + "万";
				break;
			case 5:
				if (perchar != 0) tmpnewchar = tmpnewchar + "拾";
				break;
			case 6:
				if (perchar != 0) tmpnewchar = tmpnewchar + "佰";
				break;
			case 7:
				if (perchar != 0) tmpnewchar = tmpnewchar + "仟";
				break;
			case 8:
				tmpnewchar = tmpnewchar + "亿";
				break;
			case 9:
				tmpnewchar = tmpnewchar + "拾";
				break;
		}
		newchar = tmpnewchar + newchar;
	}
	if (("" + Num).indexOf(".") != -1) {
		if (part[1].length > 2) {
			part[1] = part[1].substr(0, 2)
		}
		for (i = 0; i < part[1].length; i++) {
			tmpnewchar = ""
			var perchar = part[1].charAt(i)
			switch (perchar) {
				case "0":
					tmpnewchar = "零" + tmpnewchar;
					break;
				case "1":
					tmpnewchar = "壹" + tmpnewchar;
					break;
				case "2":
					tmpnewchar = "贰" + tmpnewchar;
					break;
				case "3":
					tmpnewchar = "叁" + tmpnewchar;
					break;
				case "4":
					tmpnewchar = "肆" + tmpnewchar;
					break;
				case "5":
					tmpnewchar = "伍" + tmpnewchar;
					break;
				case "6":
					tmpnewchar = "陆" + tmpnewchar;
					break;
				case "7":
					tmpnewchar = "柒" + tmpnewchar;
					break;
				case "8":
					tmpnewchar = "捌" + tmpnewchar;
					break;
				case "9":
					tmpnewchar = "玖" + tmpnewchar;
					break;
			}
			if (i == 0) tmpnewchar = tmpnewchar + "角";
			if (i == 1) tmpnewchar = tmpnewchar + "分";
			newchar = newchar + tmpnewchar;
		}
	}
	while (newchar.search("零元") != -1) {
		newchar = newchar.replace("零零", "零");
		newchar = newchar.replace("零亿", "亿");
		newchar = newchar.replace("亿万", "亿");
		newchar = newchar.replace("零万", "万");
		newchar = newchar.replace("零元", "元");
		newchar = newchar.replace("零角", "");
		newchar = newchar.replace("零分", "");
	}
	if (newchar.charAt(newchar.length - 1) == "元" || newchar.charAt(newchar.length - 1) == "角") {
		newchar = newchar + "整";
	}
	return newchar;
}
//计算数组对象某个属性的总和
export const countTotal = (arr, keyName) => {
	let $total = 0;
	$total = arr.reduce(function (total, currentValue, currentIndex, arr) {
		return parseFloat(currentValue[keyName]) ? (total + parseFloat(currentValue[keyName])) : total;
	}, 0);
	return $total;
}

//防抖函数
let timeout = null;
export const debounce = (fn, wait) => {
	if (timeout != null) clearTimeout(timeout)
	timeout = setTimeout(fn, wait)
}


//对象深拷贝
export const deepClone = (obj) => {
	let objClone = Array.isArray(obj) ? [] : {};
	if (obj && typeof obj === "object") {
		for (var key in obj) {
			if (obj.hasOwnProperty(key)) {
				//判断ojb子元素是否为对象，如果是，递归复制
				if (obj[key] && typeof obj[key] === "object") {
					objClone[key] = deepClone(obj[key]);
				} else {
					//如果不是，简单复制
					objClone[key] = obj[key];
				}
			}
		}
	}
	return objClone;
}


//字母大写转小写
export const  strChange = (arg) => {
    var str=arg.split('');
    for(var i = 0; i < str.length; i++) {
        if (str[i].charAt() >= "a" && str[i].charAt() <= "z") {
			//转换成大写
            // str[i] = str[i].toUpperCase();
        } else {
			//转换成小写
            str[i] = str[i].toLowerCase();
        }
    }
    return str.join('');
}

//创建unid
export const createUnid = () => {
	var unid = "";
	const str = "0 1 2 3 4 5 6 7 8 9 A B C D E F"
	var arr = str.split(" ");
	var dateStr = getCurDateStr();
	for (let i = 0; i < 18; i++) {
		unid += arr[Math.round(Math.random() * (arr.length - 1))];
	}
	return dateStr + unid;
}


const getCurDateStr = () => {
	//获取当前时间
	var mydate = new Date();
	var newyear = mydate.getFullYear();
	var newmonth = mydate.getMonth() + 1;
	newmonth = (newmonth < 10 ? "0" + newmonth : newmonth);
	var newDate = mydate.getDate();
	newDate = (newDate < 10 ? "0" + newDate : newDate);
	var hours = mydate.getHours(); //获取当前小时数(0-23)
	hours = (hours < 10 ? "0" + hours : hours);
	var minutes = mydate.getMinutes(); //获取当前分钟数(0-59)
	minutes = (minutes < 10 ? "0" + minutes : minutes);
	var seconds = mydate.getSeconds(); //获取当前秒数(0-59)
	seconds = (seconds < 10 ? "0" + seconds : seconds);
	var datetime = "" + newyear + newmonth + newDate + hours + minutes + seconds;
	return datetime;
}

//获取短信模板消息体 已使用
export const getmestemplate = async (e) => {
	const res = await getSmsTemplate(e)
	return res.data.data
}

//通过字典获取值
export const queryType = async (e) => {
	const res = await queryByType(e)
	return res.data.data[e.dictTypes].map(item => {
		return {
			label: item.dictname,
			value: item.dictvalue,
		}
	});
}


//把年月日时间格式转换成可以识别的时间格式
export const getDateToNum = (date) => {
	let redate = ""
	if (date.indexOf("年") > 1) {
		redate = date.substring(0, date.indexOf("年"))
	}
	if (date.indexOf("月") > 1) {
		redate = redate + "-" + date.substring(date.indexOf("月") - 2, date.indexOf("月"))
	}
	if (date.indexOf("日") > 1) {
		redate = redate + "-" + date.substring(date.indexOf("日") - 2, date.indexOf("日"))
	}
	return redate
}
/**
 * 弹窗提示方法
 * @param {String} msg 提示的消息
 * @param {Function} func 成功后执行的方法
 */
export async function toastFunc(msg = '', func = null) {
	uni.showToast({
		icon: "none",
		title: msg,
		complete() {
			setTimeout(async () => {
				func && await func()
			}, 1000)
		}
	})
}


/**
 * 模态框提示方法
 * @param {String} msg 提示的消息
 * @param {Function} func 点击确定后执行的方法
 */
export function modalFunc(msg = '', func = null, func2 = null) {
	uni.showModal({
		title: '提示',
		content: msg,
		complete(e) {
			if (e.confirm) {
				//点击确定执行的方法
				func && func()
			}else if(e.cancel){
				//点击取消执行的方法
				func2 && func2()
			}
		}
	})
}

// 跳转缺省页面
export function jumpResponseHandle(code, msg) {
	uni.redirectTo({
		url: '/pages/commonview/responceHandle?code=' + code + '&msg=' + msg
	})
}

// 判断日期大小
export function computingDate(startDate, endDate) {
	startDate = new Date(startDate).getTime()
	endDate = new Date(endDate).getTime()
	if (startDate == endDate) {
		return '等于'
	} else if (startDate < endDate) {
		return '小于'
	} else {
		return '大于'
	}
}

//获取本周日期 i传0 返回本周第一天
export function getWeek(i) {
	var now = new Date();
	var firstDay = new Date(now - (now.getDay() - 1) * 86400000);
	firstDay.setDate(firstDay.getDate() + i);
	let mon = Number(firstDay.getMonth()) + 1;
	let day = firstDay.getDate();
	if (mon < 10) {
		mon = '0' + mon
	}
	if (day < 10) {
		day = '0' + day
	}
	return now.getFullYear() + "-" + mon + "-" + day;
}

export function changeNumToHan(num) {
	var arr1 = new Array('零', '一', '二', '三', '四', '五', '六', '七', '八', '九');
	var arr2 = new Array('', '十', '百', '千', '万', '十', '百', '千', '亿', '十', '百', '千', '万', '十', '百', '千', '亿');//可继续追加更高位转换值
	if (!num || isNaN(num)) {
		return "零";
	}
	var english = num.toString().split("")
	var result = "";
	for (var i = 0; i < english.length; i++) {
		var des_i = english.length - 1 - i;//倒序排列设值
		result = arr2[i] + result;
		var arr1_index = english[des_i];
		result = arr1[arr1_index] + result;
	}
	//将【零千、零百】换成【零】 【十零】换成【十】
	result = result.replace(/零(千|百|十)/g, '零').replace(/十零/g, '十');
	//合并中间多个零为一个零
	result = result.replace(/零+/g, '零');
	//将【零亿】换成【亿】【零万】换成【万】
	result = result.replace(/零亿/g, '亿').replace(/零万/g, '万');
	//将【亿万】换成【亿】
	result = result.replace(/亿万/g, '亿');
	//移除末尾的零
	result = result.replace(/零+$/, '')
	//将【零一十】换成【零十】
	//result = result.replace(/零一十/g, '零十');//貌似正规读法是零一十
	//将【一十】换成【十】
	result = result.replace(/^一十/g, '十')
	return result;
}
