package com.xjrsoft.module.mqtt.car.service;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xjrsoft.common.mqtt.MqttSubscribe;
import com.xjrsoft.module.personnel.entity.CarParkRecords;
import com.xjrsoft.module.personnel.service.ICarParkRecordsService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.mqttv5.client.IMqttMessageListener;
import org.eclipse.paho.mqttv5.common.MqttMessage;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 修改车辆回调
 */
@Component
@MqttSubscribe(topic = "/car/park/records/timing")
@Slf4j
public class CarParkRecordsTiming implements IMqttMessageListener {
    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        try {
            ICarParkRecordsService carParkRecordsService = SpringUtil.getBean(ICarParkRecordsService.class);

            // 获取回复数据
            JSONArray jsonArray = JSONUtil.parseArray(message.toString());
            jsonArray.forEach(f -> {
                JSONArray data = JSONUtil.parseArray(f.toString());
                data.forEach(d -> {
                    JSONObject temp = JSONUtil.parseObj(d.toString());
                    CarParkRecords params = new CarParkRecords();
                    params.setCSyncId(temp.getInt("id"));
                    params.setRemark(temp.getStr("remark"));
                    params.setInPassing(temp.getInt("in_passing"));
                    params.setOutPassing(temp.getInt("out_passing"));
                    params.setCarNo(temp.getStr("car_no"));
                    params.setStatus(temp.getInt("status"));
                    params.setInTime(LocalDateTime.parse(temp.getStr("in_time"), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")));
                    params.setOutTime(LocalDateTime.parse(temp.getStr("out_time"), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")));

                    long count = carParkRecordsService.count(Wrappers.<CarParkRecords>lambdaQuery().eq(CarParkRecords::getCSyncId, params.getCSyncId()));
                    if (count == 0) {
                        carParkRecordsService.save(params);
                    } else {
                        carParkRecordsService.update(params, Wrappers.<CarParkRecords>lambdaUpdate().eq(CarParkRecords::getCSyncId, params.getCSyncId()));
                    }
                });
            });
        } catch (Exception e) {
            log.error(this.getClass().getName(), e.getMessage());
        }
    }
}
