package com.fdkankan.dxf.parse.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fdkankan.dxf.fdjson.vo.FdFloors;
import com.fdkankan.dxf.fdjson.vo.FdFloorsPanJson;
import com.fdkankan.dxf.fdjson.vo.FdPoints;
import com.fdkankan.dxf.fdjson.vo.FdWalls;
import com.fdkankan.dxf.generate.DxfDocWriter;
import com.fdkankan.dxf.generate.Vector3;
import com.fdkankan.dxf.generate.model.DxfLine;
import com.fdkankan.dxf.generate.model.base.Color;
import com.fdkankan.dxf.parse.ParseDXF;
import com.fdkankan.dxf.parse.model.entities.GeometricLine;
import com.fdkankan.dxf.parse.resolver.DxfResolver;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

public class FdJsonToDxfUtil {

    /**
     * floorplan_user.json 转 dxf
     * @param fdJsonPath floorplan.json 路径
     * @param dxfPath   dxf生成路径
     * @param subgroup  多楼层，楼层数 floorplan中需存在
     */
    public static void fdJsonToDxf(String fdJsonPath,String dxfPath,Integer subgroup)  {
        try {
            String msg = new String(Files.readAllBytes(Paths.get(fdJsonPath)));
            JSONObject jsonObject = JSONObject.parseObject(msg);
            JSONArray floors = jsonObject.getJSONArray("floors");
            for (Object obj : floors) {
                JSONObject floor = (JSONObject) (obj);
                if(floor.getInteger("subgroup") != null && floor.getInteger("subgroup").equals(subgroup)){
                    plantWall(dxfPath,floor);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * floorplan_user.json 转 dxf
     * @param fdJsonPath floorplan_user.json 路径
     * @param dxfPath   dxf生成路径
     */
    public static void fdJsonToDxf(String fdJsonPath,String dxfPath)  {
        try {
            String msg = new String(Files.readAllBytes(Paths.get(fdJsonPath)));
            JSONObject jsonObject = JSONObject.parseObject(msg);
            JSONArray floors = jsonObject.getJSONArray("floors");
            for (Object obj : floors) {
                JSONObject floor = (JSONObject) (obj);
                plantWall(dxfPath,floor);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     * 墙，根据起始点画线
     */
    private static void plantWall(String filePath, JSONObject fools) {
        HashMap<String, FdPoints> wallMap= new HashMap<>();

        JSONObject walls = fools.getJSONObject("walls");
        JSONObject points = fools.getJSONObject("points");
        for (String key : points.keySet()) {
            JSONObject obj = points.getJSONObject(key);
            FdPoints point = new FdPoints(obj.getDouble("x") * 100, obj.getDouble("y") * 100);
            wallMap.put(key,point);
        }
        DxfDocWriter dxfDocWriter = new DxfDocWriter();
        for (String key : walls.keySet()) {
            JSONObject wall = walls.getJSONObject(key);
            String start = wall.getString("start");
            String end = wall.getString("end");
            drawLinePoint(filePath,wallMap.get(start),wallMap.get(end),dxfDocWriter);
        }
        dxfDocWriter.save(filePath, true);
    }

    public static void drawLinePoint(String filePath,FdPoints point,FdPoints point2,DxfDocWriter dxfDocWriter){

        DxfLine dxfLine = new DxfLine();
        dxfLine.setStartPoint(new Vector3(point.getX(), point.getY(), 0));
        dxfLine.setEndPoint(new Vector3(point2.getX(), point2.getY(), 0));
        dxfLine.setColor(Color.GREEN);
        dxfDocWriter.addEntity(dxfLine);


    }




    /**
     * dxf 转 floorplan_user.json
     * @param dxfPath   dxf生成路径
     * @param jsonPath floorplan_user.json 路径
     */
    public static String dxfToFdJson(String dxfPath,String jsonPath){
        try {
            FdFloorsPanJson fdFloorsPanJson = new FdFloorsPanJson();
            FdFloors fdFloors = new FdFloors();
            JSONObject walls = fdFloors.getWalls();
            JSONObject points = fdFloors.getPoints();
            fdFloorsPanJson.getFloors().add(fdFloors);

            DxfResolver build = ParseDXF.build(dxfPath);
            List<GeometricLine> geometricLineList = build.getGeometricLineList();
            writeFdLine(geometricLineList,points,walls);
            String jsonString = JSONObject.toJSONString(fdFloorsPanJson);
            WriteStringToFile.writeFile(jsonString,jsonPath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return null;
    }

    private static void writeFdLine(List<GeometricLine> geometricLineList,JSONObject points,JSONObject walls) {
        HashSet<String> pointSet = new HashSet<>();
        HashMap<String,String> pointMap = new HashMap<>();
        for (GeometricLine geometricLine : geometricLineList) {
            pointSet.add(geometricLine.getStartX() + "," + geometricLine.getStartY());
            pointSet.add(geometricLine.getEndX() + "," + geometricLine.getEndY());
        }
        int pointIndex = 0;
        for (String xy : pointSet) {
            FdPoints fdPoints = new FdPoints();
            fdPoints.setX(Double.valueOf(xy.split(",")[0])/100);
            fdPoints.setY(Double.valueOf(xy.split(",")[1])/100);
            points.put("point"+pointIndex,fdPoints);
            pointMap.put(xy,"point"+pointIndex);
            pointIndex ++;
        }
        Integer wallIndex = 0;
        for (GeometricLine geometricLine : geometricLineList) {
            FdWalls fdWalls = new FdWalls();
            String pointNameStart = pointMap.get(geometricLine.getStartX() + "," + geometricLine.getStartY());
            String pointNameEnd = pointMap.get(geometricLine.getEndX() + "," + geometricLine.getEndY());
            fdWalls.setStart(pointNameStart);
            fdWalls.setEnd(pointNameEnd);
            walls.put("wall"+wallIndex,fdWalls);
            wallIndex ++;
        }
    }

    public static void main(String[] args) {
        String inPath ="D:\\cad\\work\\111\\floorplan.json";
        String outPath ="D:\\cad\\work\\111\\test1.dxf";
        FdJsonToDxfUtil.fdJsonToDxf(inPath,outPath);
    }
}
