package com.yeejoin.amos.boot.module.ccs.biz.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.github.xiaoymin.knife4j.core.util.StrUtil;
import com.yeejoin.amos.boot.module.ccs.api.entity.FireEquipmentSignalLog;
import com.yeejoin.amos.boot.module.ccs.api.service.MqttReceiveService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class MqttReceiveServiceImpl implements MqttReceiveService {


	private static Boolean bool = Boolean.FALSE;

	@Autowired
	private FireEquipmentSignalLogServiceImpl fireEquipmentSignalLogServiceImpl;


	//TODO 逻辑待补充
	@Override
	public void handlerMqttIncrementMessage(String topic, String message) {
		List<Map<String, String>> list = new ArrayList<>();
		try {
			list = (List<Map<String, String>>) JSONArray.parseObject(message, List.class);
			// 将JSON字符串转换成实体类型
//			List<FireEquipmentSignalLog> log = JSONUtil.toBean(message, FireEquipmentSignalLog.class);
		} catch (Exception e) {
			log.error("解析失败");
			throw new BadRequest("解析失败");
		}
		if (CollectionUtils.isNotEmpty(list)) {
			List<FireEquipmentSignalLog> doList = new ArrayList<>();
			for (Map<String, String> stringStringMap : list) {
				FireEquipmentSignalLog fireEquipmentSignalLog = new FireEquipmentSignalLog();
				if (stringStringMap.containsKey("objcect_type") && StrUtil.isNotBlank(stringStringMap.get("objcect_type"))) {
					if (!stringStringMap.get("objcect_type").equals("EQUIP")) {
						continue;
					}
				}
				//当为告警时新增数据
				doList.add(fireEquipmentSignalLog);
				//当为消除告警时修改原有数据 （根据设备编码、）
			}
			if (CollectionUtils.isNotEmpty(doList)) {
				fireEquipmentSignalLogServiceImpl.saveBatchLog(doList);
			}
		}
		log.info(String.format("收到mqtt消息：%s", message));
	}
}
