import {checkLogin} from '@/api/user'
import dayjs from 'dayjs'
var isEmpty =function(obj) {
	if (typeof obj == "undefined" || obj == null || obj == "") {
		return true;
	} else {
		return false;
	}
}
 
var checkToken= function() {
	var token = uni.getStorageSync('AppToken');
	if (token==null||token==undefined||token=="" ) {
		return false;
	} 
	return true;
}


var isLogin=  function() {
	return new Promise((resolve, reject) => {
		checkLogin().then(
			res => {
				if(res.code==200){
					resolve(true);
				}else{
					resolve(false);
				}
			},
			rej => { }
		);
	});
	 
}

var loginOut= function() {
	  uni.setStorageSync('AppToken',null);
	  uni.setStorageSync('userInfo',null);
}
var checkLoginState= function() {
	var token = uni.getStorageSync('AppToken');
	if (token ) {
		return true
	} else {
		return false
	}
}

var getDictLabelName= function(key,dictValue) {
	if(dictValue==null){
		return "";
	}
	var dicts = uni.getStorageSync('dicts');
	dicts=JSON.parse(dicts);
	var dict=dicts[key]
	var name="";
	dict.forEach(function(item, index, array) {
		 if(dictValue.toString()==item.dictValue.toString())
		 {
			 name=item.dictLabel
		 }
	});
	return name;
}
var getDict= function(key) {
	var dicts = uni.getStorageSync('dicts');
	dicts=JSON.parse(dicts);
	var dict=dicts[key]
	return dict;
}

var subString=function(str){
	if (str.length > 4) {
	   return str.slice(0, 4)+"...";
	}
	console.log("qxj subString:"+str);
	return str;
}


var photosToArr= function(photoUrl) {
	 var photos=[];
	 if(photoUrl!=null&&photoUrl!=''){
		 photos=photoUrl.split(',');
	 }
	 return photos
}

var dateFormat=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;
}

var 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)
  })
}
 
 var handleTree=function handleTree(data, id, parentId, rootId) {
 	id = id || 'id'
 	parentId = parentId || 'parentId'
 	rootId = rootId || Math.min.apply(Math, data.map(item => { return item[parentId] })) || 0
 	//对源数据深度克隆
 	const cloneData = JSON.parse(JSON.stringify(data))
 	//循环所有项
 	const treeData = cloneData.filter(father => {
 		let branchArr = cloneData.filter(child => {
 			//返回每一项的子级数组
 			return father[id] === child[parentId]
 		});
 		branchArr.length > 0 ? father.child = branchArr : '';
 		//返回第一层
 		return father[parentId] === rootId;
 	});
 	return treeData != '' ? treeData : data;
 }
var parsePhone=function parsePhone(mobile) {
    var str = mobile.substr(0,3)+"****"+mobile.substr(7);
    return str;
}
var parseIdCard=function parseIdCard(idCard) {
    var str = idCard.substr(0,4)+"****"+idCard.substr(8);
    return str;
}
 
//格式为"1990-01-01"
var getAge=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;//返回周岁年龄
}

var clearHisSearch= function() {
 	var searchList=[];
 	uni.setStorageSync("hisSearch",JSON.stringify(searchList));
 }
 var getHisSearch= function() {
 	var search = uni.getStorageSync('hisSearch');
 	if(search!=null&&search!=undefined&&search!=""){
 		var search=JSON.parse(search);
 		return search;
 	}
	else{
		var data=[];
		return data;
	} 
 	
 }
 var addHisSearch= function(searchVal) {
 	var search = uni.getStorageSync('hisSearch');
	var 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));
 }


