package com.casic.missiles.modular.system.util;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.casic.missiles.config.DeviceApiProperties;
import com.casic.missiles.core.util.SpringContextHolder;
import com.casic.missiles.modular.system.handler.DefaultHttpHeaderHandler;
import com.casic.missiles.modular.system.model.BusWellInfo;
import com.casic.missiles.modular.system.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Utility {
    private static final Logger logger = LoggerFactory.getLogger(Utility.class);

    public static Map<String, Object> convertBaiduAPI(String lng, String lat) {
        Map<String, Object> result = new HashMap<>();
        DeviceApiProperties sluicewellProperties = SpringContextHolder.getBean(DeviceApiProperties.class);
        String url = sluicewellProperties.getBaiduUrl();
        String ak = sluicewellProperties.getBaiduAk();
        String coords = lng + "," + lat;
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("coords", coords);
            params.put("ak", ak);
            params.put("from", "1");
            params.put("to", "5");

            String str = HttpUtils.sendGet(url, params,"",new DefaultHttpHeaderHandler());
            JSONObject jsStr = JSONObject.parseObject(str);
            if (jsStr.getInteger("status") == 0) {
                JSONObject coordinate = (JSONObject) jsStr.getJSONArray("result").get(0);
                double x = coordinate.getDouble("x");
                double y = coordinate.getDouble("y");
                result.put("x", x);
                result.put("y", y);
                return result;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void convertCoordinate(BusWellInfo busWellInfo){
        if(StrUtil.isNotEmpty(busWellInfo.getCoordinateX()) && StrUtil.isNotEmpty(busWellInfo.getCoordinateY())){
            Map<String,Object> baiduCoordinate = Utility.convertBaiduAPI(busWellInfo.getCoordinateX(),busWellInfo.getCoordinateY());
            if(ObjectUtil.isNotEmpty(baiduCoordinate)) {
                busWellInfo.setLngBaidu(baiduCoordinate.get("x").toString());
                busWellInfo.setLatBaidu(baiduCoordinate.get("y").toString());
            }else{
                logger.error("{}百度坐标转换失败",busWellInfo.getWellCode());
            }

            Map<String,Object> gaodeCoordinate = Utility.convertGaodeAPI(busWellInfo.getCoordinateX(),busWellInfo.getCoordinateY());
            if(ObjectUtil.isNotEmpty(gaodeCoordinate)) {
                busWellInfo.setLngGaode(gaodeCoordinate.get("x").toString());
                busWellInfo.setLatGaode(gaodeCoordinate.get("y").toString());
            }else{
                logger.error("{}高德坐标转换失败",busWellInfo.getWellCode());
            }
        }
    }
    public static Map<String, Object> convertGaodeAPI(String lng, String lat) {
        Map<String, Object> result = new HashMap<>();
        DeviceApiProperties sluicewellProperties = SpringContextHolder.getBean(DeviceApiProperties.class);
        String url = sluicewellProperties.getGaodeUrl();
        String ak = sluicewellProperties.getGaodeKey();
        String coords = lng + "," + lat;
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("locations", coords);
            params.put("key", ak);
            params.put("coordsys", "gps");

            String str = HttpUtils.sendGet(url, params,"",new DefaultHttpHeaderHandler());
            JSONObject jsStr = JSONObject.parseObject(str);
            if (jsStr.getInteger("status") == 1) {
                String coordinate = jsStr.getString("locations");
                String[] xy = coordinate.split(",");
                if (xy != null && xy.length >= 2) {
                    result.put("x", xy[0]);
                    result.put("y", xy[1]);
                }

                return result;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static List<String> convertBaiduAPI(List<String> coordinates) {

        List<String> result = new ArrayList<>();
        DeviceApiProperties sluicewellProperties = SpringContextHolder.getBean(DeviceApiProperties.class);
        String url = sluicewellProperties.getBaiduUrl();
        String ak = sluicewellProperties.getBaiduAk();

        Map<String, String> params = new HashMap<>();
        params.put("coords", null);
        params.put("ak", ak);
        params.put("from", "1");
        params.put("to", "5");
        //百度批量转换一次最多100对坐标
        int size = 100;
        int num = coordinates.size() / 100;
        for (int i = 0; i <= num; i++) {

            if (i == num) {
                size = coordinates.size() % 100;
                if (size == 0) {
                    return result;
                }
            }

            StringBuilder sb = new StringBuilder();
            for (String coordinate : coordinates.subList(i * 100, i * 100 + size)) {
                sb.append(coordinate);
                sb.append(";");
            }
            params.replace("coords", sb.deleteCharAt(sb.length() - 1).toString());

            try {
                String str = HttpUtils.sendGet(url, params,"",new DefaultHttpHeaderHandler());
                JSONObject jsStr = JSONObject.parseObject(str);
                if (jsStr.getInteger("status") == 0) {

                    for (Object baiduCoordinate : jsStr.getJSONArray("result")) {
                        BigDecimal x = ((JSONObject) baiduCoordinate).getBigDecimal("x");
                        BigDecimal y = ((JSONObject) baiduCoordinate).getBigDecimal("y");
                        result.add(x + "," + y);
                    }
                } else {
                    return result;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static List<String> convertGaodeAPI(List<String> coordinates) {
        List<String> result = new ArrayList<>();

        DeviceApiProperties sluicewellProperties = SpringContextHolder.getBean(DeviceApiProperties.class);
        String url = sluicewellProperties.getGaodeUrl();
        String ak = sluicewellProperties.getGaodeKey();

        Map<String, String> params = new HashMap<>();
        params.put("locations", null);
        params.put("key", ak);
        params.put("coordsys", "gps");

        int size = 40;
        int num = coordinates.size() / 40;//批量转换一次最多40对坐标
        for (int i = 0; i <= num; i++) {

            if (i == num) {
                size = coordinates.size() % 40;
                if (size == 0) {
                    return result;
                }
            }

            StringBuilder sb = new StringBuilder();
            for (String coordinate : coordinates.subList(i * 40, i * 40 + size)) {
                sb.append(coordinate);
                sb.append("|");
            }
            params.replace("locations", sb.deleteCharAt(sb.length() - 1).toString());

            try {
                String str = HttpUtils.sendGet(url, params,"",new DefaultHttpHeaderHandler());
                JSONObject jsStr = JSONObject.parseObject(str);
                if (jsStr.getInteger("status") == 1) {
                    String[] gaodeCoordinates = jsStr.getString("locations").split(";");
                    if (gaodeCoordinates != null) {
                        for (String gaodeCoordinate : gaodeCoordinates) {
                            result.add(gaodeCoordinate);
                        }
                    }
                } else {
                    return result;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

}
