package com.yonge.cooleshow.biz.dal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonge.cooleshow.biz.dal.entity.TenantPersonStat;
import com.yonge.cooleshow.biz.dal.mapper.TenantPersonStatMapper;
import com.yonge.cooleshow.biz.dal.service.TenantPersonStatService;
import com.yonge.cooleshow.biz.dal.wrapper.TenantPersonStatWrapper;
import com.yonge.toolset.utils.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 机构人员信息统计
 * 2023-07-25 10:43:00
 */
@Slf4j
@Service
public class TenantPersonStatServiceImpl extends ServiceImpl<TenantPersonStatMapper, TenantPersonStat> implements TenantPersonStatService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void tenantPersonStatTask() {
        Date date = DateUtil.addDays(new Date(), -1);
        String day = DateUtil.format(date, DateUtil.DEFAULT_PATTERN);
        String month = DateUtil.format(date,DateUtil.ISO_YEAR_MONTH_FORMAT);
        this.lambdaUpdate().eq(TenantPersonStat::getMonth,month).remove();
        String year = DateUtil.getYear(date);
        //获取初始化数据
        List<TenantPersonStat> stats = baseMapper.init();
        if(CollectionUtils.isNotEmpty(stats)){
            stats.stream().forEach(e->{
                e.setDay(day);
                e.setMonth(month);
                e.setYear(year);
            });
            this.saveBatch(stats);
        }
    }

    @Override
    public TenantPersonStatWrapper.TenantPersonStatSum indexSum(TenantPersonStatWrapper.TenantPersonStatQuery query) {
        //获取时间周期，以及分组条件
        List<String> dates = this.getDates(query);
        List<TenantPersonStatWrapper.TenantPersonStatDto> vos = baseMapper.indexSum(query);

        Map<String, TenantPersonStatWrapper.TenantPersonStatDto> dateMap = vos.stream()
                .collect(Collectors.toMap(TenantPersonStatWrapper.TenantPersonStatDto::getDate, Function.identity()));
        Set<String> keySet = dateMap.keySet();
        // 遍历日期列表，补全数据并添加到结果集中
        List<TenantPersonStatWrapper.TenantPersonStatDto> dtos = new ArrayList<>();
        for (String date : dates) {
            if (keySet.contains(date)) {
                //如果存在对应日期的数据，则添加到结果集中
                dtos.add(dateMap.get(date));
            } else {
                // 如果不存在对应日期的数据
                TenantPersonStatWrapper.TenantPersonStatDto dto = new TenantPersonStatWrapper.TenantPersonStatDto();
                dto.setDate(date);
                dtos.add(dto);
            }
        }
        return new TenantPersonStatWrapper.TenantPersonStatSum(baseMapper.sumByNow(query.getTenantId()),dtos);
    }

    private List<String> getDates(TenantPersonStatWrapper.TenantPersonStatQuery query){
        Date startTime = DateUtil.stringToDate(query.getStartTime(),DateUtil.DEFAULT_PATTERN);
        Date endTime = DateUtil.stringToDate(query.getEndTime(),DateUtil.DEFAULT_PATTERN);
        List<String> dates;
        if(DateUtil.daysBetween(startTime, endTime) <= 31){
            query.setGroupBy("day_");
            query.setFormat("%d日");
            dates = DateUtil.getDatesBetweenByDay(startTime, endTime);
        } else if (DateUtil.monthsBetween(startTime, endTime) <= 12) {
            query.setGroupBy("month_");
            query.setFormat("%m月");
            dates = DateUtil.getDatesBetweenByMonth(startTime, endTime);
        }else {
            query.setGroupBy("year_");
            query.setFormat("%Y年");
            dates = DateUtil.getDatesBetweenByYear(startTime, endTime);
        }
        return dates;
    }
}