package com.wuban.tron.explore.service.impl;

import com.wuban.tron.explore.dao.AddressRepository;
import com.wuban.tron.explore.dao.CensusRepository;
import com.wuban.tron.explore.entity.Census;
import com.wuban.tron.explore.service.CensusService;
import com.wuban.tron.explore.util.BigDecimalUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <core>数据统计接口实现类</core>
 *
 * @author sky
 * @date 2020/11/24
 */
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CensusServiceImpl implements CensusService {

    private final CensusRepository censusRepository;

    private final AddressRepository addressRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateCensus(Census census) {
        Census obj = this.censusRepository.selectOneByExample(null);
        if (obj == null) {
            this.censusRepository.insert(census);
            return;
        }

        long totalTrans = 0;
        if (census.getTotalTrans() != null) {
            totalTrans = obj.getTotalTrans() + census.getTotalTrans();
        }

        long totalBlockSize = 0;
        if (census.getTotalBlockSize() != null) {
            BigDecimal bg = BigDecimalUtil.getAdd(new BigDecimal(obj.getTotalBlockSize()), new BigDecimal(census.getTotalBlockSize()));
            totalBlockSize = bg.longValue();
        }

        if (totalTrans != 0) {
            obj.setTotalTrans(totalTrans);
        }

        if (totalBlockSize != 0) {
            obj.setTotalBlockSize(totalBlockSize);
        }

        this.censusRepository.updateById(obj);
    }

    @Override
    public void updateTotalAccount() {
        Integer totalAccount = this.addressRepository.countByPager(null);
        Census obj = this.censusRepository.selectOneByExample(null);

        Census census = new Census();
        if (obj == null) {
            census.setTotalTrans(0L);
            census.setTotalBlockSize(0L);
            census.setTotalAccount(Long.valueOf(totalAccount));
            this.censusRepository.insert(census);
            return;
        }

        obj.setTotalAccount(Long.valueOf(totalAccount));
        this.censusRepository.updateById(obj);
    }

    @Override
    public Census selectOneByExample() {
        return this.censusRepository.selectOneByExample(null);
    }


}
