package cn.reghao.tnb.content.app.geo.service;

import cn.reghao.jutil.jdk.serializer.JsonConverter;
import cn.reghao.jutil.jdk.io.TextFile;
import cn.reghao.tnb.content.app.ContentApplication;
import cn.reghao.tnb.content.app.geo.db.mapper.*;
import cn.reghao.tnb.content.app.geo.model.po.*;
import cn.reghao.tnb.content.app.geo.model.vo.GeoArea;
import cn.reghao.tnb.content.app.geo.model.vo.MapMarker;
import cn.reghao.tnb.content.app.geo.model.vo.MapPoint;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;

import java.util.*;

/**
 * @author reghao
 * @date 2025-03-15 19:39:57
 */
@Slf4j
@ActiveProfiles("dev")
@SpringBootTest(classes = ContentApplication.class)
public class GeoTest {
    @Autowired
    MapService mapService;

    @Autowired
    GeoChinaMapper geoChinaMapper;
    @Test
    public void parseGeoData() {
        TextFile textFile = new TextFile();
        String filePath = "/home/reghao/Downloads/geo/ok_geo.csv";
        List<String> list = textFile.read(filePath);

        System.out.println(list.get(0));
        for (int i = 1; i < list.size(); i++) {
            String line = list.get(i);
            String[] arr = line.split(",\"");
            String[] arr1 = arr[0].split(",");

            if (arr1[0].startsWith("71")) {
                continue;
            }

            int id = Integer.parseInt(arr1[0]);
            int pid = Integer.parseInt(arr1[1]);
            int deep = Integer.parseInt(arr1[2]);

            String name = arr[1].replace("\"", "");
            String extPath = arr[2].replace("\"", "");

            String geo = arr[3];
            String[] geoArr = geo.replace("\"", "").split(" ");
            double lat = Double.parseDouble(geoArr[0]);
            double lng = Double.parseDouble(geoArr[1]);
            String polygon = arr[4].replace("\"", "");
            String[] polygonArr = polygon.split(";");
            List<String> polygonStrList = new ArrayList<>();
            if (polygonArr.length == 1) {
                String polygonStr = getPolygonStr(polygonArr[0]);
                polygonStrList.add(polygonStr);
            } else {
                for (String polygonLine : polygonArr) {
                    String polygonStr = getPolygonStr(polygonLine);
                    polygonStrList.add(polygonStr);
                }
            }

            GeoChina geoChina = new GeoChina(id, pid, deep, name, extPath, lng, lat);
            GeoChina geoChina0 = geoChinaMapper.findById(id);
            if (geoChina0 == null) {
                try {
                    if (polygonStrList.size() == 1) {
                        geoChina.setPolygon(polygonStrList.get(0));

                        geoChinaMapper.save(geoChina);
                    } else {
                        StringBuilder sb = new StringBuilder();
                        for (String str : polygonStrList) {
                            sb.append("((").append(str).append(")),");
                        }
                        String multiPolygon = sb.toString();
                        int idx = multiPolygon.lastIndexOf(",");
                        multiPolygon = multiPolygon.substring(0, idx);
                        geoChina.setMultiPolygon(multiPolygon);

                        geoChinaMapper.saveMultiPolygon(geoChina);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println();
                }
            }
        }
    }

    private String getPolygonStr(String polygonStr) {
        String first = polygonStr.split(",")[0];
        return polygonStr + ("," + first);
    }

    private String getEarthPolygon(String polygon) {
        List<String> list1 = new ArrayList<>();
        String[] polygonArr = polygon.split(",");
        for (String point : polygonArr) {
            String[] pointArr = point.split(" ");
            list1.add(pointArr[0] + "," + pointArr[1] + ",0");
        }

        StringBuilder sb = new StringBuilder();
        for (String str : list1) {
            sb.append(str).append(" ");
        }

        return sb.toString().trim();
    }

    @Autowired
    CameraPhotoMapper cameraPhotoMapper;
    @Test
    void photoMapTest() {
        List<CameraPhoto> list = cameraPhotoMapper.findAll();
    }

    @Autowired
    BusStationMapper busStationMapper;
    @Test
    void geoBusTest() {
        List<BusStation> list = busStationMapper.findAll();
        for (BusStation busStation : list) {
            String id = busStation.getId()+"";
            String stationName = busStation.getStationName();
            String latStr = String.valueOf(busStation.getLat());
            String latStr1 = String.format("%s.%s", latStr.substring(0, 2), latStr.substring(2));
            double lat = Double.parseDouble(latStr1);

            String lngStr = String.valueOf(busStation.getLng());
            String lngStr1 = String.format("%s.%s", lngStr.substring(0, 3), lngStr.substring(3));
            double lng = Double.parseDouble(lngStr1);
            MapPoint mapPoint = new MapPoint(lng, lat);

            MapMarker mapMarker = new MapMarker(id, stationName, mapPoint);
        }
    }

    @Autowired
    MallReplyMapper mallReplyMapper;
    @Test
    public void updateCupTest() {
        List<MallReply> list = mallReplyMapper.findAll();
        list.forEach(mallReply -> {
            String extra = mallReply.getExtra();
            String cup = getFormattedTitle1(extra);
            if (cup != null) {
                mallReply.setCup(cup);
                mallReplyMapper.updateSetCup(mallReply.getReplyId(), cup);
            }
        });
    }

    String getFormattedTitle1(String title) {
        String extra1 = null;
        if (title.startsWith("{")) {
            JsonObject jsonObject = JsonConverter.jsonToJsonElement(title).getAsJsonObject();
            if (jsonObject.get("尺码") != null) {
                extra1 = jsonObject.get("尺码").getAsString();
                if (extra1.contains("码（建议")) {
                    String[] arr = extra1.split(" ");
                    extra1 = arr[arr.length-1].replace("）", "");
                } else if (extra1.contains("[【")) {
                    String[] arr = extra1.split("\\[【");
                    if (arr.length == 1) {
                        return null;
                    }

                    extra1 = arr[arr.length-1].replace("】]", "");
                    System.out.println();
                } else if (extra1.contains("（建议")) {
                    String[] arr = extra1.split("斤 ");
                    if (arr.length == 1) {
                        arr = extra1.split("\\[\\(");
                    }

                    extra1 = arr[arr.length-1].replace("）", "");
                } else if (extra1.contains("[(")) {
                    String[] arr = extra1.split(" ");
                    if (arr.length == 1) {
                        arr = extra1.split("\\[\\(");
                    }

                    extra1 = arr[arr.length-1].replace(")]", "");
                }
            } else if (jsonObject.get("颜色分类") != null) {
                extra1 = jsonObject.get("颜色分类").getAsString();
                if (extra1.contains("2023新版-肤色")) {
                    String[] arr = extra1.split("）");
                    if (arr.length == 1) {
                        return null;
                    }

                    extra1 = arr[arr.length-1];
                } else if (extra1.contains("杯【")) {
                    String[] arr = extra1.split("【");
                    if (arr.length == 1) {
                        arr = extra1.split("\\[\\(");
                    }

                    extra1 = arr[0].split("）")[1];
                }
            }
        } else {
            extra1 = title.split("尺码:")[1];
            String[] arr = title.split("&nbsp;&nbsp");
            for (String str : arr) {
                if (str.startsWith("尺码")) {
                    extra1 = str.split(":")[1];
                    break;
                }
            }
        }
        return extra1;
    }

    @Test
    public void updateAreaCodeTest() {
        List<CameraPhoto> list = cameraPhotoMapper.findAll();
        for (CameraPhoto cameraPhoto : list) {
            double lng = cameraPhoto.getLongitude().doubleValue();
            double lat = cameraPhoto.getLatitude().doubleValue();
            MapPoint mapPoint = new MapPoint(lng, lat);
            GeoArea geoArea = geoChinaMapper.findByPoint(mapPoint);
            if (geoArea != null) {
                int areaCode = geoArea.getId();
                String extPath = geoArea.getExtPath();
                String objectId = cameraPhoto.getObjectId();
                cameraPhotoMapper.updateSetAreaCode(objectId, areaCode);
                log.info("update {} {} -> {}", objectId, areaCode, extPath);
            }
        }
    }
}
