using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Hotline.Tools;

public static class LocationConverter
{
    private const double Pi = Math.PI;
    private const double A = 6378245.0;
    private const double Ee = 0.006693421622965943;

    public static (double lat, double lon)  Wgs84ToGcj02(double lat, double lon)
    {
        double dLat = TransformLat(lon - 105.0, lat - 35.0);
        double dLon = TransformLon(lon - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * Pi;
        double magic = Math.Sin(radLat);
        magic = 1.0 - Ee * magic * magic;
        double sqrtMagic = Math.Sqrt(magic);
        dLat = dLat * 180.0 / A * (1.0 - Ee) / magic * sqrtMagic * Pi;
        dLon = dLon * 180.0 / A / sqrtMagic * Math.Cos(radLat) * Pi;

        double mgLat = lat + dLat;
        double mgLon = lon + dLon;

        return (mgLat, mgLon);
    }

    public static (double lat, double lon) Gcj02ToWgs84(double lat, double lon)
    {
        var gps = Transform(lat, lon);
        double lontitude = lon * 2.0 - gps.lon;
        double latitude = lat * 2.0 - gps.lat;

        return (latitude, lontitude);
    }

    private static 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 * Math.Sqrt(Math.Abs(x));
        ret += (20.0 * Math.Sin(6.0 * x * Pi) + 20.0 * Math.Sin(2.0 * x * Pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.Sin(y * Pi) + 40.0 * Math.Sin(y / 3.0 * Pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.Sin(y / 12.0 * Pi) + 320.0 * Math.Sin(y * Pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    private static double TransformLon(double x, double y)
    {
        double ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.Sqrt(Math.Abs(x));
        ret += (20.0 * Math.Sin(6.0 * x * Pi) + 20.0 * Math.Sin(2.0 * x * Pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.Sin(x * Pi) + 40.0 * Math.Sin(x / 3.0 * Pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.Sin(x / 12.0 * Pi) + 300.0 * Math.Sin(x / 30.0 * Pi)) * 2.0 / 3.0;
        return ret;
    }

    private static (double lat, double lon) Transform(double lat, double lon)
    {
        double dLat = TransformLat(lon - 105.0, lat - 35.0);
        double dLon = TransformLon(lon - 105.0, lat - 35.0);
        double radLat = lat / 180.0 * Pi;
        double magic = Math.Sin(radLat);
        magic = 1.0 - Ee * magic * magic;
        double sqrtMagic = Math.Sqrt(magic);
        dLat = dLat * 180.0 / A * (1.0 - Ee) / magic * sqrtMagic * Pi;
        dLon = dLon * 180.0 / A / sqrtMagic * Math.Cos(radLat) * Pi;

        double mgLat = lat + dLat;
        double mgLon = lon + dLon;

        return (mgLat, mgLon);
    }
}
