package jnpf.attendance.service.impl;

import jnpf.attendance.mapper.InitializationMapper;
import jnpf.attendance.mapper.StorageRestMapper;
import jnpf.attendance.service.InitializationService;
import jnpf.entity.attendance.AttendanceStorageRest;
import jnpf.model.attendance.vo.AttendanceBalanceRecordVo;
import jnpf.model.attendance.vo.attendance.BalanceUseRecordVo;
import jnpf.util.DateDetail;
import jnpf.util.FtbUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author huanglinpan
 * @Date 2024/7/1 9:16
 * @Version 1.0 （版本号）
 */
@Service
public class InitializationServiceImpl implements InitializationService {

    @Resource
    private InitializationMapper initializationMapper;

    @Resource
    private StorageRestMapper storageRestMapper;


    @Override
    @Deprecated
    public Integer storageRest() {
        DateDetail dateDetail = new DateDetail();
        SimpleDateFormat Y_M = new SimpleDateFormat("yyyy-MM");
        SimpleDateFormat Y_M_D = new SimpleDateFormat("yyyy-MM-dd");
        // 该代码段用于获取当前时间的上一个月的年-月格式字符串
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        // 获取上个月的年月
        String lastMonthDate = Y_M.format(calendar.getTime());
        // 初始化表
        initializationMapper.truncatStorageRest();
        // 查出用户拥有的劵余额
        List<AttendanceBalanceRecordVo> allBalance = initializationMapper.getBalanceRecord();
        // 查出用户拥有的劵使用记录
        List<BalanceUseRecordVo> allBalanceUseRecord = initializationMapper.getAllBalanceUseRecord();
        // 过滤出所有的用户
        List<String> userIds = allBalance.stream().map(AttendanceBalanceRecordVo::getUserId).distinct().collect(Collectors.toList());
        // 通过用户进行分组
        Map<String, List<AttendanceBalanceRecordVo>> allBalanceMap = allBalance.stream().collect(Collectors.groupingBy(AttendanceBalanceRecordVo::getUserId));
        Map<String, List<BalanceUseRecordVo>> allBalanceUseMap = allBalanceUseRecord.stream().collect(Collectors.groupingBy(BalanceUseRecordVo::getBalanceId));
        List<AttendanceStorageRest> list = new ArrayList<>();
        // 处理用户数据
        allBalanceMap.forEach((key, value) -> {
            // 获取数据集合中最小的创建时间日期
            AttendanceBalanceRecordVo min = Collections.min(value, Comparator.comparing(AttendanceBalanceRecordVo::getCreatorTimeStr));
            String minYM = Y_M.format(min.getCreatortime());
            List<String> monthsBetweenStr = DateDetail.getMonthsBetweenStr(minYM, lastMonthDate);
            monthsBetweenStr.forEach(month -> {
                // 月底最后一天
                String lastDayOfMonthStr = dateDetail.getLastDayOfMonthStr(month);
                Date lastDayOfMonth = null;
                try {
                    lastDayOfMonth = Y_M_D.parse(lastDayOfMonthStr);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
                Date finalLastDayOfMonth = lastDayOfMonth;
                // 过滤出创建时间小于月末并且（过期时间为空或者过期时间大于月末）的数据
                List<AttendanceBalanceRecordVo> recordVos = value.stream().filter(t -> t.getCreatortime().before(finalLastDayOfMonth) && (null == t.getExpireTime() || t.getExpireTime().after(finalLastDayOfMonth))).collect(Collectors.toList());
                // 遍历处理数据 计算余额
                BigDecimal num = new BigDecimal("0.00");
                if (!recordVos.isEmpty()) {
                    // 找出有使用记录的劵记录
                    for (AttendanceBalanceRecordVo recordVo : recordVos) {
                        List<BalanceUseRecordVo> balanceUseRecordVos = allBalanceUseMap.get(recordVo.getId());
                        // 查看有无使用记录
                        if (null != balanceUseRecordVos){
                            // 有使用记录，找到月末前的记录
                            List<BalanceUseRecordVo> useRecordVos = balanceUseRecordVos.stream().filter(t1 -> t1.getCreatorTime().before(finalLastDayOfMonth)).collect(Collectors.toList());
                            if (!useRecordVos.isEmpty()){
                                // 用户时间前使用额度
                                BigDecimal balanceNum = new BigDecimal("0.00");
                                for (BalanceUseRecordVo useRecordVo : useRecordVos) {
                                    balanceNum = balanceNum.add(useRecordVo.getQuota());
                                }
                                // 未使用额度 劵总额 - 已使用额度
                                BigDecimal subtract = recordVo.getTotal().subtract(balanceNum);
                                num = num.add(subtract);
                            }else {
                                // 没有使用记录
                                num = num.add(recordVo.getTotal());
                            }
                        }else {
                            // 没有记录，将劵余额相加
                            num = num.add(recordVo.getTotal());
                        }
                    }
                }
                AttendanceStorageRest attendanceStorageRest = new AttendanceStorageRest();
                attendanceStorageRest.setId(FtbUtil.getId());
                attendanceStorageRest.setUserId(key);
                attendanceStorageRest.setYearMonth(month);
                attendanceStorageRest.setNum(num);
                list.add(attendanceStorageRest);
            });
        });
        if (!list.isEmpty()) {
            // 批量保存存休信息
            storageRestMapper.saveBatch(list);
            return list.size();
        }
        return 0;
    }

}
