#ifndef __POSITION_HELPER_H__
#define __POSITION_HELPER_H__

#include <cmath>
#define _USE_MATH_DEFINES

inline double transformLat(double x, double y)
{
	double ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * std::sqrt(std::abs(x));
	ret += (20.0 * std::sin(6.0 * x * M_PI) + 20.0 * std::sin(2.0 * x * M_PI)) * 2.0 / 3.0;
	ret += (20.0 * std::sin(y * M_PI) + 40.0 * std::sin(y / 3.0 * M_PI)) * 2.0 / 3.0;
	ret += (160.0 * std::sin(y / 12.0 * M_PI) + 320 * std::sin(y * M_PI / 30.0)) * 2.0 / 3.0;
	return ret;
}

inline double transformLng(double x, double y)
{
	double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * std::sqrt(std::abs(x));
	ret += (20.0 * std::sin(6.0 * x * M_PI) + 20.0 * std::sin(2.0 * x * M_PI)) * 2.0 / 3.0;
	ret += (20.0 * std::sin(x * M_PI) + 40.0 * std::sin(x / 3.0 * M_PI)) * 2.0 / 3.0;
	ret += (150.0 * std::sin(x / 12.0 * M_PI) + 300.0 * std::sin(x / 30.0 * M_PI)) * 2.0 / 3.0;
	return ret;
}

inline void transformPosition(double& lat, double& lng)
{
    // 卫星椭球坐标投影到平面地图坐标系的投影因子
#define AXIS 6378245.0
    // 椭球的偏心率(a^2 - b^2) / a^2
#define OFFSET 0.00669342162296594323
	double dLat = transformLat(lng - 105.0, lat - 35.0);
	double dLon = transformLng(lng - 105.0, lat - 35.0);
	double radLat = lat / 180.0 * M_PI;
	double magic = std::sin(radLat);
	magic = 1 - OFFSET * magic * magic;
	double sqrtMagic = std::sqrt(magic);
	dLat = (dLat * 180.0) / ((AXIS * (1 - OFFSET)) / (magic * sqrtMagic) * M_PI);
	dLon = (dLon * 180.0) / (AXIS / sqrtMagic * std::cos(radLat) * M_PI);
	lat += dLat;
	lng += dLon;
}

inline bool shouldConvertPosition(double lat, double lon)
{
	if (lon < 72.004 || lon > 137.8347)
	{
		return false;
	}
	if (lat < 0.8293 || lat > 55.8271)
	{
		return false;
	}
	return true;
}


#endif // __POSITION_HELPER_H__