# -*- coding:utf-8 -*-
# @Time    : 2020/5/18 9:17 上午
# @Author  : Creat by Han
from Crypto.Cipher import AES
import base64
import configparser
import os
import json
import math
import copy

environ = None
try:
    try:
        with open(os.path.expanduser("~/.environ"), "r") as f:
            environ = f.read().strip()
            assert environ
    except:
        with open(os.path.expanduser("F:\.environ.txt"), "r") as f:
            environ = f.read().strip()
            assert environ
except:
    raise Exception("no ~/.environ found! you must create one!")

_ = configparser.ConfigParser()
_flag = None

# 获取项目配置文件
def parse_config_new(config_dir=None):
    dir_name = os.path.dirname(os.path.dirname(__file__))
    config_dir = os.path.abspath(dir_name)
    global _flag
    if not _flag:
        with open(os.path.join(config_dir, "%s" % environ), "r") as f:
            _flag = f.read()
            if _flag:
                _flag = json.loads(_flag)
            else:
                _flag = {}
    return _flag


# token加密
class Aescrypt():
    def __init__(self, key, model, iv, encode_):
        self.encode_ = encode_
        self.model = {'ECB': AES.MODE_ECB, 'CBC': AES.MODE_CBC}[model]
        self.key = self.add_16(key)
        if model == 'ECB':
            self.aes = AES.new(self.key, self.model)
        elif model == 'CBC':
            self.aes = AES.new(self.key, self.model, iv)

    def add_16(self, par):
        par = par.encode(self.encode_)
        while len(par) % 32 != 0:
            par += b'\x00'
        return par

    def aesencrypt(self, text):
        text = self.add_16(text)
        self.encrypt_text = self.aes.encrypt(text)
        return base64.encodebytes(self.encrypt_text).decode().strip()

    def aesdecrypt(self, text):
        text = base64.decodebytes(text.encode(self.encode_))
        self.decrypt_text = self.aes.decrypt(text)
        return self.decrypt_text.decode(self.encode_).strip('\0')


PrAes = Aescrypt('yf7232275', 'ECB', '', 'gbk')



# 简单判断坐标点是否在中国
# 不在的话返回True
# 在的话返回False
def judge_China(lon, lat):
    if lon < 70 or lon > 140:
        return True
    if lat < 0 or lat > 55:
        return True
    return False


# 设置常量
pi = 3.141592653589793234  # π
r_pi = pi * 3000.0 / 180.0
la = 6378245.0  # 长半轴
ob = 0.00669342162296594323  # 扁率


# 经纬度计算功能类
def transformlat(lon, lat):
    r = -100.0 + 2.0 * lon + 3.0 * lat + 0.2 * lat * lat + 0.1 * lon * lat + 0.2 * math.sqrt(math.fabs(lon))
    r += (20.0 * math.sin(6.0 * lon * pi) + 20.0 * math.sin(2.0 * lon * pi)) * 2.0 / 3.0
    r += (20.0 * math.sin(lat * pi) + 40.0 * math.sin(lat / 3.0 * pi)) * 2.0 / 3.0
    r += (160.0 * math.sin(lat / 12.0 * pi) + 320 * math.sin(lat * pi / 30.0)) * 2.0 / 3.0
    return r

def transformlng(lon, lat):
    r = 300.0 + lon + 2.0 * lat + 0.1 * lon * lon + 0.1 * lon * lat + 0.1 * math.sqrt(math.fabs(lon))
    r += (20.0 * math.sin(6.0 * lon * pi) + 20.0 * math.sin(2.0 * lon * pi)) * 2.0 / 3.0
    r += (20.0 * math.sin(lon * pi) + 40.0 * math.sin(lon / 3.0 * pi)) * 2.0 / 3.0
    r += (150.0 * math.sin(lon / 12.0 * pi) + 300.0 * math.sin(lon / 30.0 * pi)) * 2.0 / 3.0
    return r

# wgs84 -> gcj02
# lng为wgs84的经度
# lat为wgs84的纬度
# 返回值为转换后坐标的列表形式，[经度, 纬度]
def wgs84_gcj02(lon_wgs84, lat_wgs84):
    if judge_China(lon_wgs84, lat_wgs84):  # 判断是否在国内
        return [lon_wgs84, lat_wgs84]
    tlat = transformlat(lon_wgs84 - 105.0, lat_wgs84 - 35.0)
    tlng = transformlng(lon_wgs84 - 105.0, lat_wgs84 - 35.0)
    rlat = lat_wgs84 / 180.0 * pi
    m = math.sin(rlat)
    m = 1 - ob * m * m
    sm = math.sqrt(m)
    tlat = (tlat * 180.0) / ((la * (1 - ob)) / (m * sm) * pi)
    tlng = (tlng * 180.0) / (la / sm * math.cos(rlat) * pi)
    lat_gcj02 = lat_wgs84 + tlat
    lon_gcj02 = lon_wgs84 + tlng
    return [lon_gcj02, lat_gcj02]


def wgs84_to_gcj02():
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    with open(os.path.join(BASE_DIR, "base.json"), 'r', encoding='utf-8') as fg:
        wgs84 = json.load(fg)
    wgs84_copy = copy.deepcopy(wgs84)
    features = wgs84.get("features")
    new_out_features = []
    for f in features:
        new_in_features = {
            "geometry": {},
            "attributes": f.get("attributes")
        }
        rings = f.get("geometry").get("rings")
        new_rings = []
        for r in rings:
            temp = []
            for i in r:
                # print(i)
                # print('--------------------')
                result = wgs84_gcj02(i[0], i[1])
                # print(result)
                temp.append(result)
            new_rings.append(temp)
        new_in_features["geometry"] = {"rings": new_rings}
        new_out_features.append(new_in_features)
    wgs84_copy["features"] = new_out_features
    with open(os.path.join(BASE_DIR, "gcj02.json"), 'w', encoding='utf-8', ) as fk:
        json.dump(wgs84_copy, fk, ensure_ascii=False)

wgs84_to_gcj02()