 
 
import {checkLogin} from '@/api/user'
export function isEmpty(obj) {
	if (obj == "undefined" || obj == null || obj == "") {
		return true;
	} else {
		return false;
	}
}
 
 
export function isLogin() {
	return new Promise((resolve, reject) => {
		checkLogin().then(
			res => {
				if(res.code==200){
					resolve(true);
				}else{
					resolve(false);
				}
			},
			rej => { }
		);
	}); 
}

export function isLoginCourse() {
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('AppTokenmini_RTCourse');
		if (token==null||token==undefined||token=="" ) {
			resolve(false);
		} else {
			resolve(true);
		}
	}); 
}

export function getDictLabelName(dicts,dictValue) {
	if(dictValue==null){
		return "";
	}
	 
	var name="";
	dicts.forEach(function(item, index, array) {
		 if(dictValue.toString()==item.dictValue.toString())
		 {
			 name=item.dictLabel
		 }
	});
	return name;
}
 

export function parseText(txt,len) {
	if(txt.length>len){
		var text=txt.substr(0,len)+"..."
		return text;
	}
	return txt;
	 
}

export function parseIDCardInfo(idCard) {
  // 正则表达式匹配身份证号格式
  var reg = /^\d{17}[\dXx]$/;
  
  if (reg.test(idCard)) {
    // 提取出生日期
    var birthday = idCard.substring(6, 14);
    var year = birthday.substring(0, 4);
    var month = birthday.substring(4, 6);
    var day = birthday.substring(6, 8);
    
    // 计算年龄
    var currentYear = new Date().getFullYear();
    var age = currentYear - parseInt(year);
    
    // 提取性别
    var genderCode = parseInt(idCard.charAt(16));
    var gender = genderCode % 2 === 0 ? "女" : "男";
    
    return {
      birthday: year + "-" + month + "-" + day,
      age: age,
      gender: gender
    };
  }
  
  return null; // 身份证号格式不正确
}
export function photosToArr(photoUrl) {
	 var photos=[];
	 if(photoUrl!=null&&photoUrl!=''){
		 photos=photoUrl.split(',');
	 }
	 return photos
}


export function timeFormat(timestamp) {
	var date = new Date(timestamp );//时间戳为10位需*1000，时间戳为13位的话不需乘1000
	var Y = date.getFullYear() + '-';
	var M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
	var D = date.getDate() + ' ';
	var h=(date.getHours()+1 < 10 ? '0'+(date.getHours()+1) : date.getHours()+1) + ':';
	var m=(date.getMinutes()+1 < 10 ? '0'+(date.getMinutes()+1) : date.getMinutes()+1) + ':';
	var s=(date.getSeconds()+1 < 10 ? '0'+(date.getSeconds()+1) : date.getSeconds()+1);
	return Y+M+D+h+m+"00";
}

export function dateFormat(fmt, date) {
    let ret;
    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;
}

export function getProvider(service) {
  return new Promise((resolve, reject) => {
    // 获取当前环境的服务商
    uni.getProvider({
      service: service || 'oauth',
      success: function (res) {
        // 此处可以排除h5
        if (res.provider) {
          resolve(res.provider[0])
        }
      },
      fail() {
        reject('获取环境服务商失败')
      },
    })
  }).catch(error => {
    console.log('167', error)
  })
}

export function parsePhone(mobile) {
	console.log(mobile)
	if(mobile!=null){
		var str = mobile.substr(0,3)+"****"+mobile.substr(7);
		return str;
	}
}

export function getAge(strBirthday){       
     var returnAge,
    		strBirthdayArr=strBirthday.split("-"),
     	birthYear = strBirthdayArr[0],
     	birthMonth = strBirthdayArr[1],
     	birthDay = strBirthdayArr[2],  
    	 	d = new Date(),
     	nowYear = d.getFullYear(),
     	nowMonth = d.getMonth() + 1,
     	nowDay = d.getDate();   
     if(nowYear == birthYear){
         returnAge = 0;//同年 则为0周岁
     }
     else{
         var ageDiff = nowYear - birthYear ; //年之差
         if(ageDiff > 0){
             if(nowMonth == birthMonth) {
                 var dayDiff = nowDay - birthDay;//日之差
                 if(dayDiff < 0) {
                     returnAge = ageDiff - 1;
                 }else {
                     returnAge = ageDiff;
                 }
             }else {
                 var monthDiff = nowMonth - birthMonth;//月之差
                 if(monthDiff < 0) {
                     returnAge = ageDiff - 1;
                 }
                 else {
                     returnAge = ageDiff ;
                 }
             }
         }else {
             returnAge = -1;//返回-1 表示出生日期输入错误 晚于今天
         }
     } 
     return returnAge;//返回周岁年龄
}

export function parseIdCard(idCard) {
    var str = idCard.substr(0,4)+"****"+idCard.substr(8);
    return str;
}

export function urlToObj(url) {
   let obj = {}
   let str = url.slice(url.indexOf('?') + 1)
   let arr = str.split('&')
   for (let j = arr.length, i = 0; i < j; i++) {
     let arr_temp = arr[i].split('=')
     obj[arr_temp[0]] = arr_temp[1]
   }
   return obj
}
 
export function logout() {
	uni.setStorageSync('AppToken',null);
}


export function clearHisSearch() {
 	var searchList=[];
 	uni.setStorageSync("hisSearch",JSON.stringify(searchList));
}
export function getHisSearch() {
 	var search = uni.getStorageSync('hisSearch');
 	if(search!=null&&search!=undefined&&search!=""){
 		var search=JSON.parse(search);
 		return search;
 	}
	else{
		var data=[];
		return data;
	} 
 	
 }
export function addHisSearch(searchVal) {
 	var search = uni.getStorageSync('hisSearch');
	var searchList=[];
	console.log(searchList)
	if(search!=null&&search!=undefined&&search!=""){
		searchList=JSON.parse(search);
		
	}
	searchList.push(searchVal);
	//去复
	const uniqueArr = [...new Set(searchList)];
	uni.setStorageSync("hisSearch",JSON.stringify(uniqueArr));
 }

 /**
  * 随机字符串
  * 
  */
export function generateRandomString(length) {
  let result = '';
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;
  
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }
  return result;
}
 
