import store from '../store/store.js'
import request from '@/util/index.js'

// const QQMapWX = require('./qqmap-wx-jssdk.min.js')
// const qqmapsdk = new QQMapWX({
//   key: "SVKBZ-P6QCJ-NH7F7-KOPJW-CBNEV-FUBRT"
// })
// /**
//  * 地图两点之间的距离
//  * @doc 文档参考：https://lbs.qq.com/qqmap_wx_jssdk/method-search.html
//  * @export
//  * @param {*} to 坐标 { latitude: 39.984060, longitude: 116.307520 }
//  * @param {*} location 坐标：{ latitude: 39.984060, longitude: 116.307520 }
//  * @returns
//  */
//  function calculateDistance (fromp, to) {

//   return new Promise((resolve, reject) => {
//     qqmapsdk.calculateDistance({
// 		mode: 'straight',
// 		to: [{
// 			latitude: to.latitude,
// 			longitude: to.longitude
// 		}],
// 		'from': {
// 			latitude: fromp.latitude,
// 			longitude: fromp.longitude
// 		},
//       success: res => {
//         resolve(res)
//       },
//       fail: err => {
//         reject(err)
//         uni.showToast({
//           title: err.message,
//           icon: 'none',
//           duration: 3000
//         })
//       }
//     })
//   })
// }

// /**
// * 坐标转换，百度地图坐标转换成腾讯地图坐标
// * lng 腾讯经度（pointy）
// * lat 腾讯纬度（pointx）
// * 经度>纬度
// */
// function bMapToQQMap(lng, lat) {

//     if (lng == null || lng == '' || lat == null || lat == '')
//         return [lng, lat];

//     var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
//     var x = parseFloat(lng) - 0.0065;
//     var y = parseFloat(lat) - 0.006;
//     var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
//     var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
//     var lng = (z * Math.cos(theta)); //.toFixed(7);
//     var lat = (z * Math.sin(theta)); //.toFixed(7);

//     return [lng, lat];

// }

const netChange = () => {
	uni.onNetworkStatusChange(function (res) {
		// console.log(res.isConnected)
		store.mutations.isConnect(res.isConnected)
		if (!res.isConnected) {
			uni.showToast({
				title: '网络未连接',
				icon: 'none'
			})
		}
	})
}
const cutDate = (dd, type, daynum) => {
	dd = new Date(dd) || new Date();
	type = type || 'YYYY/MM/DD' //hh:mm:ss
	daynum = daynum * 24 * 60 * 60 * 1000 || 0
	// console.log(daynum,dd,dd.getTime()+daynum)
	dd = new Date(dd.getTime() + daynum) // 获取AddDayCount天后的日期
	var y = dd.getFullYear()
	var m = (dd.getMonth() + 1) < 10 ? '0' + (dd.getMonth() + 1) : (dd.getMonth() + 1) // 获取当前月份的日期，不足10补0
	var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号，不足10补0
	var h = dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()
	var mi = dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()
	var s = dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds()
	return type.replace('YYYY', y).replace('MM', m).replace('DD', d).replace('hh', h).replace('mm', mi).replace('ss', s)
}
// 四舍五入的保留两位小数的 金额化数字方法
const fmoney = (s, n) => {
	/*
	 * 参数说明：
	 * s：要格式化的数字
	 * n：保留几位小数
	 * */
	n = n > 0 && n <= 20 ? n : 2;
	var fuhao = ''; //如果数字小于零则值为-
	if (s < 0) {
		s = Math.abs(s);
		fuhao = '-'
	}
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
	var l = s.split(".")[0].split("").reverse(),
		r = s.split(".")[1];
	let t = "";
	for (let i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	if (n === 0) {
		return s
	} else {
		return fuhao + [...t].reverse().join("") + "." + r;
	}
}


// 四舍五入不保留小数的 金额化数字方法
function noDecimal(s) {
	console.log('s', s)
	let fuhao = ''; //如果数字小于零则值为-
	if (s < 0) {
		s = Math.abs(s);
		fuhao = '-'
	}
	s = parseFloat((s + "").replace(/[^\d\.-]/g, "")) + ""
	let l = s.split(".")[0].split("").reverse(),
		r = s.split(".")[1];
	let t = ''
	for (let i = 0; i < l.length; i++) {
		t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
	}
	return fuhao + [...t].reverse().join("")

}

/**
 * 将数据转成日期格式
 * @param {string} s: 要格式化的日期数据
 */
function changeStringToDate(s) {
	if (s.length === 14) {
		return s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8) + ' ' +
			s.substring(8, 10) + ':' + s.substring(10, 12) + ':' + s.substring(12, 14);
	} else if (s.length === 8) {
		return s.substring(0, 4) + '-' + s.substring(4, 6) + '-' + s.substring(6, 8);
	}
}

