import Vue from 'vue'
const FormData = require('./formData.js')

function formateDate(fmt = 'yyyy-mm-dd', date = '') {
	if (!date) {
		date = new Date()
	}

	try {
		if (typeof date == 'string') {
			date = date.replace(/-/g, '/').replace(/T/g, ' ')
			if (date.indexOf('/') == -1) {
				date = new Date(parseFloat(date))
			}
			date = new Date(date)
		} else if (typeof date == 'number') {
			date = new Date(date)
		}
	} catch (error) {
		console.log('时间格式化出错', error)
		date = new Date()
	}

	let ret
	let weak = (function (date) {
		let days = date.getDay()
		let weekArrTxt = [
			'星期天',
			'星期一',
			'星期二',
			'星期三',
			'星期四',
			'星期五',
			'星期六',
		]
		let weekArrTxt2 = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
		return [weekArrTxt[days], weekArrTxt2[days]]
	})(date)
	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(), // 秒
		// 有其他格式化字符需求可以继续添加,必须转化成字符串
		'W+': weak[0],
		'w+': weak[1],
	}
	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
}

function getDateDiff(time = new Date()) {
	if (time == '') return '未知'

	// 当前时间
	let now = new Date()
	let ny = formateDate('yyyy', now)
	let nm = formateDate('mm', now)
	let nd = formateDate('dd', now)
	let nH = formateDate('HH', now)
	let nM = formateDate('MM', now)
	let nS = formateDate('SS', now)

	let oDate = new Date(formateDate('yyyy/mm/dd HH:MM:SS', time))
	let oy = formateDate('yyyy', oDate)
	let om = formateDate('mm', oDate)
	let od = formateDate('dd', oDate)
	let oH = formateDate('HH', oDate)
	let oM = formateDate('MM', oDate)
	let oS = formateDate('SS', oDate)
	// console.log(parseInt(nm), parseInt(om));
	if ('' + ny + nm + nd + nH + nM == '' + oy + om + od + oH + oM) {
		//同分
		return '刚刚'
	} else if ('' + ny + nm + nd + nH == '' + oy + om + od + oH) {
		//同时
		return parseInt(nM) - parseInt(oM) + '分钟前'
	} else if ('' + ny + nm + nd == '' + oy + om + od) {
		//同天
		return oH + ':' + oM
	} else if ('' + ny + nm == '' + oy + om) {
		//同月
		return om + '-' + od + ' ' + oH + ':' + oM
	} else if ('' + ny == '' + oy) {
		//同年
		return om + '-' + od + ' ' + oH + ':' + oM
	} else {
		return oy + '-' + om + '-' + od
	}
}

//检测url是否合法
function TestUrl(url) {
	let regex = new RegExp(
		'(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]'
	)
	if (regex.test(url)) {
		return true
	} else {
		return false
	}
}

var ThrottleObject = new Map()
//节流器 程序名 执行函数 节流时间
function InitThrottle(name, event, time) {
	if (ThrottleObject.get(name)) clearTimeout(ThrottleObject.get(name)) //清除前程序

	//执行方法
	let obj = setTimeout(() => {
		ThrottleObject.delete(name)
		event()
	}, time)

	//存入栈
	ThrottleObject.set(name, obj)
}

//页面数据持久化工具 , app 使用  页面名称 this对象  带 async 的回调函数
async function PersistencePages(name, vdom, callback) {
	// #ifndef APP-PLUS
	callback()
	// #endif

	// #ifdef APP-PLUS
	let key = 'Persistence_' + name

	let odata = await uni.getStorageSync(key)
	let net = await getNetWork()

	if (odata && !net) {
		//取
		Object.keys(odata).forEach((item) => {
			vdom[item] = odata[item]
		})
	} else if (net) {
		//存
		//先执行页面数据获取
		await callback()

		let data = {}
		Object.keys(vdom).forEach((item) => {
			if (item.indexOf('_') == -1 && item.indexOf('$') == -1) {
				//排除原生、全局参数
				if (typeof vdom[item] != 'function') {
					//排除方法
					data[item] = vdom[item]
				}
			}
		})
		//缓存数据
		uni.setStorageSync(key, data)
	}
	// #endif
}

async function getNetWork() {
	return new Promise((res, rej) => {
		uni.getNetworkType({
			success: (re) => {
				if (re.networkType == 'none') {
					res(false)
				} else {
					res(true)
				}
			},
			fail() {
				res(false)
			},
		})
	})
}

