package org.dromara.elevator.service.message.impl;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.elevator.domain.bo.EFaultMessageBo;
import org.dromara.elevator.domain.message.DevFaultReq;
import org.dromara.elevator.domain.vo.EElevatorInfoVo;
import org.dromara.elevator.service.IEElevatorInfoService;
import org.dromara.elevator.service.message.FaultService;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;

import static org.dromara.elevator.constant.TopicConstant.ELEVATOR_FAULT_TOPIC;

/**
 * 故障消息实现
 *
 * @author ym
 * @version 1.0.0
 * @date 2024-08-21 16:09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class FaultServiceImpl implements FaultService {

    private final KafkaTemplate<String, String> kafkaTemplate;

    private final IEElevatorInfoService elevatorInfoService;

    @Override
    public void pushDevFault(DevFaultReq req) {
        DevFaultReq.DevFaultInfo faultInfo = req.getMsg().getObj();
        if (Objects.isNull(faultInfo)) {
            return;
        }
        EElevatorInfoVo info = elevatorInfoService.selectByElevatorNum(faultInfo.getElevatorCode());
        if (Objects.isNull(info)) {
            log.info("故障消息,电梯编号:{}, 未查询到相关数据", faultInfo.getElevatorCode());
            return;
        }
        // 接收消息推到 Kafka
        EFaultMessageBo faultMessageBo = new EFaultMessageBo();
        faultMessageBo.setCreateBy(1L);
        faultMessageBo.setDeviceCode(faultInfo.getCode());
        faultMessageBo.setFaultCode(faultInfo.getFaultCode());
        faultMessageBo.setFaultName(faultInfo.getFaultName());
        faultMessageBo.setElevatorNum(faultInfo.getElevatorCode());
        faultMessageBo.setElevatorName(info.getElevatorName());
        faultMessageBo.setRegisterCode(info.getRegisterCode());
        faultMessageBo.setDeptId(info.getDeptId());
        faultMessageBo.setLat(info.getLat());
        faultMessageBo.setLng(info.getLng());
        faultMessageBo.setHappenTime(DateUtils.parseDate(faultInfo.getCreateTime()));
        faultMessageBo.setSource(String.valueOf(faultInfo.getResource()));
        faultMessageBo.setFloor(faultInfo.getFloor());
        faultMessageBo.setPicture(faultInfo.getPhoto());
        faultMessageBo.setFaultPushType(faultInfo.getType());
        faultMessageBo.setState(0);
        kafkaTemplate.send(ELEVATOR_FAULT_TOPIC, JsonUtils.toJsonString(faultMessageBo));
    }
}
