package com.muyu.cargateway.service.Impl;

import com.muyu.cargateway.domain.VehicleConnection;
import com.muyu.cargateway.domain.VinIp;
import com.muyu.cargateway.domain.model.MqttServerModel;
import com.muyu.cargateway.domain.req.VehicleConnectionReq;
import com.muyu.cargateway.mapper.CarOneClickOperationMapper;
import com.muyu.cargateway.service.CarOneClickOperationService;
import com.muyu.common.redis.service.RedisService;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @ Tool：IntelliJ IDEA
 * @ Author：CHX
 * @ Date：2024-09-26-20:16
 * @ Version：1.0
 * @ Description：车辆一键操作业务实现层
 * @author Lenovo
 */
@Log4j2
@Service
public class CarOneClickOperationServiceImpl implements CarOneClickOperationService {

    @Autowired
    private CarOneClickOperationMapper carOneClickOperationMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisService redisService;

    /**
     * 获取连接信息
     * @param vehicleConnectionReq 车辆连接请求参数
     * @return
     */
    @Override
    public MqttServerModel getConnect(VehicleConnectionReq vehicleConnectionReq) {
        log.info("车辆连接请求:{}",vehicleConnectionReq.toString());

        // 使用交换机发送消息
        rabbitTemplate.convertAndSend("exchange_topics_inform","inform.#.email.#",vehicleConnectionReq.getVehicleVin());
        log.info("发送消息成功:{}",vehicleConnectionReq.getVehicleVin());


        VehicleConnection vehicleConnection = new VehicleConnection();
        //车辆vin
        vehicleConnection.setVehicleVin(vehicleConnectionReq.getVehicleVin());
        //用户名
        vehicleConnection.setUsername(vehicleConnectionReq.getUsername());
        //密码(vin+时间戳+随机数)
        vehicleConnection.setPassword(vehicleConnectionReq.getVehicleVin()+vehicleConnectionReq.getTimestamp()+vehicleConnectionReq.getNonce());
        //查询车辆vin集合
        List<String> vehicleConnections =carOneClickOperationMapper.selectByVehicleVin(vehicleConnectionReq.getVehicleVin());
        if(vehicleConnections.isEmpty()){
            //添加
            carOneClickOperationMapper.addConnect(vehicleConnection);
        }
        log.info("该车辆已存在,不能重复预上线");
        //TODO 返回连接信息 做轮询操作


        return new MqttServerModel("tcp://"+"106.15.136.7"+":1883","vehicle");

    }
    /**
     * 添加车辆绑定IP地址存入redis中
     */
    public void addIpAddress(VinIp vinIp){
        redisService.setCacheObject("vehicle_ip_address:"+vinIp.getVehicleVin(),vinIp.getIpAddress());
    }

}
