package com.clx.performance.service.impl;

import com.clx.performance.dao.IntegralRecordDao;
import com.clx.performance.dao.IntegralStatisticsDao;
import com.clx.performance.dao.IntegralTruckDao;
import com.clx.performance.enums.PerformanceResultEnum;
import com.clx.performance.enums.integral.IntegralRecordEnum;
import com.clx.performance.model.IntegralRecord;
import com.clx.performance.model.IntegralStatistics;
import com.clx.performance.model.IntegralTruck;
import com.clx.performance.param.pc.IntegralRecordAddParam;
import com.clx.performance.service.IntegralMqService;
import com.clx.performance.service.IntegralRecordService;
import com.clx.performance.service.integral.IntegralRuleService;
import com.clx.performance.utils.LocalDateTimeUtils;
import com.clx.performance.vo.pc.integral.AppIntegralRuleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;

@Slf4j
@Service
public class IntegralRecordServiceImpl implements IntegralRecordService {

    @Autowired
    private IntegralRecordDao integralRecordDao;

    @Autowired
    private IntegralTruckDao integralTruckDao;

    @Autowired
    private IntegralStatisticsDao integralStatisticsDao;

    @Autowired
    private IntegralMqService integralMqService;
    @Autowired
    private IntegralRuleService integralRuleService;

    @Override
    public void addDriverReportRecord(IntegralRecordAddParam param) {
        String statisticsDate = LocalDateTimeUtils.getWeekStart();

        IntegralTruck truck = integralTruckDao.getByTruckNo(param.getTruckNo()).orElseThrow(PerformanceResultEnum.INTEGRAL_TRUCK_NO_EXIST);

        // 查找最新统计
        IntegralStatistics statistics = integralStatisticsDao.selectByTruckNoAndStatisticsDate(param.getTruckNo(), statisticsDate).orElseThrow(PerformanceResultEnum.INTEGRAL_TRUCK_NO_EXIST);

        // 更新积分
        statistics.setIntegral(statistics.getIntegral()+param.getIntegral());
        integralStatisticsDao.updateIntegral(statistics);

        truck.setIntegral(statistics.getIntegral());
        integralTruckDao.updateIntegral(truck);

        // 新增积分记录
        IntegralRecord record = save(statistics.getId(), statistics.getStatisticsDate(), statistics.getTruckNo(), IntegralRecordEnum.Type.SYSTEM.getValue(), param.getIntegral(), param.getRemark());

        // 发送mq (新增积分记录)
        integralMqService.integralRecordAdd(record.getStatisticsId(), record.getTruckNo(), record.getType(), record.getIntegral(), record.getRemark());

    }

    @Override
    public void addDriverReportRecord(AppIntegralRuleVO ruleInfo, String truckNo, Integer type, Integer integral, String remark) {
        String statisticsDate = LocalDateTimeUtils.getWeekStart();

        IntegralTruck truck = integralTruckDao.getByTruckNo(truckNo).orNull();
        if (truck == null) {return;}

        // 查找最新统计
        IntegralStatistics statistics = integralStatisticsDao.selectByTruckNoAndStatisticsDate(truckNo, statisticsDate).orNull();
        if (statistics == null) {return;}

        IntegralRecord integralRecord = integralRecordDao.selectByStatisticsIdAndType(statistics.getId(), type);
        if (integralRecord != null
                && integralRecord.getCreateTime().plusSeconds(ruleInfo.getDriverReportRule().getReportLimit().multiply(new BigDecimal(3600)).intValue()).isAfter(LocalDateTime.now())){
            log.info("上报频繁，本次无效， truckNo:{}, type:{}, integral:{}, remark:{}", truckNo, type, integral, remark);
            return;
        }

        Integer sum = integralRecordDao.sumByStatisticsIdAndTypes(statistics.getId(), IntegralRecordEnum.DRIVER_REPORT_lIST);
        if (sum == null) {sum = 0;}
        if (sum > ruleInfo.getDriverReportRule().getIntegralLimit()){
            log.info("上报积分超上限，本次无效， truckNo:{}, type:{}, integral:{}, remark:{}", truckNo, type, integral, remark);
            return;
        }

        // 更新积分
        statistics.setIntegral(statistics.getIntegral()+integral);
        integralStatisticsDao.updateIntegral(statistics);

        truck.setIntegral(statistics.getIntegral());
        integralTruckDao.updateIntegral(truck);

        // 新增积分记录
        IntegralRecord record = save(statistics.getId(), statistics.getStatisticsDate(), statistics.getTruckNo(), type, integral, remark);

        // 发送mq (新增积分记录)
        integralMqService.integralRecordAdd(record.getStatisticsId(), record.getTruckNo(), record.getType(), record.getIntegral(), record.getRemark());

    }

