package com.cmvr.ti.service.ex;

import cn.hutool.core.text.StrPool;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.common.core.domain.entity.SysDictData;
import com.cmvr.common.exception.GlobalException;
import com.cmvr.common.utils.StringUtils;
import com.cmvr.system.domain.vo.CarIcon;
import com.cmvr.system.domain.vo.CarUi;
import com.cmvr.system.service.ISysDictTypeService;
import com.cmvr.system.util.CarPathFinderUtil;
import com.cmvr.test.service.ex.ExTiVehicleFunctionService;
import com.cmvr.ti.model.domain.TiVehicleFunction;
import com.cmvr.ti.model.domain.TiVehicleUi;
import com.cmvr.ti.model.vo.TiVehicleFunctionVO;
import com.cmvr.ti.service.ITiVehicleFunctionService;
import com.cmvr.ti.service.ITiVehicleUiService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
@RequiredArgsConstructor
public class ExTiVehicleFunctionServiceImpl implements ExTiVehicleFunctionService {

    private final ITiVehicleFunctionService tiVehicleFunctionService;

    private final ITiVehicleUiService tiVehicleUiService;

    private final ISysDictTypeService iSysDictTypeService;


    @Override
    public JSONArray queryByIds(String ids) {
        List<TiVehicleFunction> tiVehicleFunctions = tiVehicleFunctionService.listByIds(StrUtil.split(StrPool.COMMA, ids));
        return JSONArray.from(tiVehicleFunctions);
    }

    @Override
    public JSONObject queryById(Long id) {
        return JSONObject.from(tiVehicleFunctionService.getById(id));
    }

    /**
     * 寻找从当前页面到能执行目标功能的最短点击路径
     * 返回：点击的功能序列（JSONArray 包装 List<TiVehicleFunction>）
     */
    @Override
    public JSONObject findNextClickToFunction(
            Long vehicleConfigId,
            String startUiName,
            String targetFuncName) {
        // 功能字典
        // 实际用的是 sys_dict_data，这里假设你有方法能查到 data 列表
        List<SysDictData> functionDictData = iSysDictTypeService.selectDictDataByType("ti_function_config");

        // 界面字典
        List<SysDictData> uiDictData = iSysDictTypeService.selectDictDataByType("ti_ui_config");

        // 构建 功能 value → label 的映射
        Map<String, String> funcValueToLabel = new HashMap<>();
        for (SysDictData data : functionDictData) {
            funcValueToLabel.put(data.getDictValue(), data.getDictLabel());
        }

        // 构建 界面 value → label 的映射
        Map<String, String> uiValueToLabel = new HashMap<>();
        for (SysDictData data : uiDictData) {
            uiValueToLabel.put(data.getDictValue(), data.getDictLabel());
        }

        // 1. 查询当前车型的实际界面和功能数据
        List<TiVehicleUi> uiList = tiVehicleUiService.selectTiVehicleUiList(
                TiVehicleUi.builder().vehicleConfigId(vehicleConfigId).build());

        List<TiVehicleFunction> funcList = tiVehicleFunctionService.selectTiVehicleFunctionList(
                TiVehicleFunctionVO.builder().vehicleConfigId(vehicleConfigId).build());

        // 2. funcKey → TiVehicleFunction
        Map<Long, TiVehicleFunction> funcById = new HashMap<>();
        for (TiVehicleFunction f : funcList) {
            funcById.put(f.getId(), f);
        }
        // 3.组装uiMap
        Map<String, CarUi> uiMap = new HashMap<>();
        List<CarIcon> icons;
        CarUi carUi;
        for (TiVehicleUi ui : uiList) {
            icons = new ArrayList<>();
            for (String funcId : StringUtils.split(ui.getFuncIds(), StrPool.COMMA)) {
                TiVehicleFunction func = funcById.get(Long.valueOf(funcId));
                CarIcon icon = new CarIcon(
                        funcValueToLabel.get(func.getFuncKey()),
                        func.getIconUrl(),
                        "",
                        "",
                        "1".equals(func.getRemark()) ? funcValueToLabel.get(func.getFuncKey()) : ""
                );
                icons.add(icon);
            }
            carUi = new CarUi(
                    uiValueToLabel.get(ui.getUiKey()),
                    ui.getUiUrl(),
                    icons
            );
            uiMap.put(carUi.getUiName(), carUi);
        }
        // 4.获取路径
        List<CarIcon> path = CarPathFinderUtil.findPath(uiMap, startUiName, targetFuncName);
        if (CollectionUtils.isEmpty(path)) {
            throw new GlobalException("没有找到匹配的路径");
        }
        // 5.组装结果
        Map<String, Object> map = new HashMap<>();
        map.put("nextLocation", path.get(0).getIconName());
        map.put("isEnd", path.size() == 1);
        map.put("iconUrl", path.get(0).getIconImage());

        return JSONObject.from(map);


    }



}