function toNextRoute(type, url) {
	uni[type]({
		url: url,
		success: (result) => {

			addUserBehavior({
				intoRoute: url
			})
		}
	})
}

function formatNumber(num) {
	// 先保留两位小数，不四舍五入
	num = Math.floor(num * 100) / 100;

	// 添加千分号
	let [integer, decimal] = num.toString().split('.');
	integer = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ','); // 千分号格式化

	return decimal ? `${integer}.${decimal}` : integer; // 如果有小数部分则保留
}

// 记录用户行为的方法 每个页面的onUnload里面要调用
function addUserBehavior(obj) {

	var pages = getCurrentPages() // 获取加载的页面
	let len = pages.length
	if (len) {
		var currentPage = pages[len - 1] // 获取当前页面的对象
		var nowRoute = '/' + currentPage.route // 当前页面url
		if (obj) {
			obj.outtoRoute = (obj.outtoRoute === '' || obj.outtoRoute) ? obj.outtoRoute : nowRoute
			obj.intoRoute = obj.intoRoute ? obj.intoRoute.split('?')[0] : ''
		} else {
			obj = {}
			obj.outtoRoute = nowRoute
			obj.intoRoute = len > 1 ? '/' + pages[len - 2].route : '/pages/index/index'
		}
	}
	obj.visitChannels = store.state.visitChannels
	let userDate = store.state.userData

	let baseInfo = uni.getStorageSync('userInfo')

	let req = {
		userName: userDate.UserName,
		phoneNumber: userDate.Membership_Phone,
		userId: userDate.UserId ? userDate.UserId : '',
		wechatAppId: 'wx6e28691bea93c6ec',
		intoRoute: obj.intoRoute,
		outtoRoute: obj.outtoRoute,
		visitChannels: obj.visitChannels,
		behaviorRecordDesc: '',
		LoginIP: baseInfo.ip || '',
		LoginPlace: (baseInfo.prov ? baseInfo.prov : '') + (baseInfo.prov && baseInfo.city ? '-' : '') + (baseInfo.city ? baseInfo.city : ''),
		SOURCE_PLATFORM: '数智化看板'
	}
	request.$webGet('CommercialApi/UserBehavior/AddUserBehavior', req).then(() => {

	})
}

function addUserBehaviorNew(obj) {

	var pages = getCurrentPages() // 获取加载的页面
	let len = pages.length
	if (len) {
		var currentPage = pages[len - 1] // 获取当前页面的对象
		var nowRoute = '/' + currentPage.route // 当前页面url
		if (obj) {
			obj.outtoRoute = (obj.outtoRoute === '' || obj.outtoRoute) ? obj.outtoRoute : nowRoute
			obj.intoRoute = obj.intoRoute ? obj.intoRoute.split('?')[0] : ''
		} else {
			obj = {}
			obj.outtoRoute = nowRoute
			obj.intoRoute = len > 1 ? '/' + pages[len - 2].route : '/pages/index/index'
		}
	}
	obj.visitChannels = store.state.visitChannels
	let userDate = store.state.userData
	let req = {
		userName: userDate.UserName,
		phoneNumber: userDate.Membership_Phone,
		userId: userDate.UserId ? userDate.UserId : '',
		wechatAppId: 'wx6e28691bea93c6ec',
		intoRoute: obj.intoRoute,
		outtoRoute: obj.outtoRoute,
		visitChannels: obj.visitChannels,
		behaviorRecordDesc: ''
	}
	request.$webGet('CommercialApi/UserBehavior/AddUserBehavior', req).then(() => {

	})
}
/*
	根据关键字获取相应的枚举选项，文档见 https://eshangtech.com:18900/EShangApiMain/swagger/ui/index#!/FrameWork/FrameWork_GetFieldEnumByField
	params:{FieldExplainField,FieldEnumStatus}
 */
async function getFieldEnumByField(params) {
	if (!params.FieldExplainField) return null
	// 缓存了上次请求的数据 如果字段一致 则直接返回缓存数据 否则请求
	// 可优化：根据有效期判断是否再次请求
	if (!this.dataMap) {
		this.dataMap = {}
	}
	if (this.dataMap[params.FieldExplainField]) {
		return this.dataMap[params.FieldExplainField]
	}
	const data = await request.$webGet('EShangApiMain/FrameWork/GetFieldEnumByField', params)
	if (data.Result_Code == 100) {
		let typeMap = {}
		data.Result_Data.List.map(n => {
			typeMap[n.value] = n.label
		})
		this.dataMap[params.FieldExplainField] = typeMap
		return typeMap
	}

}


