import axios from 'axios';
import router from "../router";
import {
	Toast
} from "vant";

import {
	baseUrl2
} from './request';
// 转换时间格式
export function timeValidate(date, type) {
	const time = date ? new Date(date) : new Date()
	const yyyy = time.getFullYear()
	const MM = (time.getMonth() + 1).toString().padStart(2, 0)
	const dd = time.getDate().toString().padStart(2, '0')
	const hh = time.getHours().toString().padStart(2, '0')
	const mm = time.getMinutes().toString().padStart(2, '0')
	const ss = time.getSeconds().toString().padStart(2, '0')
	if (type == 'ymd') {
		return `${yyyy}-${MM}-${dd}`;
	}
	if (type == 'md') {
		return `${MM}.${dd}`
	}
	return `${yyyy}-${MM}-${dd} ${hh}:${mm}:${ss}`
}


// 获取当前近多少天  7后7天  -7 前五天
export function getRecentDay(n, type) {
	var currentDate = new Date();
	var preDate = new Date(currentDate.getTime() + n * 24 * 3600 * 1000)
	let year = preDate.getFullYear()
	let mon = preDate.getMonth() + 1
	let day = preDate.getDate()
	let s = year + '-' + (mon < 10 ? ('0' + mon) : mon) + '-' + (day < 10 ? ('0' + day) : day)
	if (type == 'ymd') {
		return s
	} else {
		return s + ' 00:00:00'
	}
}

// 获取n近7月  7后7 -7 前
export function getnRencebtMonth(n) {
	let date = new Date();
	date.setMonth(date.getMonth() - n)
	date.toLocaleDateString()
	let y = date.getFullYear()
	let m = date.getMonth() + 1
	m = m < 10 ? ('0' + m) : m + ''
	return y + m
}
/**
 * 数据去重 相同数据值累加
 * @param {Object} array 数据
 */
export function setArray(array) {
	let newArr = []
	array.forEach(item => {
		const res = newArr.findIndex(ol => {
			//组织机构代码相同 并且报警类别相同
			return item.ssbmdm == ol.ssbmdm && item.bjlb == ol.bjlb
		})
		if (res !== -1) {
			newArr[res].sl = newArr[res].sl + item.sl
		} else {
			newArr.push(item)
		}
	})

	return newArr
}

/**
 * 合并数据
 * @param {Object} array 数据
 */
export function hbArray(array, item1, item2, item3) {
	let newArr = []
	array.forEach(item => {
		const res = newArr.findIndex(ol => {
			//组织机构代码相同 并且报警类别相同
			return item.product == ol.product
		})
		if (res !== -1) {
			newArr[res][item1] = newArr[res][item1] + item[item1]
			newArr[res][item2] = newArr[res][item2] + item[item2]
			newArr[res][item3] = newArr[res][item3] + item[item3]
		} else {
			newArr.push(item)
		}
	})

	return newArr
}
/**
 * 时间格式
 * @param {*} type
 * @param {*} time
 */
