package com.cmvr.system.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.system.domain.SysVehOperConfig;
import com.cmvr.system.domain.vo.CarIcon;
import com.cmvr.system.domain.vo.CarUi;
import com.cmvr.system.service.CarPathFinderService;
import com.cmvr.system.service.ISysVehOperConfigService;
import com.cmvr.system.util.CarPathFinderUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * CarPathFinderService的具体实现类
 * 用于查找从起始界面到目标功能的路径
 */
@Service
@RequiredArgsConstructor
public class CarPathFinderServiceImpl implements CarPathFinderService {

    private final ISysVehOperConfigService vehOperConfigService;

    /**
     * 获取 JSON 配置，查找路径
     */
    @Override
    public List<CarIcon> findPath(String manufacturer, String vehType, String startUi, String targetFeature) {
        SysVehOperConfig sysVehOperConfig = vehOperConfigService.selectSysVehOperConfig(manufacturer, vehType);
        if (ObjUtil.isEmpty(sysVehOperConfig)) {
            throw new GlobalException("未找到对应的车机配置");
        }
        String configStr = sysVehOperConfig.getJsonData();
        if (StrUtil.isEmpty(configStr)) {
            return null;
        }
        JSONArray jsonData = JSON.parseArray(configStr);
        return findPath(jsonData, startUi, targetFeature);
    }

    /**
     * 直接使用 JSON 数据查找路径
     */
    @Override
    public List<CarIcon> findPath(JSONArray jsonData, String startUi, String targetFeature) {
        Map<String, CarUi> uiMap = CarPathFinderUtil.buildUiMapFromJson(jsonData);
        return CarPathFinderUtil.findPath(uiMap, startUi, targetFeature);
    }
}
