package com.zd.laboratory.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.zd.common.redis.service.RedisService;
import com.zd.laboratory.mapper.AlgorithmMapper;
import com.zd.laboratory.service.AlgorithmService;
import com.zd.system.api.domain.Algorithm;
import com.zd.system.api.domain.AlgorithmVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

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

/**
 * @Author: zhoupan
 * @Date: 2021/11/29/10:32
 * @Description:
 */
@Service
public class AlgorithmServiceImpl implements AlgorithmService {

    Logger logger = LoggerFactory.getLogger(AlgorithmServiceImpl.class);

    @Autowired
    private RedisService redisService;

    @Autowired
    private AlgorithmMapper algorithmMapper;

    /**
     * 每10秒执行 取出算法解析结果
     */
    @Scheduled(fixedDelay = 10*1000)
    public void consumeLogList()
    {
        //这么弄肯定会丢数据， 以后有消息中间件 这里的逻辑要搬过去
        ListOperations<Object,Object> listOperations = redisService.redisTemplate.opsForList();
        List<Algorithm> list = new ArrayList<>();
        int size = 0;
        do {
            //每次最多只批量插入三条  返回的数据太大了
            if(list.size()>=3)
            {
                save(list);
                list.clear();
            }
            size = list.size();
            Algorithm algorithmResult = (Algorithm) listOperations.rightPop("AlgorithmResult");
            if(algorithmResult!=null) list.add(algorithmResult);
            //数据太大了需要分批次处理
            //首先需要解决 sql 插入的大小限制
            //＂max_allowed_packet = 1M＂

        }
        while (list.size()>size);
        save(list);

    }

    /**
     * 批量保存
     * @param list
     */
    public void save(List<Algorithm> list)
    {
        if(CollUtil.isNotEmpty(list))
        {
            algorithmMapper.insertBatchAlgorithm(list);

        }

    }


    @Override
    public List<AlgorithmVO> queryList(AlgorithmVO algorithm) {

        return algorithmMapper.queryList(algorithm);
    }


    @Override
    public Object saveData(Algorithm algorithm) {
        List<Algorithm> list = new ArrayList<>();
        list.add(algorithm);
        return algorithmMapper.insertBatchAlgorithm(list);
    }

    @Override
    public Algorithm getId(Long id) {

        return algorithmMapper.getId(id);
    }

    @Override
    public int update(Algorithm algorithm) {
        return algorithmMapper.update(algorithm);
    }

    @Override
    public int del(Long id) {
        return algorithmMapper.del(id);
    }
}