export function dateFormat(type, time) {
	let date
	if (time) {
		date = new Date(time);
	} else {
		date = new Date();
	}
	let year = date.getFullYear();
	let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
	let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
	let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
	let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	if (type == 'all') {
		//格式化日期时间
		return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
	} else if (type == 'z') {
		//前一天
		let date1 = new Date(date.getTime() - 24 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == 'z2') {
		//前2天
		let date1 = new Date(date.getTime() - 48 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == 'h') {
		//后一天
		let date1 = new Date(date.getTime() + 24 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == '3') {
		//近三天
		let date1 = new Date(date.getTime() - 72 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == 'week') {
		//近7天
		let date1 = new Date(date.getTime() - 168 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == 'month') {
		//近一月
		let date1 = new Date(date.getTime() - 720 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == '3month') {
		//近三月
		let date1 = new Date(date.getTime() - 2160 * 60 * 60 * 1000)
		return setTimeTormat(date1);
	} else if (type == '6month') {
		//近半年
		let date1 = new Date(date.getTime() - 4320 * 60 * 60 * 1000)
		return setTimeTormat(date1);

	} else {
		//当天日期
		return `${year}-${month}-${day}`;
	}
}

//设置时间
function setTimeTormat(date) {
	let year1 = date.getFullYear();
	let month1 =
		date.getMonth() + 1 < 10 ?
			"0" + (date.getMonth() + 1) :
			date.getMonth() + 1;
	let day1 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
	return `${year1}-${month1}-${day1}`;
}
/**
 * 获取类型名称
 * @param {*} type
 */
export function getTypeName(type) {
	let name
	switch (type) {
		case 'zjq':
			name = '总数'
			break
		case 'zdjq':
			name = '重大警情'
			break
		case 'wffz':
			name = '违法犯罪'
			break
		case 'jmjq':
			name = '街面警情'
			break
	}
	return name
}

/**
 * 警情数据去重
 * @param {Object} array 数据
 */
export function setArrayQc(array) {
	let newArr = []
	array.forEach(item => {
		const res = newArr.findIndex(ol => {
			return item.type == ol.type
		})
		if (res !== -1) {
			newArr[res] = item
		} else {
			newArr.push(item)
		}
	})
	return newArr
}

//深珀方面警情相关请求
export function spPostRequest(url, data = {}, fun) {
	axios.post(`${baseUrl2}/xz1Api${url}`, data, {}).then(res => {
		fun(res.data)
	})
}

//托尔斯走访记录相关请求
export function trsGetRequest(url, params = {}, token, fun) {
	axios.get(`${baseUrl2}/trs2Api${url}`, {
		params,
		headers: {
			"Authorization": `Bearer ${token}`,
			"User-Agent": "trs",
			"End-Mode": "app"
		},
	}).then(res => {
		fun(res.data)
	})
}
//托尔斯走访记录相关请求
export function trsPostRequest(url, data = {}, token, fun) {
	axios.post(`${baseUrl2}/trs2Api${url}`, data, {
		headers: {
			"Authorization": `Bearer ${token}`,
			"User-Agent": "trs",
			"End-Mode": "app"
		}
	}).then(res => {
		fun(res.data)
	})
}
export function trs2PostRequest(url, data, token, fun) {
	axios.post(`${baseUrl2}/trs2Api${url}?${data}`, {}, {
		headers: {
			"Authorization": `Bearer ${token}`,
			"User-Agent": "trs",
			"End-Mode": "app"
		}
	}).then(res => {
		fun(res.data)
	})
}
//获取托尔斯token
export function getTrsToken(params, fun) {
	axios.get(`${baseUrl2}/mosty-api/mosty-base/trs/token/new/getToken`, {
		params
	}, {}).then(res => {
		fun(res.data)
	})
}

//源码实有人口任务相关请求
export function ymGetRequest(url, params = {}, token, fun) {
	axios.get(`${baseUrl2}/ymApi/af-api/api${url}`, {
		params,
		headers: {
			"Authorization": token,
		},
	}).then(res => {
		fun(res.data)
	})
}
//源码实有人口任务相关请求
export function ymPostRequest(url, data = {}, token, fun) {
	axios.post(`${baseUrl2}/ymApi/af-api/api${url}`, data, {
		headers: {
			"Authorization": token,
		}
	}).then(res => {
		fun(res.data)
	})
}

//获取源码token
export function getYmToken(data, fun) {
	axios.post(`${baseUrl2}/ymApi/af-api/login`, data, {}).then(res => {
		fun(res.data)
	}).catch((err) => {
		hintToast("您没有权限，请联系管理员!")
	});
}
//获取模板内容信息
export function getPzPlateList(bklx) {
	if (bklx) {
		let plateList = []
		let module = JSON.parse(getStorage("defaultModule"))
		//模板信息
		if (module) {
			let info = module.find(item => {
				return bklx == item.bklx
			})
			//模板内容信息
			if (info) plateList = info.plateList
		}
		return plateList
	}
}

/**
 * 计算两点之间距离
 * @export
 * @param {*} lat1
 * @param {*} lng1
 * @param {*} lat2
 * @param {*} lng2
 */
export function getDistance(lat1, lng1, lat2, lng2) {
	let redLat1 = lat1 * Math.PI / 180.0;
	let redLat2 = lat2 * Math.PI / 180.0;
	let a = redLat1 - redLat2;
	let b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
	let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(redLat1) * Math.cos(redLat2) * Math.pow(Math
		.sin(b / 2), 2)));
	s = s * 6378.137;
	s = Math.round(s * 10000) / 10000
	s = s * 1000
	return s
}

/**
 * @export 函数节流
 * @param {*} fn 函数
 * @param {number} [time=500] 延迟延迟执行毫秒数
 * @param {number} [type=2] 1 时间戳 2 定时器
 */
export function throtter(fn, time = 500, type = 2) {
	let previous, timeout
	if (type == 1) previous = 0
	return function () {
		let context = this
		let args = arguments
		if (type == 1) {
			let now = Date.now()
			if (now - previous > time) {
				fn.apply(context, args);
				previous = now;
			}
		} else {
			if (!timeout) {
				timeout = setTimeout(() => {
					timeout = null
					fn.apply(context, args);
				}, time)
			}
		}
	}
}

/**
 *对象数组排序
 * @export
 * @param {*} attr 排序的字段
 * @param {*} rev true 升序 false 降序
 */
export function compare(attr, rev) {
	if (rev == undefined) {
		rev = 1
	} else {
		rev = rev ? 1 : -1
	}
	return (a, b) => {
		a = a[attr]
		b = b[attr]
		if (a > b) {
			return rev * -1
		}
		if (a < b) {
			return rev * 1
		}
		return 0
	}
}
/**
 * 获取base64地址
 * @param {*} fun 回调
 * @param {*} url 地址
 */
export function getBase64(fun, url) {
	if (fun && typeof fun === 'function') {
		axios.get(`${baseUrl2}/mosty-api/mosty-base/image/base64`, {
			params: {
				url
			}
		}).then((res) => {
			fun(`data:image/jpeg;base64,${res.data.data}`);
		}).catch((err) => {
			fun("");
		});
	} else {
		// Promise模式
		return new Promise((resolve, reject) => {
			axios.get(`${baseUrl2}/mosty-api/mosty-base/image/base64`, {
				params: { url }
			}).then((res) => {
				resolve(`data:image/jpeg;base64,${res.data.data}`);
			}).catch((err) => {
				console.error('获取base64失败:', err);
				resolve("");
			});
		});
	}
}
/**
 * 文件是否是图片
 * @param {*} val
 */
export function IS_PNG(val) {
	return ['bmp', 'jpg', 'png', 'tif', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo',
		'eps', 'ai', 'raw', 'wmf', 'webp', 'avif', 'apng'
	].indexOf(val.toLowerCase()) !== -1
}
/**
 * 文件是否是音频
 * @param {*} val
 */
export function IS_MP3(val) {
	return ['mp3', 'wav', 'wma', 'mp2', 'flac', 'midi', 'ra', 'ape', 'aac', 'cda', 'mov'].indexOf(val.toLowerCase()) !==
		-1
}

/**
 * 文件是否是视频
 * @param {*} val
 */
export function IS_MP4(val) {
	return ['avi', 'wmv', 'mpeg', 'mp4', 'm4v', 'mov', 'asf', 'fiv', 'f4v', 'mvb', 'rm', '3gp', 'vob'].indexOf(val
		.toLowerCase()) !== -1
}
/**
 * 数据去重
 * @param {*} array 去重数据
 * @param {*} val 去重字段
 */
export function dataQc(array, val) {
	let newArr = []
	array.forEach(item => {
		const res = newArr.findIndex(ol => {
			return item[val] == ol[val]
		})
		if (res !== -1) {
			newArr[res] = item
		} else {
			newArr.push(item)
		}
	})
	return newArr
}
//默认时间赛选条件
export function setTimeQuantum() {
	return {
		title: "按时间",
		isCheckBox: false,
		array: [{
			name: "今日",
			key: 1,
		},
		{
			name: "近三日",
			key: 2,
		},
		{
			name: "近一周",
			key: 3,
		},
		{
			name: "近一月",
			key: 4,
		},
		{
			name: "近三月",
			key: 5,
		},
		{
			name: "近半年",
			key: 6,
		},
		],
	}
}

export function GetDateDiff(startTime, endTime, diffType) {
	startTime = startTime.replace(/\-/g, "/");
	endTime = endTime.replace(/\-/g, "/");
	var sTime = new Date(startTime);
	var eTime = new Date(endTime);
	var timeType = 1
	switch (diffType) {
		case 's':
			timeType = 1000;
			break;
		case 'm':
			timeType = 1000 * 60;
			break;
		case 'h':
			timeType = 1000 * 3600;
			break;
		case 'd':
			timeType = 1000 * 3600 * 24;
			break;

		default:
			break;
	}
	return parseInt((eTime.getTime() - sTime.getTime()) / parseInt(timeType))

}

/**
 * 跳转首页
 * @param {*} value ID
 */
export function setUserHome(value) {
	switch (value) {
		case 6:
			setStorage("homeUrl", "/newTwoHome");
			router.replace("/newTwoHome");
			break;
		case 7:
			setStorage("homeUrl", "/");
			router.replace("/");
			break;

	}
}
//获取天气数据
export function getWeatherData(params, fun) {
	axios.get(`${baseUrl2}/mosty-api/mosty-base/other/getWeather`, {
		params
	}, {}).then(res => {
		fun(res.data.data)
	})
}


/**
 * 提示窗口
 * @param {*} msg  消息
 * @param {*} hintType  位置
 */
Toast.allowMultiple();
export function hintToast(msg, hintType = 'top') {
	const toast1 = Toast({
		message: msg,
		position: hintType
	})
}
export function getLocationJs() {
	let jwd = {}
	if ("geolocation" in navigator) {
		navigator.geolocation.getCurrentPosition(
			(pos) => {
				if (pos.coords) {
					jwd.lat = pos.coords.latitude;
					jwd.lng = pos.coords.longitude;
				}
			},
			(err) => {
				console.log(err, "err");
			}
		);
	} else {
		console.log("Geolocation is not supported by this browser.");
	}
	return jwd;
};
