package com.clx.performance.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.clx.performance.dao.IntegralRecordDao;
import com.clx.performance.dao.IntegralStatisticsDao;
import com.clx.performance.dao.IntegralTruckDao;
import com.clx.performance.model.IntegralTruck;
import com.clx.performance.param.pc.PageIntegralStatisticsParam;
import com.clx.performance.param.pc.pageIntegralStatisticsDetailParam;
import com.clx.performance.service.IntegralStatisticsService;
import com.clx.performance.utils.LocalDateTimeUtils;
import com.clx.performance.vo.pc.IntegralRecordVO;
import com.clx.performance.vo.pc.IntegralStatisticsVO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
@AllArgsConstructor
public class IntegralStatisticsServiceImpl implements IntegralStatisticsService {

    private final IntegralStatisticsDao integralStatisticsDao;
    private final IntegralRecordDao integralRecordDao;
    private IntegralTruckDao integralTruckDao;



    @Override
    public IPage<IntegralStatisticsVO> pageStatisticsList(PageIntegralStatisticsParam param) {
        IPage<IntegralStatisticsVO> page = integralStatisticsDao.pageByParam(param);

        List<String> truckNoList = page.getRecords().stream().map(item -> item.getTruckNo()).collect(Collectors.toList());
        if (!truckNoList.isEmpty()) {
            List<IntegralTruck> integralTruckList = integralTruckDao.listByTruckNoList(truckNoList);
            Map<String, Integer> echelonMap = integralTruckList.stream().collect(Collectors.toMap(item -> item.getTruckNo(), item -> item.getEchelon()));
            for (IntegralStatisticsVO item : page.getRecords()) {
                item.setEchelon(echelonMap.get(item.getTruckNo()));
            }
        }

        return page;

    }

    @Override
    public IPage<IntegralRecordVO> pageStatisticsDetailList(pageIntegralStatisticsDetailParam param) {
        return integralRecordDao.pageByParam(param);

    }

    /**
     * 新手积分计算
     */
    @Override
    public int protectionIntegralCalc(LocalDateTime statisticsDate) {
        int day = diffDay(statisticsDate, LocalDateTimeUtils.getDayStart());
        if (day >= 7) {return 0;}

        return (7-day)*30;
    }

    @Override
    public int protectionIntegralCalc(LocalDateTime createTime, LocalDateTime statisticsDate){
        int day = diffDay(LocalDateTimeUtils.getDayStart(createTime), statisticsDate);
        if (day >= 7) {return 0;}

        return (7-day)*30;
    }

    private int diffDay(LocalDateTime beginDate, LocalDateTime endDate){
        long day = Duration.between(beginDate, endDate).toDays();

        return (int)day;
    }

}
