// commonUtils.js
const http = uni.$u.http

// 判断数据是否为空
function isDataEmpty(data) {
  if (data === null || data === undefined) {
    return true;
  }
  
  if (typeof data === 'string' && data.trim() === '') {
    return true;
  }
  
  if (Array.isArray(data) && data.length === 0) {
    return true;
  }
  
  if (typeof data === 'object' && Object.keys(data).length === 0) {
    return true;
  }
  
  return false;
}

// 日期转换
function formatDate(timestamp) {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	return `${year}-${month}-${day}`;
}

// 日期转换
function dateFormatYmd(dateStr) { 
	const timestamp = new Date(dateStr).getTime();
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = (date.getMonth() + 1).toString().padStart(2, '0');
	const day = date.getDate().toString().padStart(2, '0');
	return `${year}-${month}-${day}`;
}

// 获取服务器图片
async function getImgUrlByOssId(ossId){ 
	console.log(ossId)
	if(ossId){
		try {
			const res = await uni.$u.http.get('/resource/oss/listByIds/'+ossId,{data: {auth: true}}); 
			if(res.length > 0){
				console.log(res[0].url);
				const url = res[0].url;
				return url.replace(/^http:/, "https:");
			}
		} catch (err) { 
			await uni.showToast({ 
				title: "操作失败" 
			}); 
		} 
	}
	return null;
}

// 刷新用户登录信息
async function refreshUserLoginInfo(){ 
	uni.$u.http.get('/member/wechat/getUserInfo',{data: {auth: true}}).then((res)=>{
		// 数据获取token
		this.$store.commit('updateLoginUserInfo', res);
		console.log(this.$store.state.loginUserInfo)
	}).catch(() =>{
		uni.showToast({
			title: "操作失败"
		})
	});
}

// 替换http为https
function replaceHttpWithHttps(url){
	return url.replace(/^http:/, "https:");
}

// 导出工具类方法
export default {
  isDataEmpty,
  formatDate,
  dateFormatYmd,
  getImgUrlByOssId,
  refreshUserLoginInfo,
  replaceHttpWithHttps
};