package com.ruoyi.robot.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.robot.domain.LdRoadmap;
import com.ruoyi.robot.mapper.LdRoadmapMapper;
import com.ruoyi.robot.service.ILdRoadmapService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 路网数据Service实现
 */
@Service
public class LdRoadmapServiceImpl implements ILdRoadmapService {

    @Autowired
    private LdRoadmapMapper roadmapMapper;

    @Autowired
    private RedisCache redisCache;

    private static final String ROADMAP_CACHE_KEY = "ld:roadmap:geojson:";

    @Override
    public LdRoadmap selectRoadmapByMapName(String mapName) {
        return roadmapMapper.selectByMapName(mapName);
    }

    @Override
    public String getGeoJsonByMapName(String mapName) {
        LdRoadmap roadmap = selectRoadmapByMapName(mapName);
        if (roadmap != null && StringUtils.isNotBlank(roadmap.getGeojsonData())) {
            return roadmap.getGeojsonData();
        }
        return null;
    }

    @Override
    public int saveRoadmap(String mapName, String geoJsonData) {
        LdRoadmap roadmap = roadmapMapper.selectByMapName(mapName);

        if (roadmap == null) {
            roadmap = new LdRoadmap();
            roadmap.setMapName(mapName);
            roadmap.setGeojsonData(geoJsonData);
            roadmap.setVersion(1);
            roadmap.setIsValid(1);
            int result = roadmapMapper.insert(roadmap);

            if (result > 0) {
                redisCache.deleteObject(ROADMAP_CACHE_KEY + mapName);
            }
            return result;
        } else {
            Map<String, Object> saveData = new HashMap<>();
            saveData.put("type","FeatureCollection");
            saveData.put("features", JSON.parseArray(geoJsonData));
            saveData.put("map", mapName);
            // 转换为 JSON 字符串
            roadmap.setGeojsonData(JSON.toJSONString(saveData));
            roadmap.setVersion(roadmap.getVersion() + 1);
            int result = roadmapMapper.updateById(roadmap);

            if (result > 0) {
                redisCache.deleteObject(ROADMAP_CACHE_KEY + mapName);
            }
            return result;
        }
    }
}
