package com.muyu.cloud.vehicle.gateway.service.impl;

import com.muyu.cloud.vehicle.gateway.domain.VehicleConnection;
import com.muyu.cloud.vehicle.gateway.domain.VinIp;
import com.muyu.cloud.vehicle.gateway.domain.model.MqttServerModel;
import com.muyu.cloud.vehicle.gateway.domain.req.VehicleConnectionReq;
import com.muyu.cloud.vehicle.gateway.mapper.VehicleConnectionMapper;
import com.muyu.cloud.vehicle.gateway.service.VehicleConnectionService;
import com.muyu.common.core.domain.Result;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Log4j2
@Service
public class VehicleConnectionServiceImpl implements VehicleConnectionService {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private VehicleConnectionMapper vehicleConnectionMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 获取连接信息
     * @param vehicleConnectionReq 车辆连接请求参数
     * @return
     */
    @Override
    public Result<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());
        //添加连接信息
        vehicleConnectionMapper.addConnect(vehicleConnection);
        //先判断vin码
        HashOperations<String, String, String> hashOps = redisTemplate.opsForHash();
        String vinIp = hashOps.get("vinIp", vehicleConnectionReq.getVehicleVin());
        if(vinIp!=null){
            log.info("车辆绑定ip失败，已经存在");
            throw new RuntimeException("车辆绑定ip失败，已经存在");
        }

        //判断redis有没有count键
        if(redisTemplate.hasKey("count")){
            //取出count
            Integer count = Integer.valueOf(redisTemplate.opsForValue().get("count"));
            if(count == 1){
                redisTemplate.opsForValue().set("count",String.valueOf(0));
            }else {
                redisTemplate.opsForValue().set("count",String.valueOf(count+1));
            }
            //根据游标count获取服务IP
            String ip = redisTemplate.opsForList().index("ipList", count);
            //关联车辆和服务
            this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ip));
            //响应信息
            log.info("车辆:{}",vehicleConnectionReq.getVehicleVin()+"绑定成功:{}",ip);
            return Result.success(new MqttServerModel("tcp://"+ip+":1883","vehicle"));

        }else {
            redisTemplate.opsForValue().set("count",String.valueOf(0));
            //根据游标count获取服务器Ip
            String ip = redisTemplate.opsForList().index("ipList", 0);
            //关联车辆和服务
            this.addIpAddress(new VinIp(vehicleConnectionReq.getVehicleVin(),ip));
            //响应信息
            log.info("车辆:{}",vehicleConnectionReq.getVehicleVin(),"与:{}绑定成功",ip);
            return Result.success(new MqttServerModel("tcp://"+ip+":1883","vehicle"));
        }
    }
    /**
     * 添加车辆绑定IP地址存入redis中
     */
    public void addIpAddress(VinIp vinIp) {
        if (vinIp == null || vinIp.getVin() == null || vinIp.getVin().isEmpty() || vinIp.getIp() == null || vinIp.getIp().isEmpty()) {
            throw new IllegalArgumentException("vin 或 ip 不能为空或无效");
        }
        redisTemplate.opsForHash().put("vinIp", vinIp.getVin(), vinIp.getIp());
    }
}
