/**
 * 
 * @author maxd
 * @date 2019.8.1
 */
import configdata from './config'
module.exports = {
	//微信的appId
	getWxAppid() {
		return 'wxd0bec3a917085e78'
	},
	//全局邀请码
	getInvitation() {
		return uni.getStorageSync("publicRelation")
	},
	//获取APP下载地址
	getAppDownUrl() {
		return uni.getStorageSync("appurl")
	},
	//全局域名 部分html中需要单独替换 需要修改config中的网络请求域名
	publicYuMing() {
		return configdata.h5Url
	},
	logout() {
		this.remove("token");
		this.remove("userId");
		this.remove("mobile");
		this.remove("openid");
		this.remove("nickName");
		this.remove("relation");
		this.remove("image_url");
		this.remove("relation_id");
		this.remove("isInvitation");
		this.remove("member");
	},
	loginClear() {
		this.remove("token");
		this.remove("userId");
		this.remove("mobile");
		this.remove("nickName");
		this.remove("image_url");
		this.remove("relation_id");
		this.remove("isInvitation");
		this.remove("member");
	},
	showLoading(title) {
		uni.showLoading({
			title: title
		});
	},
	showToast(title) {
		uni.showToast({
			title: title,
			mask: false,
			duration: 2000,
			icon: "none"
		});
	},
	getChatSearchKeys: function(key) {
		let list = uni.getStorageSync("chatSearchKeys");
		let keys = key.replace(/\s*/g, "")
		let over = false
		for (var i = 0; i < keys.length; i++) {
			// console.error(keys[i])
			if (list.indexOf(keys[i]) != -1) {
				over = true;
				// return over;
			}

		}
		return over;

	},
	setJson: function(key, value) {
		let jsonString = JSON.stringify(value);
		try {
			uni.setStorageSync(key, jsonString);
		} catch (e) {
			// error
		}
	},
	setData: function(key, value) {
		try {
			uni.setStorageSync(key, value);
		} catch (e) {
			// error
		}
	},
	getData: function(key) {
		try {
			const value = uni.getStorageSync(key);
			if (value) {
				return value;
			}
		} catch (e) {
			// error
		}

	},
	getJson: function(key) {
		try {
			const value = uni.getStorageSync(key);
			if (value) {
				return JSON.parse(value);
			}
		} catch (e) {
			// error
		}

	},
	clear: function() {
		uni.clearStorage();
	},
	get: function(key) { //获取队列里面全部的数据
		let data = this.getJson(key);
		if (data instanceof Array) {
			return data;
		}
		return [];
	},
	insert: function(param) { //队列插入数据
		param.capacityNum = param.capacityNum || 100; //队列容量 默认队列中超过100条数据，自动删除尾部
		let data = this.getJson(param.key);
		if (data instanceof Array) {
			if (data.length > param.capacityNum) {
				let total = data.length - param.capacityNum;
				for (let i = 0; i < total; i++) {
					data.pop();
				}
			}
			data.unshift(param.value);
		} else {
			data = [];
			data.push(param.value);
		}
		this.setJson(param.key, data);
	},
	removeItem: function(key, itemIds) { //提供itemIds数组 批量删除队列中的某项数据
		let data = this.getJson(key);
		if (data instanceof Array) {
			for (let i = 0; i < itemIds.length; i++) {
				for (let p = 0; p < data.length; p++) {
					if (itemIds[i] === data[p].itemid) {
						data.splice(p, 1);
						break;
					}
				}
			}
			this.setJson(key, data);
		}
	},
	isExist: function(key, itemId) { //检测某条数据在队列中是否存在
		let data = this.getJson(key);
		if (data instanceof Array) {
			for (let p = 0; p < data.length; p++) {
				if (itemId === data[p].itemid) {
					return true;
				}
			}
		}
		return false;
	},
	isExistPdd: function(key, itemId) { //检测某条数据在队列中是否存在
		let data = this.getJson(key);
		if (data instanceof Array) {
			for (let p = 0; p < data.length; p++) {
				if (itemId === data[p].goodsId) {
					return true;
				}
			}
		}
		return false;
	},
	isExistJd: function(key, itemId) { //检测某条数据在队列中是否存在
		let data = this.getJson(key);
		if (data instanceof Array) {
			for (let p = 0; p < data.length; p++) {
				if (itemId === data[p].skuId) {
					return true;
				}
			}
		}
		return false;
	},
	remove: function(key) { //删除某条队列
		try {
			uni.removeStorageSync(key);
			//localStorage.removeItem(key)
		} catch (e) {
			// error
		}
	},
	getCount: function(key) { //获取队列中全部数据数量

		let data = this.getJson(key);
		if (data instanceof Array) {
			return data.length;
		}
		return 0;
	},
	uploadFile:function(path,callback){
		const uploadTask=uni.uploadFile({ // 上传接口
			url: configdata.APIHOST1 + '/alioss/upload', //真实的接口地址
			filePath: path,
			name: 'file',
			success: (uploadFileRes) => {
				let content = JSON.parse(uploadFileRes.data).data;
				uni.hideLoading();
				callback(content)
			},fail:(err)=>{
				callback(false)
				console.log(err)
			}
		});
		uploadTask.onProgressUpdate((res) => {
		  uni.showLoading({
		    title: '上传进度' + res.progress+'%',
		  })
		  if(res.progress>=100){
			  uni.hideLoading()
		  }
		})
	},
	array_column:function (arr, column_key, index_key = null) {
	    if (index_key === null) {
	        return arr.map(item => item[column_key]);
	    }
	    
	    return arr.reduce((result, item) => {
	        result[item[index_key]] = item[column_key];
	        return result;
	    }, {});
	},
	isCurrentMonth:function (date) {
	  const now = new Date();
	  return now.getFullYear() === date.getFullYear() && 
	         now.getMonth() === date.getMonth();
	},
	getHighestEducation:function (educations) {
	  // 定义学历等级映射（从低到高）
	  const educationLevels = {
	    '小学': 1,
	    '初中': 2,
	    '高中': 3,
	    '中专': 4,
	    '大专': 5,
	    '本科': 6,
	    '硕士': 7,
	    '博士': 8,
	    '博士后': 9
	  };
	
	  let highestEducation = null;
	  let highestLevel = -1;
	
	  educations.forEach(edu => {
	    const level = educationLevels[edu.degree] || 0;
	    if (level > highestLevel) {
	      highestLevel = level;
	      highestEducation = edu.degree;
	    }
	  });
	
	  return highestEducation;
	},
	
	//职业状态
	resumesStatus(){
		
		return [{
				value: '0',
				text: '离职-随时到岗',
				recommended: true
			},
			{
				value: '1',
				text: '在职-月内到岗',
				recommended: true
			},
			{
				value: '2',
				text: '在职-考虑机会',
				recommended: false
			},
			{
				value: '3',
				text: '在职-暂不考虑',
				recommended: false
			}
		]
	},
	
	appConfirm:function(content='请确认您的操作？',callback,title='操作提示',button=["继续","取消"]){
		// #ifndef APP-PLUS 
		uni.showModal({
			title: title,
			content: content,
			success: function(res) {
				if (res.confirm) {
					callback(true)
				}else
					callback(false)
			}
		});
		return
		//#endif
		// #ifdef APP-PLUS 
		plus.nativeUI.confirm(content, function(e){
				if(e.index==0)
					callback(true)
				else
					callback(false)
			},title,button);
		//#endif
	},
	isDateExpired:function (targetDate) {
	    const currentTimestamp = new Date().getTime();
	    const targetTimestamp = new Date(targetDate).getTime();
		const rest=targetTimestamp < currentTimestamp
		if(rest)
			return [true,0]
		    // 计算毫秒差
		const diffInMs =  targetTimestamp -currentTimestamp; 
		    
		    // 转换为小时（向上取整确保显示完整小时）
		const hours = Math.ceil(diffInMs / (1000 * 60 * 60));  
		    
		return [rest,hours > 0 ? hours : 0];  // 返回非负值
	},
	convert12to24:function (time12h) {
	  // 使用正则表达式匹配12小时制格式
	  const regex = /^(0?[1-9]|1[0-2]):([0-5]\d)\s?(AM|PM)$/i;
	  const match = time12h.match(regex);
	  
	  if (!match) {
	    throw new Error('无效的时间格式，请使用如 "2:00 PM" 或 "02:00 PM" 的格式');
	  }
	  
	  let hour = parseInt(match[1], 10);
	  const minute = match[2];
	  const period = match[3].toUpperCase();
	  
	  // 处理AM/PM转换逻辑
	  if (period === 'PM' && hour !== 12) {
	    hour += 12;
	  } else if (period === 'AM' && hour === 12) {
	    hour = 0;
	  }
	  
	  // 格式化为两位数
	  const hour24 = hour.toString().padStart(2, '0');
	  
	  return `${hour24}:${minute}`;
	},
	changeTabbar:function(res){
		setTimeout(() => {
			if(res==1){
			uni.setTabBarItem({
			  index: 0,
			  text: '首页',
			 iconPath: "/static/tabbar/Home.png",
			 selectedIconPath: "/static/tabbar/Iconly_Bold_Home.png",
			})
			uni.setTabBarItem({
			  index: 1,
			  text: '急聘',
			  "pagePath": "/pages/index/game/gameList",
			  "iconPath": "/static/tabbar/jipin.png",
			  "selectedIconPath": "/static/tabbar/ACjipin.png",
			})
			}else{
				uni.setTabBarItem({
				  index: 0,
				  text: '牛人',
				 iconPath: "/static/tabbar/niu.png",
				 selectedIconPath: "/static/tabbar/niu2.png",
				})
				uni.setTabBarItem({
				  index: 1,
				  "pagePath": "/pages/talentSearch/index",
				   	"iconPath": "/static/tabbar/Hrsearch.png",
				   	"selectedIconPath": "/static/tabbar/ACsearch.png",
				   	"text": "搜索"
				})
			}
		    // 可以在这里添加 tabbar 更新后的后续操作
		    console.log('tabbar 更新完成');
		  },100);
	},
};