// 得到这个月有多少天
function getThisMonthDay(value) {
	let date = new Date(value)
	let y = date.getFullYear()
	let m = date.getMonth() + 1
	let howDay;
	let flag = false
	if (y % 4 === 0 && y % 100 !== 0 || y % 400 === 0) {
		flag = true
	}
	switch (m) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			howDay = 31
			break
		case 4:
		case 6:
		case 9:
		case 11:
			howDay = 30
			break
		case 2:
			if (flag) {
				howDay = 29
			} else {
				howDay = 28
			}
			break
	}
	return howDay
}

// 输入时间拿到月份
function getThisMonth(value) {
	const date = new Date(value)
	let y = date.getFullYear()
	let m = date.getMonth() + 1
	if (m < 10) {
		m = '0' + m
	}
	return `${y}${m}`
}
// 输入时间得到带-的月份
function getThisMonthHaveHeng(value) {
	const date = new Date(value)
	let y = date.getFullYear()
	let m = date.getMonth() + 1
	if (m < 10) {
		m = '0' + m
	}
	return `${y}-${m}`
}
//有横杠
function getThisMonthHave(value) {
	const date = new Date(value)
	let y = date.getFullYear()
	let m = date.getMonth() + 1
	if (m < 10) {
		m = '0' + m
	}
	return `${y}-${m}`
}

// 显示月日
function handleGetMonthDay(value) {
	const date = new Date(value)
	let m = date.getMonth() + 1
	if (m < 10) {
		m = '0' + m
	}
	let d = date.getDate()
	if (d < 10) {
		d = '0' + d
	}
	return `${m}-${d}`
}

// 输入时间拿到月份 输出月份的字符串
function getThisTimeMonth(value) {
	const date = new Date(value)
	let m = date.getMonth() + 1
	if (m < 10) {
		m = '0' + m
	}
	return `${m}`
}

// 视频播放
const EZUIPlayer = require('./ezuikit.js');

function playVideo(opt) {

	return new EZUIPlayer(opt)
}

