
package com.cmvr.inspection.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import cmvr.api.AgvCommand;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cmvr.common.utils.SecurityUtils;
import com.cmvr.device.domain.DeDeviceTerminalConfig;
import com.cmvr.device.service.IDeDeviceTerminalConfigService;
import com.cmvr.edge.client.model.EdgeCommonVO;
import com.cmvr.edge.client.service.EdgeAgvService;
import com.cmvr.inspection.domain.InspectionMap;
import com.cmvr.inspection.domain.vo.InspectionRobotVo;
import com.cmvr.inspection.mapper.InspectionMapMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cmvr.common.utils.DateUtils;
import com.cmvr.inspection.mapper.InspectionRobotMapper;
import com.cmvr.inspection.domain.InspectionRobot;
import com.cmvr.inspection.service.IInspectionRobotService;
import cn.hutool.core.util.StrUtil;
import com.cmvr.common.exception.GlobalException;

/**
 * 巡检机器人Service业务层处理
 *
 * @author cmvr-iot
 * @since 2026-05-29
 */
@Service
public class InspectionRobotServiceImpl extends ServiceImpl<InspectionRobotMapper, InspectionRobot> implements IInspectionRobotService
{
    @Autowired
    private InspectionRobotMapper inspectionRobotMapper;

    @Autowired
    private InspectionMapMapper inspectionMapMapper;

    @Autowired
    private EdgeAgvService edgeAgvService;

    @Autowired
    private IDeDeviceTerminalConfigService deDeviceTerminalConfigService;

    /**
     * 查询巡检机器人
     *
     * @param id 巡检机器人主键
     * @return 巡检机器人
     */
    @Override
    public InspectionRobot selectInspectionRobotById(String id)
    {
        return inspectionRobotMapper.selectInspectionRobotById(id);
    }

    /**
     * 查询巡检机器人列表
     *
     * @param inspectionRobot 巡检机器人
     * @return 巡检机器人
     */
    @Override
    public List<InspectionRobotVo> selectInspectionRobotList(InspectionRobot inspectionRobot)
    {
        return inspectionRobotMapper.selectInspectionRobotVoList(inspectionRobot);
    }

    /**
     * 新增巡检机器人
     *
     * @param inspectionRobot 巡检机器人
     * @return 结果
     */
    @Override
    public int insertInspectionRobot(InspectionRobot inspectionRobot)
    {
        DeDeviceTerminalConfig deDeviceTerminalConfig = new DeDeviceTerminalConfig();
        deDeviceTerminalConfig.setName(inspectionRobot.getRobotName());
        deDeviceTerminalConfig.setDescription("机器人终端");
        deDeviceTerminalConfig.setStatus("1");
        deDeviceTerminalConfig.setHost(inspectionRobot.getIpAddress());
        deDeviceTerminalConfig.setPort(inspectionRobot.getPort());
        // 自动创建设备管理模块的终端并将终端id保存机器人中
        deDeviceTerminalConfigService.insertDeDeviceTerminalConfig(deDeviceTerminalConfig);
        inspectionRobot.setTerminalId(deDeviceTerminalConfig.getId());
        // 生成UUID作为主键
        if (inspectionRobot.getId() == null || inspectionRobot.getId().isEmpty()) {
            inspectionRobot.setId(UUID.randomUUID().toString().replace("-", ""));
        }
        inspectionRobot.setCreateTime(DateUtils.getNowDate());
        inspectionRobot.setCreateBy(SecurityUtils.getUsername());
        return inspectionRobotMapper.insertInspectionRobot(inspectionRobot);
    }

    /**
     * 修改巡检机器人
     *
     * @param inspectionRobot 巡检机器人
     * @return 结果
     */
    @Override
    public int updateInspectionRobot(InspectionRobot inspectionRobot)
    {
        inspectionRobot.setUpdateTime(DateUtils.getNowDate());
        inspectionRobot.setUpdateBy(SecurityUtils.getUsername());
        DeDeviceTerminalConfig deDeviceTerminalConfig = deDeviceTerminalConfigService.selectDeDeviceTerminalConfigById(inspectionRobot.getTerminalId());
        deDeviceTerminalConfig.setName(inspectionRobot.getRobotName());
        deDeviceTerminalConfig.setHost(inspectionRobot.getIpAddress());
        deDeviceTerminalConfig.setPort(inspectionRobot.getPort());
        deDeviceTerminalConfigService.updateDeDeviceTerminalConfig(deDeviceTerminalConfig);
        return inspectionRobotMapper.updateInspectionRobot(inspectionRobot);
    }

    /**
     * 批量删除巡检机器人
     *
     * @param ids 需要删除的巡检机器人主键
     * @return 结果
     */
    @Override
    public int deleteInspectionRobotByIds(String[] ids)
    {
        List<InspectionRobot> inspectionRobots = inspectionRobotMapper.selectBatchIds(Arrays.asList(ids));
        deDeviceTerminalConfigService.deleteDeDeviceTerminalConfigByIds(inspectionRobots.stream().map(InspectionRobot::getTerminalId).toArray(String[]::new));
        return inspectionRobotMapper.deleteInspectionRobotByIds(ids);
    }

    /**
     * 获取机器人地图列表（从AGV获取）
     *
     * @param robotId 机器人ID
     * @return 地图状态信息
     */
    @Override
    public AgvCommand.AgvMapStatus getRobotMapList(String robotId)
    {
        InspectionRobot robot = inspectionRobotMapper.selectInspectionRobotById(robotId);
        if (robot == null) {
            throw new GlobalException("机器人不存在");
        }
        if (StrUtil.isBlank(robot.getIpAddress())) {
            throw new GlobalException("机器人IP地址未配置");
        }

        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setTerminalId(robot.getTerminalId());
        edgeCommonVO.setDeviceId(robot.getRobotCode());

        return edgeAgvService.getMapStatus(edgeCommonVO);
    }