var parseTime= function(num){//时间戳数据处理
         let date = new Date(num*1000);
        //时间戳为10位需*1000，时间戳为13位的话不需乘1000
        let y = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? ('0' + MM) : MM;//月补0
        let d = date.getDate();
        d = d < 10 ? ('0' + d) : d;//天补0
        let h = date.getHours();
        h = h < 10 ? ('0' + h) : h;//小时补0
        let m = date.getMinutes();
        m = m < 10 ? ('0' + m) : m;//分钟补0
        let s = date.getSeconds();
        s = s < 10 ? ('0' + s) : s;//秒补0
        return y + '-' + MM + '-' + d + ' ' + h + ':' + m+ ':' + s;

}   
// var setData= function(obj){
// 	 let that = this;
// 	 let keys = [];
// 	 let val,data;
// 	 Object.keys(obj).forEach(function(key){
// 		 keys = key.split('.');
// 		 val = obj[key];
// 		 data = that.$data;
// 		 keys.forEach(function(key2,index){
// 			 if(index+1 == keys.length){
// 				 that.$set(data,key2,val);
// 			 }else{
// 				 if(!data[key2]){
// 					 that.$set(data,key2,{});
// 				 }
// 			 }
// 			 data = data[key2];
// 		 })
// 	 });
//  }
var setData= function(obj){
	let that = this;
	const handleData = (tepData, tepKey, afterKey) => {
		var tepData2 = tepData;
		tepKey = tepKey.split('.');
		tepKey.forEach(item => {
			if (tepData[item] === null || tepData[item] === undefined) {
				let reg = /^[0-9]+$/;
				tepData[item] = reg.test(afterKey) ? [] : {};
				tepData2 = tepData[item];
			} else {
				tepData2 = tepData[item];
			}
		});
		return tepData2;
	};
	const isFn = function(value) {
		return typeof value == 'function' || false;
	};
	Object.keys(obj).forEach(function(key) {
		let val = obj[key];
		key = key.replace(/\]/g, '').replace(/\[/g, '.');
		let front, after;
		let index_after = key.lastIndexOf('.');
		if (index_after != -1) {
			after = key.slice(index_after + 1);
			front = handleData(that, key.slice(0, index_after), after);
		} else {
			after = key;
			front = that;
		}
		if (front.$data && front.$data[after] === undefined) {
			Object.defineProperty(front, after, {
				get() {
					return front.$data[after];
				},
				set(newValue) {
					front.$data[after] = newValue;
					that.hasOwnProperty("$forceUpdate") && that.$forceUpdate();
				},
				enumerable: true,
				configurable: true
			});
			front[after] = val;
		} else {
			that.$set(front, after, val);
		}
	});

}
 const urlToObj = function(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
 }
 var checkCompanyUserLoginState= function() {
 	var token = uni.getStorageSync('CompanyUserToken');
 	if (token ) {
 		return true
 	} else {
 		return false
 	}
 }
 

/**
 * 格式化时间
 * @param {Object} 时间字符串
 */
var formatDate=function(dateStr) {

	let date = dayjs(dateStr,'YYYY-MM-DD HH:mm:ss');
	let today = dayjs();

	let formatStr = "";
	if (date.year() != today.year()) {
		formatDate = date.format('YYYY-MM-DD HH:mm');
	} 
	else if (date.month() === today.month()) {
		switch (date.date() - today.date()) {
			case 0:
				formatDate = date.format('今天 HH:mm');
				break;
			case -1:
				formatDate = date.format('昨天 HH:mm');
				break;
			case 1:
				formatDate = date.format('明天 HH:mm');
				break;
			default:
				formatDate = date.format('MM-DD HH:mm');
				break;
		}
	} 
	else if (date.month() - today.month() === 0 && date.date() === 1) {
		formatDate = date.format('明天 HH:mm');
	} 
	else {
		formatDate = date.format('MM-DD HH:mm');
	}
	return formatDate;
}
/**
 * 随机字符串
 * 
 */
var generateRandomString=function(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;
}
var isLoginCourse=function(){
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('TOKEN_WEXIN');
		if (token==null||token==undefined||token=="" ) {
			resolve(false);
		} else {
			resolve(true);
		}
	}); 
}

module.exports = {
		isLoginCourse:isLoginCourse,
		generateRandomString:generateRandomString,
		formatDate:formatDate,
        isEmpty : isEmpty,
		checkLoginState : checkLoginState,
		getDictLabelName:getDictLabelName,
		photosToArr:photosToArr,
		dateFormat:dateFormat,
		getProvider:getProvider,
		isLogin:isLogin,
		checkToken:checkToken,
		loginOut:loginOut,
		handleTree:handleTree,
		parsePhone:parsePhone,
		getAge:getAge,
		parseIdCard:parseIdCard,
		getDict:getDict,
		addHisSearch:addHisSearch,
		clearHisSearch:clearHisSearch,
		getHisSearch:getHisSearch,
		parseTime:parseTime,
		setData:setData,
		urlToObj:urlToObj,
		subString:subString,
		checkCompanyUserLoginState:checkCompanyUserLoginState
		
		
};