package cn.iocoder.yudao.module.system.api.robot;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.module.system.api.robot.dto.RobotGenericsDTO;
import cn.iocoder.yudao.module.system.api.robot.dto.RobotStatusDataPoseDTO;
import cn.iocoder.yudao.module.system.constant.robot.RobotTaskChcheConstant;
import cn.iocoder.yudao.module.system.util.redis.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Slf4j
@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
public class RobotGenericsStatusApiImpl implements RobotGenericsStatusApi {

    @Resource
    private RedisUtil redisUtil;

    @Resource@Value("${zn.robot_position_cache_time:600}")
    private Long robotPositionCacheTime;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Override
    public void updateRobotCommonStatus(RobotGenericsDTO robotStatusData) {
        taskExecutor.execute(() -> {
            doUpdateRobotCommonStatus(robotStatusData);
        });
    }

    public void doUpdateRobotCommonStatus(RobotGenericsDTO robotStatusData) {
        if (ObjectUtil.isEmpty(robotStatusData) || ObjectUtil.isEmpty(robotStatusData.getData())
                || ObjectUtil.isEmpty(robotStatusData.getData().getMac())) {
            log.info("参数不全 :{}", JSON.toJSONString(robotStatusData));
        }

        String mac = robotStatusData.getData().getMac();
        String pose2dKey = RobotTaskChcheConstant.ROBOT_INFORMATION_POSE_BAT_SOC +mac;

        Object object = redisUtil.get(pose2dKey);
        RobotStatusDataPoseDTO robotStatusDataPoseDTO= JSONUtil.toBean((String)object, RobotStatusDataPoseDTO.class);
        robotStatusDataPoseDTO.setArea(robotStatusData.getData().getZone());
        robotStatusDataPoseDTO.setFloor(robotStatusData.getData().getFloor());
        String batSoc = robotStatusData.getData().getHw_states().getBat_soc();
        if (ObjectUtil.isNotEmpty(batSoc)) {
            BigDecimal a = new BigDecimal(batSoc);
            BigDecimal b = new BigDecimal("100");
            BigDecimal multiply = a.multiply(b);
            robotStatusDataPoseDTO.setBat_soc(multiply.toString());
        }

        redisUtil.set(pose2dKey,JSON.toJSONString(robotStatusDataPoseDTO),robotPositionCacheTime);
    }
}
