/**
 * 显示消息提示框
 * @param content 提示的标题
 */
export function toast(content) {
	uni.showToast({
		icon: 'none',
		title: content
	})
}

/**
 * 显示模态弹窗
 * @param content 提示的标题
 */
export function showConfirm(content) {
	return new Promise((resolve, reject) => {
		uni.showModal({
			title: '提示',
			content: content,
			cancelText: '取消',
			confirmText: '确定',
			success: function(res) {
				resolve(res)
			}
		})
	})
}

/**
 * 参数处理
 * @param params 参数
 */
export function tansParams(params) {
	let result = ''
	for (const propName of Object.keys(params)) {
		const value = params[propName]
		var part = encodeURIComponent(propName) + "="
		if (value !== null && value !== "" && typeof(value) !== "undefined") {
			if (typeof value === 'object') {
				for (const key of Object.keys(value)) {
					if (value[key] !== null && value[key] !== "" && typeof(value[key]) !== 'undefined') {
						let params = propName + '[' + key + ']'
						var subPart = encodeURIComponent(params) + "="
						result += subPart + encodeURIComponent(value[key]) + "&"
					}
				}
			} else {
				result += part + encodeURIComponent(value) + "&"
			}
		}
	}
	return result
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    } else if (typeof time === 'string') {
      time = time.replace(new RegExp(/-/gm), '/').replace('T', ' ').replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * 传入一个年月日 计算出几岁几个月几天
 * @param {Object} birthDateString
 */
export function calculateAge(birthDateString,intoday = new Date()) {
	// 将出生日期字符串转换为Date对象
	const birthDate = new Date(birthDateString);

	// 获取当前日期
	const today = new Date(intoday);

	// 计算年份差
	let years = today.getFullYear() - birthDate.getFullYear();

	// 调整年份差，因为有可能还没过今年的生日
	const month = today.getMonth();
	const day = today.getDate();
	const birthMonth = birthDate.getMonth();
	const birthDay = birthDate.getDate();

	if (month < birthMonth || (month === birthMonth && day < birthDay)) {
		years--;
	}

	// 计算月份差（考虑到年份调整）
	let months = today.getMonth() - birthMonth;
	if (months < 0) {
		months += 12;
		// years--; // 如果月份是负数，说明还没过生日，年份再减一（但上面的逻辑已经处理了年份）
	}

	// 计算天数差
	let days = today.getDate() - birthDay;
	if (days < 0) {
		// 如果天数是负数，说明本月还没过生日，需要回退到上个月
		days += new Date(today.getFullYear(), today.getMonth(), 0).getDate();
		months--;

		// 如果月份已经是0了（实际上会是-1，因为减去了1），则年份也要减
		if (months < 0) {
			months += 12;
			// years--; // 但由于我们已经在上面处理过年份了，这里其实不需要再减
		}
	}

	return {
		years,
		months,
		days
	};
}




export function getParams(name) {
	var str = window.location.search.substr(1)
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
	var r = str.match(reg); //匹配目标参数
	if (r != null) {
		return decodeURIComponent(r[2]);
	}
	return null; //返回参数值
}

export function getQuery(name) {
	var reg = new RegExp('(^|&)' + name + '=(.*)(&[^&=]+=)');
	    var regLast = new RegExp('(^|&)' + name + '=(.*)($)');
	    var r = window.location.search.substr(1).match(reg) || window.location.search.substr(1).match(regLast);
	    if (r != null) {
	      var l = r[2].match(/&[^&=]+=/)
	      if (l) {
	        return decodeURIComponent(r[2].split(l[0])[0]);
	      } else return decodeURIComponent(r[2]);
	    }
	    return null;
}