// 输入年份和月份 输出该月的天数 是一个数组 格式为 *月**日
function getThisMonthDateList(value) {
	let date = new Date(value)
	let y = date.getFullYear()
	let m = date.getMonth() + 1
	let howDay;
	let flag = false
	if (y % 4 === 0 && y % 100 !== 0 || y % 400 === 0) {
		flag = true
	}
	switch (m) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			howDay = 31
			break
		case 4:
		case 6:
		case 9:
		case 11:
			howDay = 30
			break
		case 2:
			if (flag) {
				howDay = 29
			} else {
				howDay = 28
			}
			break
	}
	let list = []
	for (let i = 0; i <= howDay, ++i;) {
		if (i > howDay) {
			break
		} else {
			list.push({
				label: `${m}月${i}日`,
				value: `${y}-${m < 10 ? '0' + m : m}-${i < 10 ? '0' + i : i}`
			})
		}
	}
	return list
}
// 传入 老的时间和要变成的时间 老时间要日期 新时间不用  月份为1无效
function handleReduceAMonth(nowTime, newTime) {
	const oldDate = new Date(nowTime)
	let y = oldDate.getFullYear()
	let m = oldDate.getMonth() + 1
	let d = oldDate.getDate()

	const newDate = new Date(newTime)
	let newY = newDate.getFullYear()
	let newM = newDate.getMonth() + 1
	let thisMonth = newM < 10 ? '0' + newM : newM

	let howDay = this.getThisMonthDay(`${y}-${m}`)
	let newHowDay = this.getThisMonthDay(`${newY}-${thisMonth}`)
	const nowDate = new Date()
	let nowM = nowDate.getMonth() + 1
	let nowD = nowDate.getDate()


	if (d === newHowDay) {
		if (d < nowD) {
			if (newM < 10) {
				newM = '0' + newM
			}
			if (newHowDay < 10) {
				newHowDay = '0' + newHowDay
			}
			return `${newY}-${newM}-${newHowDay}`
		} else {
			if (newM === nowM) {
				if (newM < 10) {
					newM = '0' + newM
				}
				if (nowD < 10) {
					nowD = '0' + nowD
				}
				return `${newY}-${newM}-${nowD}`
			} else {
				if (newM < 10) {
					newM = '0' + newM
				}
				if (newHowDay < 10) {
					newHowDay = '0' + newHowDay
				}
				return `${newY}-${newM}-${newHowDay}`
			}
		}
	} else {
		if (newM === 2) {
			if (d > newHowDay) {
				if (newM < 10) {
					newM = '0' + newM
				}
				if (newHowDay < 10) {
					newHowDay = '0' + newHowDay
				}
				return `${newY}-${newM}-${newHowDay}`
			} else {
				if (newM < 10) {
					newM = '0' + newM
				}
				if (d < 10) {
					d = '0' + d
				}
				return `${newY}-${newM}-${d}`
			}
		} else {
			if (nowD < d) {
				if (nowM === newM) {
					if (newM < 10) {
						newM = '0' + newM
					}
					if (nowD < 10) {
						nowD = '0' + nowD
					}
					return `${newY}-${newM}-${nowD}`
				} else {
					if (d < newHowDay) {
						if (newM < 10) {
							newM = '0' + newM
						}
						if (d < 10) {
							d = '0' + d
						}
						return `${newY}-${newM}-${d}`
					} else {
						if (newM < 10) {
							newM = '0' + newM
						}
						if (newHowDay < 10) {
							newHowDay = '0' + newHowDay
						}
						return `${newY}-${newM}-${newHowDay}`
					}

				}
			} else {
				if (newM < 10) {
					newM = '0' + newM
				}
				if (d < 10) {
					d = '0' + d
				}
				return `${newY}-${newM}-${d}`
			}
		}
	}
}
// 不四舍五入 保留两位小数的金额化方法
function getMoney(money) {
	if (!money || isNaN(money)) return "0.00";
	let num = parseFloat(money + '') + '';
	num = parseInt(money * 100 + '') / 100 + ''

	let reg = /(-?\d+)(\d{3})/;
	while (reg.test(num)) {
		num = num.replace(reg, "$1,$2");
	}

	let idx = num.indexOf('.')
	if (idx === -1) {
		num = num + '.00'
	}

	if (idx > 0) {
		let num_per = num.substring(0, idx) + '.'
		let num_next = num.substring(idx + 1).padEnd(2, '0')
		num = num_per + num_next
	}

	return num;
}
// 不四舍五入 不保留两位小数的金额化方法
function getMoneyNoDecimal(money) {
	if (!money || isNaN(money)) return "0";
	let num = parseFloat(money + '') + '';
	num = parseInt(money * 100 + '') / 100 + ''
	let reg = /(-?\d+)(\d{3})/;
	while (reg.test(num)) {
		num = num.replace(reg, "$1,$2");
	}
	let idx = num.indexOf('.')
	if (idx === -1) {
		num = num
	}
	if (idx > 0) {
		let num_per = num.substring(0, idx)
		let num_next = num.substring(idx + 1)
		num = num_per
	}
	return num;
}
// 封装的排序数组的方法
// list 为排序的数组   field 为按照那个字段排序  type 正序还是倒序 1正 2倒
const handleGetSortList = (list, field, type) => {
	if (list && list.length > 0) {
		let len = list.length
		if (type === 2) {
			for (var i = 0; i < len - 1; i++) {
				for (var j = 0; j < len - 1 - i; j++) {
					if (list[i][field] < list[j][field]) {
						var temp = list[j];
						list[j] = list[j + 1];
						list[j + 1] = temp;
					}
				}
			}
		} else {
			for (var i = 0; i < len - 1; i++) {
				for (var j = 0; j < len - 1 - i; j++) {
					if (list[i][field] > list[j][field]) {
						var temp = list[j];
						list[j] = list[j + 1];
						list[j + 1] = temp;
					}
				}
			}
		}
	}
	return list
}


// 计算两个时间之间有多少个月份
function getMonthDiff(startDate, endDate) {
	const start = new Date(startDate);
	const end = new Date(endDate);

	// 计算总月数差
	let months = (end.getFullYear() - start.getFullYear()) * 12 + (end.getMonth() - start.getMonth());

	// 如果结束日小于开始日，则少算一个月
	if (end.getDate() < start.getDate()) {
		months--;
	}

	return months;
}

// 在开始时间上 累加月份
function generateMonthList(startDate, monthCount) {
	const result = [];
	const start = new Date(startDate);

	for (let i = 0; i < monthCount; i++) {
		// 复制时间，避免直接修改 start
		const date = new Date(start);
		date.setMonth(start.getMonth() + i);

		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, '0');

		result.push({
			full: `${year}-${month}`, // YYYY-MM
			realFull: `${year}${month}`, // YYYY-MM
			month: Number(month)              // MM
		});
	}

	return result;
}



export default {
	netChange,
	cutDate,
	getThisMonthDay,
	getThisMonth,
	getThisMonthHaveHeng,
	getThisMonthHave,
	getThisTimeMonth,
	handleGetMonthDay,
	fmoney,
	formatNumber,
	noDecimal,
	changeStringToDate,
	toNextRoute,
	addUserBehavior,
	addUserBehaviorNew,
	getFieldEnumByField, // 获取枚举参数
	// calculateDistance,
	// bMapToQQMap,
	playVideo,
	getMoney,
	handleGetSortList,
	getMoneyNoDecimal,
	getThisMonthDateList,
	handleReduceAMonth,
	getMonthDiff,
	generateMonthList
}