package com.lutao.cloud.consume.factory;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.lutao.cloud.collect.vo.DataAddVO;
import com.lutao.cloud.common.core.kafka.MessageCommandEnum;
import com.lutao.cloud.common.core.util.MessageInfo;
import com.lutao.cloud.consume.service.AtmosphereMonitorInfoService;
import com.lutao.entity.AtmosphereMonitorInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 感知监测信息
 *
 * @author yx
 * @date 2023/07/21
 */
@Component
@Slf4j
public class AtmosphereMonitorInfoStrategy implements CommandStrategy<AtmosphereMonitorInfo> {

    @Resource
    private AtmosphereMonitorInfoService atmosphereMonitorInfoService;

    private static AtmosphereMonitorInfoStrategy atmosphereMonitorInfoStrategy;

    private List<AtmosphereMonitorInfo> atmosphereMonitorInfos = new ArrayList<>();


    @PostConstruct
    public void init() {
        atmosphereMonitorInfoStrategy = this;
        atmosphereMonitorInfoStrategy.atmosphereMonitorInfoService = this.atmosphereMonitorInfoService;
        atmosphereMonitorInfoStrategy.atmosphereMonitorInfos = this.atmosphereMonitorInfos;
    }

    @Override
    public MessageInfo execute(String command, JsonNode data, DataAddVO dataAddVO) {
        if (MessageCommandEnum.MESSAGE_ADD.getCommand().equals(command)) {
            AtmosphereMonitorInfo atmosphereMonitorInfo = JSONUtil.toBean(data.toString(), AtmosphereMonitorInfo.class);
            atmosphereMonitorInfo.setAppId(dataAddVO.getAppId());
            log.info("AtmosphereMonitorInfoStrategy 进行add操作 ......");
            atmosphereMonitorInfoStrategy.atmosphereMonitorInfoService.save(atmosphereMonitorInfo);
        }

        return MessageInfo.ok();

    }

    @Override
    public MessageInfo executeBatch(List<DataAddVO> dataAddVOS) {

        for (DataAddVO dataAddVO : dataAddVOS) {
            AtmosphereMonitorInfo atmosphereMonitorInfo = JSONUtil.toBean(dataAddVO.getJsonDate().toString(), AtmosphereMonitorInfo.class);
            atmosphereMonitorInfo.setAppId(dataAddVO.getAppId());
            atmosphereMonitorInfos.add(atmosphereMonitorInfo);
        }

        String command = dataAddVOS.get(0).getCommand();

        if (MessageCommandEnum.MESSAGE_ADD.getCommand().equals(command)) {
            log.info("AtmosphereMonitorInfoStrategy 进行add-Batch操作 ......");
            atmosphereMonitorInfoStrategy.atmosphereMonitorInfoService.saveBatch(atmosphereMonitorInfos);
        }

        return MessageInfo.ok();
    }
}