    /**
     * 绑定机器人地图
     *
     * @param robotId 机器人ID
     * @param mapId 地图ID
     * @return 结果
     */
    @Override
    public int bindRobotMap(String robotId, String mapId)
    {
        InspectionRobot robot = inspectionRobotMapper.selectInspectionRobotById(robotId);
        if (robot == null) {
            throw new GlobalException("机器人不存在");
        }

        InspectionMap map = inspectionMapMapper.selectInspectionMapById(mapId);
        if (map == null) {
            throw new GlobalException("地图不存在");
        }

        robot.setCurrentMapId(mapId);
        robot.setUpdateTime(DateUtils.getNowDate());
        robot.setUpdateBy(SecurityUtils.getUsername());

        return inspectionRobotMapper.updateInspectionRobot(robot);
    }

    /**
     * 上传地图到机器人
     *
     * @param robotId 机器人ID
     * @param mapId 地图ID
     * @return 结果
     */
    @Override
    public String uploadMapToRobot(String robotId, String mapId)
    {
        InspectionRobot robot = inspectionRobotMapper.selectInspectionRobotById(robotId);
        if (robot == null) {
            throw new GlobalException("机器人不存在");
        }

        InspectionMap map = inspectionMapMapper.selectInspectionMapById(mapId);
        if (map == null) {
            throw new GlobalException("地图不存在");
        }

        if (StrUtil.isBlank(map.getMapFilePath())) {
            throw new GlobalException("地图文件路径不存在");
        }

        // TODO: 从文件路径读取地图内容
        // 这里需要根据实际存储方式实现
        String mapContent = readMapFile(map.getMapFilePath());

        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setTerminalId(robot.getTerminalId());
        edgeCommonVO.setDeviceId(robot.getRobotCode());

//        cmvr.api.AgvCommand.AgvUploadMapResult result = edgeAgvService.robotConfigUploadMap(edgeCommonVO, mapContent);
//
//        if (result.getRetCode() != 0) {
//            throw new GlobalException("上传地图失败: " + result.getErrMsg());
//        }

        return "上传成功";
    }

    /**
     * 从机器人下载地图
     *
     * @param robotId 机器人ID
     * @param mapName 地图名称
     * @return 地图ID
     */
    @Override
    public String downloadMapFromRobot(String robotId, String mapName)
    {
        InspectionRobot robot = inspectionRobotMapper.selectInspectionRobotById(robotId);
        if (robot == null) {
            throw new GlobalException("机器人不存在");
        }

        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setTerminalId(robot.getTerminalId());
        edgeCommonVO.setDeviceId(robot.getRobotCode());

        cmvr.api.AgvCommand.AgvDownloadMapResult result = edgeAgvService.robotConfigDownloadMap(edgeCommonVO, mapName);

        // 保存地图到数据库
//        InspectionMap inspectionMap = new InspectionMap();
//        inspectionMap.setId(UUID.randomUUID().toString().replace("-", ""));
//        inspectionMap.setMapName(mapName);
//        inspectionMap.setMapSourceRobotId(robotId);
//        inspectionMap.setMapSourceName(mapName);
//
//        // TODO: 将地图内容保存到文件系统，并返回文件路径
//        // String filePath = saveMapToFile(result.getMapContent(), mapName);
//        // inspectionMap.setMapFilePath(filePath);
//
//        inspectionMap.setStatus("0");
//        inspectionMap.setCreateTime(DateUtils.getNowDate());
//        inspectionMap.setCreateBy(SecurityUtils.getUsername());
//
//        inspectionMapMapper.insertInspectionMap(inspectionMap);




        return result.getMapContent();
    }

    /**
     * 同步机器人状态（电量、位置等）
     *
     * @param robotId 机器人ID
     * @return 更新后的机器人信息
     */
    @Override
    public InspectionRobot syncRobotStatus(String robotId)
    {
        InspectionRobot robot = inspectionRobotMapper.selectInspectionRobotById(robotId);
        if (robot == null) {
            throw new GlobalException("机器人不存在");
        }

        EdgeCommonVO edgeCommonVO = new EdgeCommonVO();
        edgeCommonVO.setTerminalId(robot.getTerminalId());
        edgeCommonVO.setDeviceId(robot.getRobotCode());

        try {
            // 获取电池状态
            cmvr.api.AgvCommand.AgvBatteryStatus batteryStatus = edgeAgvService.getBatteryStatus(edgeCommonVO);
            robot.setBatteryLevel((int)(batteryStatus.getBatteryLevel() * 100));

            // 获取位置信息
            cmvr.api.AgvCommand.AgvRobotLocation location = edgeAgvService.getRobotLocation(edgeCommonVO);
            robot.setCurrentPosition(location.getX() + "," + location.getY() + "," + location.getAngle());

            // 获取状态信息
            cmvr.api.AgvCommand.AgvStatusInfo statusInfo = edgeAgvService.getStatusInfo(edgeCommonVO);

            robot.setUpdateTime(DateUtils.getNowDate());
            inspectionRobotMapper.updateInspectionRobot(robot);

        } catch (Exception e) {
            // 记录日志但不抛出异常，允许部分失败
            e.printStackTrace();
        }

        return robot;
    }

    /**
     * 读取地图文件内容
     *
     * @param filePath 文件路径
     * @return 文件内容
     */
    private String readMapFile(String filePath)
    {
        // TODO: 实现文件读取逻辑
        return "";
    }

}