// 文件tempUrl 转 上传参数
function tempUrlToUpload(tempUrl, fileName, other = {}) {
	let formData = new FormData()
	if (tempUrl) {
		formData.appendFile('File', tempUrl, fileName)
	}
	// 遍历增加额外参数
	Object.keys(other).forEach((key) => {
		formData.append(key, other[`${key}`])
	})
	let data = formData.getData()
	return {
		data: data.buffer,
		header: {
			'content-type': data.contentType,
		},
	}
}

// 列表追加key
function listAddKey(list) {
	console.log(list)
	return list.map((item) => {
		return {
			...item,
			key: Vue.prototype.$u.guid(),
		}
	})
}

function getColorForStr(str) {
	if (!str) {
		return '#ffffff'
	}
	// 姓名拼音首字母为基础生成背景色,过滤白色及相近色
	// 定义26个颜色
	const colors = [
		'#000000', // 黑色
		'#1C1C1C', // 深灰色
		'#333333', // 较深灰色
		'#400000', // 深红色
		'#004000', // 深绿色
		'#000040', // 深蓝色
		'#590059', // 深紫红色
		'#404000', // 深橄榄色
		'#004040', // 深青色
		'#660000', // 更深红色
		'#006600', // 更浅绿色
		'#000066', // 更深蓝色
		'#7F0000', // 极深红色
		'#007F00', // 极深绿色
		'#00007F', // 极深蓝色
		'#8B008B', // 深洋红色
		'#990000', // 非常深红色
		'#009900', // 非常深绿色
		'#000099', // 非常深蓝色
		'#A52A2A', // 褐红色
		'#00A500', // 深草绿色
		'#0000A5', // 深宝蓝色
		'#B22222', // 耐火砖色
		'#00B200', // 深翠绿色
		'#0000B2', // 深海军蓝色
		'#C71585', // 洋红色
	]
	const index = str.charCodeAt(0) % 26
	return colors[index]
}
function calculateAge(birthdate) {
	const birthdateObj = new Date(birthdate); // 将出生日期转换为 Date 对象
	const currentDate = new Date(); // 获取当前日期
	let age = currentDate.getFullYear() - birthdateObj.getFullYear(); // 计算年份差
  
	// 检查当前日期是否在出生日期的月份和日期之前
	if (currentDate.getMonth() < birthdateObj.getMonth() || 
		(currentDate.getMonth() === birthdateObj.getMonth() && currentDate.getDate() < birthdateObj.getDate())) {
	  age--; // 如果是,则岁数减 1
	}
  
	return age; // 返回计算出的岁数
  }
  function getDayName() {
	const daysOfWeek = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
	const currentDate = new Date(); // 获取当前日期
	const dayIndex = currentDate.getDay(); // 获取当前日期是星期几(0-6)
	return daysOfWeek[dayIndex]; // 返回对应的星期名称
  }
  function getPaddTopheight() {
	const systemInfo = uni.getSystemInfoSync();
        let statusBarHeight = systemInfo.statusBarHeight;
        let navBarHeight = 44;
		let paddTopheight = '';
        if (systemInfo.platform === 'ios') {
            navBarHeight = 44;
        } else if (systemInfo.platform === 'android') {
            navBarHeight = 50;
        }
        paddTopheight = navBarHeight + statusBarHeight;
		return paddTopheight || 70
}
function isArray (arr) {
    return Object.prototype.toString.call(arr) === '[object Array]';
}
function deepClone (obj) {
	// 对常见的“非”值,直接返回原来值
	if([null, undefined, NaN, false].includes(obj)) return obj;
    if(typeof obj !== "object" && typeof obj !== 'function') {
		//原始类型直接返回
        return obj;
    }
    var o = isArray(obj) ? [] : {};
    for(let i in obj) {
        if(obj.hasOwnProperty(i)){
            o[i] = typeof obj[i] === "object" ? deepClone(obj[i]) : obj[i];
        }
    }
    return o;
}

const util = {
	formateDate,
	PersistencePages,
	getNetWork,
	getDateDiff,
	TestUrl,
	tempUrlToUpload,
	listAddKey,
	getColorForStr,
	calculateAge,
	getDayName,
	getPaddTopheight,
	deepClone
}

export default util