package com.hzjt.service;

import com.hzjt.domain.Traffalarmrecordstat;
import com.hzjt.mapper.TraffalarmrecordstatMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Service
public class AlarmRecordStatisticsService {
    private Map<String, Long> statisticsMap = new HashMap<>(16);
    private TraffalarmrecordstatMapper traffalarmrecordstatMapper;

    @Autowired
    public AlarmRecordStatisticsService(TraffalarmrecordstatMapper traffalarmrecordstatMapper) {
        this.traffalarmrecordstatMapper = traffalarmrecordstatMapper;
    }

    public synchronized void statistics(String key) {
        Long count = statisticsMap.putIfAbsent(key, 1L);
        if (count != null) {
            statisticsMap.put(key, ++count);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void statisticsToDb() {
        if (statisticsMap.isEmpty()) {
            return;
        }

        Map<String, Long> statisticsDbMap;
        synchronized (this) {
            statisticsDbMap = statisticsMap;
            statisticsMap = new HashMap<>(16);
        }
        Iterator<Map.Entry<String, Long>> iterator = statisticsDbMap.entrySet().iterator();
        if (iterator.hasNext()) {
            do {
                Map.Entry<String, Long> next = iterator.next();
                String key = next.getKey();
                Long count = next.getValue();
                String[] dataArr = key.split("&");
                Traffalarmrecordstat traffalarmrecordstat = new Traffalarmrecordstat();
                traffalarmrecordstat.setAreaid(dataArr[0]);
                traffalarmrecordstat.setFdid(dataArr[1]);
                traffalarmrecordstat.setChannelid(Integer.valueOf(dataArr[2]));
                traffalarmrecordstat.setEventtype(dataArr[3]);
                String countdate = dataArr[4];
                traffalarmrecordstat.setCountdate(Long.valueOf(countdate));
                Traffalarmrecordstat dbTraffalarmrecordstat = traffalarmrecordstatMapper.selectByPrimaryKey(traffalarmrecordstat);
                if (dbTraffalarmrecordstat == null) {
                    traffalarmrecordstat.setTotalcount(count);
                    traffalarmrecordstat.setCounthour(Integer.valueOf(countdate.substring(4, 6)));
                    traffalarmrecordstatMapper.insertSelective(traffalarmrecordstat);
                    continue;
                }
                dbTraffalarmrecordstat.setTotalcount(dbTraffalarmrecordstat.getTotalcount() + count);
                traffalarmrecordstatMapper.updateByPrimaryKeySelective(dbTraffalarmrecordstat);
            } while (iterator.hasNext());
        }
//        log.info("traffalarmrecordstat�������");
    }


}
