package com.qmth.themis.business.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qmth.themis.business.dao.TERegionSummaryMapper;
import com.qmth.themis.business.entity.TERegionSummary;
import com.qmth.themis.business.service.TERegionSummaryService;
import com.qmth.themis.business.service.ThemisCacheService;
import com.qmth.themis.business.util.UidUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 地区统计表 服务实现类
 * </p>
 *
 * @author wangliang
 * @since 2023-10-27
 */
@Service
public class TERegionSummaryServiceImpl extends ServiceImpl<TERegionSummaryMapper, TERegionSummary> implements TERegionSummaryService {

    @Resource
    ThemisCacheService themisCacheService;

    /**
     * 保存地区统计信息
     *
     * @param examId
     * @param examActivityId
     */
    @Override
    public void regionSummary(Long examId, Long examActivityId) {
        List<TERegionSummary> teRegionSummaryList = this.baseMapper.regionSummary(examId, examActivityId);
        if (!CollectionUtils.isEmpty(teRegionSummaryList)) {
            for (TERegionSummary t : teRegionSummaryList) {
                TERegionSummary teRegionSummaryDb = this.getOne(new QueryWrapper<TERegionSummary>().lambda()
                        .eq(TERegionSummary::getCountry, t.getCountry())
                        .eq(TERegionSummary::getProvince, t.getProvince()));
                if (Objects.isNull(teRegionSummaryDb)) {
                    teRegionSummaryDb = new TERegionSummary();
                    BeanUtils.copyProperties(t, teRegionSummaryDb);
                    teRegionSummaryDb.setId(UidUtil.nextId());
                } else {
                    Long id = teRegionSummaryDb.getId();
                    BeanUtils.copyProperties(t, teRegionSummaryDb);
                    teRegionSummaryDb.setId(id);
                }
                this.saveOrUpdate(teRegionSummaryDb);
            }
            themisCacheService.updateRegionSummaryCache();
        }
    }
}