    @Override
    public void addDriverTruckReportRecord(AppIntegralRuleVO ruleInfo, String truckNo, Integer type, Integer integral, String remark) {
        String statisticsDate = LocalDateTimeUtils.getWeekStart();

        IntegralTruck truck = integralTruckDao.getByTruckNo(truckNo).orNull();
        if (truck == null) {return;}

        // 查找最新统计
        IntegralStatistics statistics = integralStatisticsDao.selectByTruckNoAndStatisticsDate(truckNo, statisticsDate).orNull();
        if (statistics == null) {return;}

        int exist = integralRecordDao.existByTruckNoAndType(truckNo, type);
        if (exist > 0){
            log.info("上报积分重复，本次无效， truckNo:{}, type:{}, integral:{}, remark:{}", truckNo, type, integral, remark);
            return;
        }

        // 更新积分
        statistics.setIntegral(statistics.getIntegral()+integral);
        integralStatisticsDao.updateIntegral(statistics);

        truck.setIntegral(statistics.getIntegral());
        integralTruckDao.updateIntegral(truck);

        // 新增积分记录
        IntegralRecord record = save(statistics.getId(), statistics.getStatisticsDate(), statistics.getTruckNo(), type, integral, remark);

        // 发送mq (新增积分记录)
        integralMqService.integralRecordAdd(record.getStatisticsId(), record.getTruckNo(), record.getType(), record.getIntegral(), record.getRemark());

    }

    @Override
    public void addPlatformCompensationRecord(String truckNo) {

        // 查找规则
        AppIntegralRuleVO ruleInfo = integralRuleService.getRuleInfo();

        Integer type = IntegralRecordEnum.Type.ORDER_CHILD_PLATFORM_COMPENSATION.getValue();
        Integer integral = ruleInfo.getPlatformCompensationRule().getIntegralCancel();
        String remark = IntegralRecordEnum.Type.ORDER_CHILD_PLATFORM_COMPENSATION.getMsg();

        String statisticsDate = LocalDateTimeUtils.getWeekStart();

        IntegralTruck truck = integralTruckDao.getByTruckNo(truckNo).orNull();
        if (truck == null) {return;}

        // 查找最新统计
        IntegralStatistics statistics = integralStatisticsDao.selectByTruckNoAndStatisticsDate(truckNo, statisticsDate).orNull();
        if (statistics == null) {return;}

        Integer sum = integralRecordDao.sumByStatisticsIdAndTypes(statistics.getId(), Arrays.asList(IntegralRecordEnum.Type.ORDER_CHILD_PLATFORM_COMPENSATION.getValue()));
        if (sum == null) {sum = 0;}
        if (sum > ruleInfo.getPlatformCompensationRule().getIntegralCancelLimit()){
            log.info("平台补偿超上限，本次无效， truckNo:{}, type:{}, integral:{}, remark:{}", truckNo, type, integral, remark);
            return;
        }
        else if (sum+integral > ruleInfo.getPlatformCompensationRule().getIntegralCancelLimit()){
            integral = ruleInfo.getPlatformCompensationRule().getIntegralCancelLimit()-sum;
        }
        else {

        }

        // 更新积分
        statistics.setIntegral(statistics.getIntegral()+integral);
        integralStatisticsDao.updateIntegral(statistics);

        truck.setIntegral(statistics.getIntegral());
        integralTruckDao.updateIntegral(truck);

        // 新增积分记录
        IntegralRecord record = save(statistics.getId(), statistics.getStatisticsDate(), statistics.getTruckNo(), type, integral, remark);

        // 发送mq (新增积分记录)
        integralMqService.integralRecordAdd(record.getStatisticsId(), record.getTruckNo(), record.getType(), record.getIntegral(), record.getRemark());

    }

    @Override
    public IntegralRecord save(Integer statisticsId, LocalDateTime statisticsDate, String truckNo, Integer type, Integer integral, String remark){
        IntegralRecord record = new IntegralRecord();
        record.setStatisticsId(statisticsId);
        record.setStatisticsDate(statisticsDate);
        record.setTruckNo(truckNo);
        record.setType(type);
        record.setIntegral(integral);
        record.setRemark(remark);

        // 新增记录
        integralRecordDao.saveEntity(record);

        return record;
    }

}
