package com.crm.manager.service.impl;

import com.alibaba.fastjson.JSON;
import com.crm.manager.dao.mapper.SalesRewardActivityMapper;
import com.crm.manager.dao.mapper.SalesSalaryRecordMapper;
import com.crm.manager.dao.repository.*;
import com.crm.manager.dto.export.SalesRewardStatisticsExportDto;
import com.crm.manager.service.SelesRewardService;
import com.crm.manager.service.SysConfigService;
import com.crm.manager.service.UserInfoService;
import com.crm.rely.backend.core.constant.*;
import com.crm.rely.backend.core.dto.base.PageDto;
import com.crm.rely.backend.core.dto.base.ResultWithPagerDto;
import com.crm.rely.backend.core.dto.sales.SalesRewardActivityDto;
import com.crm.rely.backend.core.dto.sales.SalesRewardDto;
import com.crm.rely.backend.core.dto.sales.SalesRewardStatisticsDto;
import com.crm.rely.backend.core.entity.base.SingleLongEntity;
import com.crm.rely.backend.core.entity.custom.info.InfoEntity;
import com.crm.rely.backend.core.entity.sales.SalesRewardDateConfigEntity;
import com.crm.rely.backend.core.entity.sales.SelesRewardActivityEntity;
import com.crm.rely.backend.core.entity.sales.SelesRewardStatisticsEntity;
import com.crm.rely.backend.core.entity.system.email.SysEmailSendEntity;
import com.crm.rely.backend.core.enums.SalesSalaryRecordType;
import com.crm.rely.backend.core.pojo.table.*;
import com.crm.rely.backend.exception.ServiceException;
import com.crm.rely.backend.service.EmailService;
import com.crm.rely.backend.util.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class SelesRewardServiceImpl implements SelesRewardService {

    @Autowired
    private SalesRewardActivityMapper salesRewardActivityMapper;
    @Autowired
    private AgentBalanceRecordRepository agentBalanceRecordRepository;
    @Autowired
    private UserInfoService uerInfoService;
    @Autowired
    private EmailService emailService;
    @Autowired
    private SalesRewardActivityRepository salesRewardActivityRepository;
    @Autowired
    private SysConfigService sysConfigService;
    @Autowired
    private SalesRewardStatisticsRepository salesRewardStatisticsRepository;
    @Autowired
    private SalesRewardRobotRepository salesRewardRobotRepository;
    @Autowired
    private SalesSalaryRecordMapper salesSalaryRecordMapper;
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Override
    public ResultWithPagerDto<List<SalesRewardStatisticsDto>> salesRewardStatistics(SelesRewardStatisticsEntity entity, InfoEntity infoEntity) throws Exception {
        Integer count = salesRewardActivityMapper.countSalesRewardStatisticsByMonth(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<SalesRewardStatisticsDto> list = salesRewardActivityMapper.salesRewardStatisticsByMonth(entity);
        if (list == null || list.size() <= 0) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }

        Integer subIndex = null;
        for (int i = 0; i < list.size(); i++) {
            SalesRewardStatisticsDto dto = list.get(i);
            dto.setSubIndex(entity.getPage().getOffset() + i + 1);
            if (infoEntity.getIbInfo().getId().equals(dto.getSalesId())) {
                subIndex = dto.getSubIndex();
            }
        }
        if ("ROLE_SALE".equals(infoEntity.getIbInfo().getRoteCode())) {
            SalesRewardStatisticsDto dto = null;
            entity.setSalesId(infoEntity.getIbInfo().getId());
            List<SalesRewardStatisticsDto> saleList = salesRewardActivityMapper.salesRewardStatisticsByMonth(entity);
            if (saleList != null && saleList.size() > 0) {
                dto = saleList.get(0);
                if (new BigDecimal(saleList.get(0).getDepositAmount()).compareTo(new BigDecimal(100)) >= 0 && subIndex == null) {
                    entity.setDepositAmount(dto.getDepositAmount());
                    Integer sub = salesRewardActivityMapper.salesSubIndexRewardStatisticsByMonth(entity);
                    dto.setSubIndex(sub);
                } else {
                    dto.setSubIndex(subIndex);
                }
            } else {
                dto = new SalesRewardStatisticsDto();
                dto.setSalesName(infoEntity.getIbInfo().getName());
                dto.setDepositAmount(0f);
                dto.setDepositCustomNum(0);
                dto.setTradeCustomNum(0);
                dto.setRewardAmount(0f);
                dto.setRewardAmountSum(0f);
            }
            list.add(dto);
        }

        return ResultWithPagerDto.success(pageDto, list);
    }

    @Override
    public List<SalesRewardStatisticsExportDto> searcherListExport(SelesRewardStatisticsEntity entity) throws Exception {
        entity.setPage(null);
        List<SalesRewardStatisticsDto> list = salesRewardActivityMapper.salesRewardStatisticsByMonth(entity);

        List<SalesRewardStatisticsExportDto> exportDtoList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            SalesRewardStatisticsDto dto = list.get(i);
            SalesRewardStatisticsExportDto exportDto = new SalesRewardStatisticsExportDto();
            BeanUtils.copyProperties(dto, exportDto);
            exportDto.setSubIndex(i + 1);
            exportDtoList.add(exportDto);
        }

        return exportDtoList;
    }


    @Override
    public ResultWithPagerDto<List<SalesRewardActivityDto>> searchPageList(SelesRewardActivityEntity entity) throws Exception {
        Integer count = salesRewardActivityMapper.countList(entity);
        PageDto pageDto = PageDto.format(entity, count);
        if (count == null || count <= 0) {
            return ResultWithPagerDto.success(pageDto);
        }
        List<SalesRewardActivityDto> list = salesRewardActivityMapper.pageList(entity);
        if (list == null || list.size() <= 0) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }

        return ResultWithPagerDto.success(pageDto, list);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deductionAmount(SingleLongEntity entity) throws Exception {
        SalesRewardActivityTable table = salesRewardActivityRepository.getFirstById(entity.getId());
        if (1 != table.getAmountType()) {
            throw new ServiceException(Constants.SYSTEM_ERROR);
        }

        table.setAmountType(2);
        salesRewardActivityRepository.save(table);

        SalesRewardActivityTable activityTable = new SalesRewardActivityTable();
        BeanUtils.copyProperties(table, activityTable);
        activityTable.setId(null);
        activityTable.setDepositAmount(table.getDepositAmount() == null ? null : -table.getDepositAmount());
        activityTable.setRewardAmount(-table.getRewardAmount());
        activityTable.setCustomNum(table.getCustomNum() == null ? null : -table.getCustomNum());
        activityTable.setAmountType(2);
        salesRewardActivityRepository.save(activityTable);

        Date rewardDate = activityTable.getRewardDate();
        Integer day = DateUtil.getDayOfWeek(rewardDate);
        if (1 != day) {
            rewardDate = DateUtil.addDate(rewardDate, 8 - day);
        }
        SalesRewardStatisticsTable statisticsTable =
                salesRewardActivityMapper.findBySalesIdAndStatisticsDate(activityTable.getSalesId(), rewardDate);
        statisticsTable.setDepositAmount(table.getDepositAmount() == null ? statisticsTable.getDepositAmount() :
                new BigDecimal(statisticsTable.getDepositAmount()).subtract(new BigDecimal(table.getDepositAmount())).floatValue());
        statisticsTable.setRewardAmount(new BigDecimal(statisticsTable.getRewardAmount()).subtract(new BigDecimal(table.getRewardAmount())).floatValue());
        salesRewardStatisticsRepository.save(statisticsTable);

        uerInfoService.addBalance(table.getSalesId(), Float.valueOf(activityTable.getRewardAmount()));

        UserInfoTable user = userInfoRepository.getFirstById(table.getSalesId());
        salaryRecordAdd(table.getSalesId(), Float.valueOf(table.getRewardAmount()), 2, user.getSalaryLogin(),
                user.getIbNo());

    }

    @Override
    public void salesRewardTask() throws Exception {
        salesRewardTask(null);

    }

    @Override
    public void salesRewardTask(Date newTime) throws Exception {

        if (newTime == null) {
            newTime = new Date();
        }

 /*       SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.SALES_REWARD_DATE);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SalesRewardDateConfigEntity configEntity = JSON.parseObject(sysConfigTable.getValue(),
                SalesRewardDateConfigEntity.class);

        if (DateUtil.formatDate(newTime).compareTo(configEntity.getActivityStartDate()) >= 0
                && configEntity.getActivityEndDate().compareTo(DateUtil.formatDate(newTime)) >= 0) {*/

            //客户入金大于500
            List<SalesRewardDto> rewardList = salesRewardActivityMapper.getCustomDepositAmount(newTime);
            for (SalesRewardDto reward : rewardList) {
                Float deposit = null;
                if (new BigDecimal(reward.getDepositAmount()).compareTo(new BigDecimal(5000)) < 0) {
                    deposit = 20f;
                } else if (new BigDecimal(reward.getDepositAmount()).compareTo(new BigDecimal(5000)) >= 0 && new BigDecimal(reward.getDepositAmount()).compareTo(new BigDecimal(10000)) < 0) {
                    deposit = 100f;
                } else {
                    deposit = 200f;
                }
                //uerInfoService.addBalance(reward.getSalesId(), deposit);
                //salaryRecordAdd(reward.getSalesId(), deposit, 1, reward.getSalaryLogin(), reward.getIbNo());

                SalesRewardActivityTable rewardTable = new SalesRewardActivityTable();
                BeanUtils.copyProperties(reward, rewardTable);
                //rewardTable.setRewardAmount(deposit);
                rewardTable.setRewardType(1);
                rewardTable.setRewardDate(DateUtil.addHour(newTime, -1));
                rewardTable.setAmountType(1);
                rewardTable.setAddTime(newTime);
                salesRewardActivityRepository.save(rewardTable);

//                sendSalesCustomDepositRewardEmail(reward, deposit);
            }

            //新增有效客户
            List<SalesRewardDto> rewardCountList = salesRewardActivityMapper.getAddCustomCountAmount(newTime);
            for (SalesRewardDto reward : rewardCountList) {
                //Float deposit = 50f;
                //uerInfoService.addBalance(reward.getSalesId(), deposit);
                //salaryRecordAdd(reward.getSalesId(), deposit, 1, reward.getSalaryLogin(), reward.getIbNo());

                SalesRewardActivityTable rewardTable = new SalesRewardActivityTable();
                BeanUtils.copyProperties(reward, rewardTable);
                //rewardTable.setRewardAmount(50f);
                rewardTable.setRewardType(2);
                rewardTable.setRewardDate(DateUtil.addHour(newTime, -1));
                rewardTable.setAmountType(1);
                rewardTable.setAddTime(newTime);
                salesRewardActivityRepository.save(rewardTable);

//                sendSaleAddCustomRewardEmail(reward, deposit);
            }
//        }

    }

    @Override
    public void salesRewardStatisticsTask() throws Exception {
        /*SysConfigTable sysConfigTable = sysConfigService.getByCode(ConfigConstants.SALES_REWARD_DATE);
        if (sysConfigTable == null) {
            throw ServiceException.exception(Constants.SYSTEM_ERROR);
        }
        SalesRewardDateConfigEntity configEntity = JSON.parseObject(sysConfigTable.getValue(),
                SalesRewardDateConfigEntity.class);

        if (DateUtil.formatDate(new Date()).compareTo(configEntity.getActivityStartDate()) >= 0
                && configEntity.getActivityEndDate().compareTo(DateUtil.formatDate(new Date())) >= 0) {*/

            String startTime = null;
            String endTime = null;

            // 假设你传入的时间
            Date now = new Date();
            // 判断是否为“周一凌晨”触发（00:00:00 ~ 00:59:59）
            boolean isMondayZero = DateUtil.isEarlyMonday(now);
            // 获取本周一日期
            Date thisMonday = DateUtil.getThisWeekMonday(now);
            // 获取上周一日期
            Date lastMonday = DateUtil.addDate(thisMonday, -7);

            // 设置时间范围
            if (isMondayZero) {
                startTime = DateUtil.formatDate(lastMonday) + " 00:00:00";
                endTime = DateUtil.formatDate(DateUtil.addDate(lastMonday, 6)) + " 23:59:59";
            } else {
                startTime = DateUtil.formatDate(thisMonday) + " 00:00:00";
                endTime = DateUtil.formatDate(DateUtil.addDate(thisMonday, 6)) + " 23:59:59";
            }

            String month = DateUtil.format("yyyyMM", new Date());
            String lastMonth = null;
            if (DateUtil.getMonth(DateUtil.parseTime(startTime)) != DateUtil.getMonth(new Date())) {
                lastMonth = DateUtil.format("yyyyMM", DateUtil.parseTime(startTime));
            }

            //查询本周入金客户数和总额
            List<SalesRewardDto> rewardCountList = salesRewardActivityMapper.salesRewardStatistics(startTime, endTime);
            Map<Long, SalesRewardDto> rewardMap =
                    rewardCountList.stream().collect(Collectors.toMap(SalesRewardDto::getSalesId,
                            SalesRewardDto -> SalesRewardDto));

            //查询本周奖励小计
            /*List<SalesRewardDto> rewardAmountList =
                    salesRewardActivityMapper.salesRewardAmountStatistics(DateUtil.parseTime(startTime),
                            DateUtil.addHour(new Date(), -1));
            Map<Long, SalesRewardDto> rewardAmountMap =
                    rewardAmountList.stream().collect(Collectors.toMap(SalesRewardDto::getSalesId,
                            SalesRewardDto -> SalesRewardDto));*/

            //查询本周扣除入金额
            List<SalesRewardDto> deductionAmountList =
                    salesRewardActivityMapper.salesDeductionAmountStatistics(DateUtil.parseTime(startTime),
                            DateUtil.addHour(new Date(), -1));
            Map<Long, SalesRewardDto> deductionAmountMap =
                    deductionAmountList.stream().collect(Collectors.toMap(SalesRewardDto::getSalesId,
                            SalesRewardDto -> SalesRewardDto));

            //查询本周统计
            List<SalesRewardStatisticsTable> tableList =
                    salesRewardActivityMapper.salesRewardWeekStatistics(startTime, 0l);
            Map<Long, SalesRewardStatisticsTable> rewardWeekMap =
                    tableList.stream().collect(Collectors.toMap(SalesRewardStatisticsTable::getSalesId,
                            SalesRewardStatisticsTable -> SalesRewardStatisticsTable));

            //查询交易客户数
            List<SalesRewardDto> tradeCountList = salesRewardActivityMapper.salesTradeStatistics(startTime, endTime,
                    month, lastMonth);

            for (SalesRewardDto tradeReward : tradeCountList) {
                SalesRewardStatisticsTable table = null;
                if (rewardWeekMap.containsKey(tradeReward.getSalesId())) {
                    table = rewardWeekMap.get(tradeReward.getSalesId());
                    table.setModifyTime(new Date());
                } else {
                    table = new SalesRewardStatisticsTable();
                    table.setSalesId(tradeReward.getSalesId());
                    table.setSalesName(tradeReward.getSalesName());
                    table.setAddTime(new Date());
                }
                table.setTradeCustomNum(tradeReward.getCustomNum());

                if (rewardMap.containsKey(tradeReward.getSalesId())) {
                    SalesRewardDto reward = rewardMap.get(tradeReward.getSalesId());
                    if (deductionAmountMap.containsKey(reward.getSalesId())) {
                        BigDecimal deductionAmount =
                                new BigDecimal(deductionAmountMap.get(reward.getSalesId()).getDepositAmount());
                        table.setDepositAmount(new BigDecimal(reward.getDepositAmount()).add(deductionAmount).floatValue());
                    } else {
                        table.setDepositAmount(reward.getDepositAmount());
                    }
                    table.setDepositCustomNum(reward.getCustomNum());
                } else {
                    table.setDepositAmount(0f);
                    table.setDepositCustomNum(0);
                }

                /*if (rewardAmountMap != null && rewardAmountMap.containsKey(tradeReward.getSalesId())) {
                    SalesRewardDto reward = rewardAmountMap.get(tradeReward.getSalesId());
                    table.setRewardAmount(reward.getRewardAmount());
                } else {
                    table.setRewardAmount(0f);
                }*/

                table.setStatisticsDate(DateUtil.parseDate(endTime));
                salesRewardStatisticsRepository.save(table);

                rewardMap.remove(tradeReward.getSalesId());

            }

            if (rewardMap.size() > 0) {
                for (Long salesId : rewardMap.keySet()) {
                    SalesRewardDto reward = rewardMap.get(salesId);

                    SalesRewardStatisticsTable table = null;
                    if (rewardWeekMap.containsKey(salesId)) {
                        table = rewardWeekMap.get(salesId);
                        table.setModifyTime(new Date());
                    } else {
                        table = new SalesRewardStatisticsTable();
                        table.setSalesId(reward.getSalesId());
                        table.setSalesName(reward.getSalesName());
                        table.setAddTime(new Date());
                    }

                    if (deductionAmountMap.containsKey(reward.getSalesId())) {
                        BigDecimal deductionAmount =
                                new BigDecimal(deductionAmountMap.get(reward.getSalesId()).getDepositAmount());
                        table.setDepositAmount(new BigDecimal(reward.getDepositAmount()).add(deductionAmount).floatValue());
                    } else {
                        table.setDepositAmount(reward.getDepositAmount());
                    }
                    table.setDepositCustomNum(reward.getCustomNum());
                    table.setStatisticsDate(DateUtil.parseDate(endTime));
                    table.setTradeCustomNum(0);

                    /*if (rewardAmountMap != null && rewardAmountMap.containsKey(salesId)) {
                        SalesRewardDto rewardDto = rewardAmountMap.get(salesId);
                        table.setRewardAmount(rewardDto.getRewardAmount());
                    } else {
                        table.setRewardAmount(0f);
                    }*/

                    salesRewardStatisticsRepository.save(table);
                }
            }

            //添加机器人
            //查询本周统计
            Map<String, SalesRewardStatisticsTable> rewardWeekRobotMap = new HashMap<>();
            List<SalesRewardStatisticsTable> tableRobotList =
                    salesRewardActivityMapper.salesRewardWeekStatistics(startTime, null);
            rewardWeekRobotMap =
                    tableRobotList.stream().collect(Collectors.toMap(SalesRewardStatisticsTable::getSalesName,
                            SalesRewardStatisticsTable -> SalesRewardStatisticsTable));

            List<SalesRewardRobotTable> robotList = salesRewardRobotRepository.findAll();
            for (SalesRewardRobotTable robotTable : robotList) {
                SalesRewardStatisticsTable table = null;
                Integer deponsitCustomNum = getRandom(robotTable.getDepositCustomNumMin(),
                        robotTable.getDepositCustomNumMax());
                Integer deponsitAmount = getRandom(robotTable.getDepositAmountMin(), robotTable.getDepositAmountMax());
                Integer tradeCustomNum = getRandom(robotTable.getTradeCustomNumMin(),
                        robotTable.getTradeCustomNumMax());
                BigDecimal rewardAmount = simulateRewards(deponsitCustomNum, Double.valueOf(deponsitAmount));

                if (rewardWeekRobotMap.containsKey(robotTable.getSalesName())) {
                    table = rewardWeekRobotMap.get(robotTable.getSalesName());
                    if (table.getDepositAmount() == null) {
                        table.setDepositAmount(0f);
                    }

                    table.setDepositCustomNum(table.getDepositCustomNum() + deponsitCustomNum);
                    table.setDepositAmount((new BigDecimal(table.getDepositAmount()).add(new BigDecimal(deponsitAmount)).floatValue()));
                    table.setTradeCustomNum(table.getTradeCustomNum() + tradeCustomNum);
                    /*if (DateUtil.formatDate(new Date()).compareTo(DateUtil.formatDate(DateUtil.addHour(new Date(),
                            -1))) != 0) {
                        table.setRewardAmount(new BigDecimal(table.getRewardAmount()).add(rewardAmount).floatValue());
                    } else {
                        table.setRewardAmount(table.getRewardAmount());
                    }*/

                    table.setModifyTime(new Date());
                } else {
                    table = new SalesRewardStatisticsTable();
                    table.setSalesName(robotTable.getSalesName());

                    table.setDepositCustomNum(deponsitCustomNum);
                    table.setDepositAmount(Float.valueOf(deponsitAmount));
                    table.setTradeCustomNum(tradeCustomNum);
                    /*if (DateUtil.formatDate(new Date()).compareTo(DateUtil.formatDate(DateUtil.addHour(new Date(),
                            -1))) != 0) {
                        table.setRewardAmount(rewardAmount.floatValue());
                    } else {
                        table.setRewardAmount(0f);
                    }*/
                    table.setAddTime(new Date());
                }

                table.setStatisticsDate(DateUtil.parseDate(endTime));
                salesRewardStatisticsRepository.save(table);

            }
        //}
    }

    public void balanceRecordAdd(Long agentId, Float amout, Integer type) {
        AgentBalanceRecordTable balanceRecordTable = new AgentBalanceRecordTable();
        balanceRecordTable.setAgentId(agentId);
        balanceRecordTable.setType(type);
        balanceRecordTable.setAmount(amout);
        balanceRecordTable.setBalanceType(4);
        balanceRecordTable.setComment("Standard trade rebate");
        balanceRecordTable.setAddTime(new Date());
        agentBalanceRecordRepository.save(balanceRecordTable);
    }

    public void salaryRecordAdd(Long salesId, Float amout, Integer operateTtype, Long salaryLogin, String ibNo) {

        SalesSalaryRecordTable salesSalaryRecordTable = new SalesSalaryRecordTable();
        salesSalaryRecordTable.setSalesId(salesId);
        salesSalaryRecordTable.setRecordType(SalesSalaryRecordType.ACTIVITY.getCode());
        salesSalaryRecordTable.setAmount(amout);
        salesSalaryRecordTable.setOperateType(operateTtype);
        salesSalaryRecordTable.setSalaryLogin(salaryLogin);
        salesSalaryRecordTable.setSalesNo(ibNo);
        salesSalaryRecordTable.setAddTime(new Date());
        salesSalaryRecordMapper.save(salesSalaryRecordTable);
    }

    public static Integer getRandom(Integer lowerBound, Integer upperBound) {
        Random rand = new Random();
        Integer randomNum = rand.nextInt(upperBound - lowerBound + 1) + lowerBound;

        return randomNum;
    }

    private void sendSalesCustomDepositRewardEmail(SalesRewardDto reward, Float deposit) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(8);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.EMAIL, reward.getEmail());
        map.put(MapConstants.V_FIRST_NAME_V, reward.getFirstName());
        map.put(MapConstants.V_LAST_NAME_V, reward.getLastName());
        map.put(MapConstants.V_ENGLISH_NAME_V, reward.getNameEn());
        map.put(MapConstants.PHONE, reward.getPhone());
        map.put(MapConstants.C_ID, String.valueOf(reward.getCId()));
        map.put(MapConstants.V_REBATE_V, String.format("%.2f", deposit.doubleValue()));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG SALES CUSTOM DEPOSIT REWARD");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.SALES_CUSTOM_DEPOSIT_REWARD);
        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.SALES_CUSTOM_DEPOSIT_REWARD);
        sysEmailSendEntity.setUsers(reward.getEmail());

        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendSaleAddCustomRewardEmail(SalesRewardDto reward, Float deposit) throws ServiceException {
        //构建map 用于后面邮件模版替换
        Map<String, String> map = new HashMap<>(3);

        map.put(MapConstants.DATE_TIME, DateUtil.formatTime(new Date()));
        map.put(MapConstants.V_ADD_CUSTOM_NUM_V, String.valueOf(reward.getCustomNum()));
        map.put(MapConstants.V_REBATE_V, String.format("%.2f", deposit.doubleValue()));

        SysEmailSendEntity sysEmailSendEntity = new SysEmailSendEntity();
        sysEmailSendEntity.setSubject("CWG SALES ADD CUSTOM REWARD");
        sysEmailSendEntity.setEmailSendEnum(EmailSendEnum.SALES_ADD_CUSTOM_REWARD);
        sysEmailSendEntity.setMap(map);
        sysEmailSendEntity.setTemplateName(SystemEmailCodeConstants.SALES_ADD_CUSTOM_REWARD);
        sysEmailSendEntity.setUsers(reward.getEmail());

        try {
            emailService.sendEmail(sysEmailSendEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

        Date newdate = DateUtil.parseTime("2025-08-11 02:30:00");
        Integer day = DateUtil.getDayOfWeek(newdate);
        if (1 == day) {
            System.out.println(DateUtil.formatDate(newdate));
        } else {
            System.out.println(DateUtil.formatDate(DateUtil.addDate(newdate, 8 - day)));
        }


//        String endTime = null;
//       Date newdate= DateUtil.parseTime("2025-07-21 00:30:00");
//        Integer agentId = DateUtil.getDayOfWeek(newdate);
//        if(1 == agentId){
//            startTime = DateUtil.formatDate(DateUtil.addDate(newdate, -6))+ " 00:00:00";;
//        }else{
//            startTime = DateUtil.formatDate(DateUtil.addDate(newdate, -agentId+2))+ " 00:00:00";
//        }
//        if (DateUtil.formatDate(newdate).compareTo(DateUtil.formatDate(DateUtil.addHour(new Date(), -1))) == 0) {
//            endTime = DateUtil.formatDate(newdate) + " 11:59:59";
//        } else {
//            endTime = DateUtil.formatDate(DateUtil.addHour(newdate, -1)) + " 23:59:59";
//        }
//        if (DateUtil.formatDate(newdate).compareTo(DateUtil.formatDate(DateUtil.addHour(newdate, -1))) == 0) {
//            endTime = DateUtil.formatDate(newdate) + " 11:59:59";
//        } else {
//            if(2 == agentId){
//                endTime = DateUtil.formatDate(DateUtil.parseDate(startTime)) + " 23:59:59";
//
//            }else{
//                endTime = DateUtil.formatDate(DateUtil.addHour(newdate, 0)) + " 23:59:59";
//            }
//
//        }
        String startTime = null;
        String endTime = null;

        // 假设你传入的时间
        Date now = DateUtil.parseTime("2025-07-21 12:30:00");

        // 判断是否为“周一凌晨”触发（00:00:00 ~ 00:59:59）
        boolean isMondayZero = DateUtil.isEarlyMonday(now);

        // 获取本周一日期
        Date thisMonday = DateUtil.getThisWeekMonday(now);
        // 获取上周一日期
        Date lastMonday = DateUtil.addDate(thisMonday, -7);

        // 设置时间范围
        if (isMondayZero) {
            startTime = DateUtil.formatDate(lastMonday) + " 00:00:00";
            endTime = DateUtil.formatDate(DateUtil.addDate(lastMonday, 6)) + " 23:59:59";
        } else {
            startTime = DateUtil.formatDate(thisMonday) + " 00:00:00";
            endTime = DateUtil.formatDate(DateUtil.addDate(thisMonday, 6)) + " 23:59:59";
        }

       /* int givenClientCount = 10;
        double totalDeposit = 2000;

        Float totalReward = simulateRewards(givenClientCount, totalDeposit);
        System.out.println("🏆 最终总奖励金额: $" + totalReward);*/
    }

    public static BigDecimal simulateRewards(int clientCount, double totalDeposit) {
        Random random = new Random();

        // 随机减少客户数量，保留 1 ~ clientCount 之间
        int actualClientCount = 1 + random.nextInt(clientCount);
        List<Double> deposits = randomSplit(totalDeposit, actualClientCount);

        List<Client> clients = new ArrayList<>();
        int validClientCount = 0;
        double totalReward = 0;

        for (double deposit : deposits) {
            double reward = 0;
            if (deposit >= 10000) {
                reward = 200;
            } else if (deposit >= 5000) {
                reward = 100;
            } else if (deposit >= 500) {
                reward = 20;
            }

            if (deposit >= 200) {
                validClientCount++;
            }

            clients.add(new Client(deposit, reward));
            totalReward += reward;
        }

        // 如果有效客户数 >= 5，追加额外奖励 $50
        if (validClientCount >= 5) {
            totalReward += 50;
        }

        // 输出奖励明细
        /*System.out.println("=== 客户入金及奖励 ===");
        for (Client client : clients) {
            System.out.printf("客户入金: $%.2f → 奖励: $%.2f\n", client.deposit, client.reward);
        }

        System.out.println("有效客户数（入金 ≥ 200）: " + validClientCount);
        if (validClientCount >= 5) {
            System.out.println("🎁 额外奖励 $50 已触发");
        }*/

        return new BigDecimal(totalReward);
    }

    // 将总金额随机拆成 n 份
    private static List<Double> randomSplit(double total, int parts) {
        Random random = new Random();
        List<Double> cuts = new ArrayList<>();
        cuts.add(0.0);
        for (int i = 0; i < parts - 1; i++) {
            cuts.add(random.nextDouble() * total);
        }
        cuts.add(total);

        Collections.sort(cuts);
        List<Double> result = new ArrayList<>();
        for (int i = 1; i < cuts.size(); i++) {
            double amount = Math.round((cuts.get(i) - cuts.get(i - 1)) * 100.0) / 100.0;
            result.add(amount);
        }
        return result;
    }

    static class Client {
        double deposit;
        double reward;

        Client(double deposit, double reward) {
            this.deposit = deposit;
            this.reward = reward;
        }
    }

    /*public static void main(String[] args) throws Exception {
        // 示例日期
        LocalDate date = LocalDate.of(2025, 1, 1); // 例如，2023年4月15日

        // 获取当前Locale的一周规则（默认是周一作为一周的第一天）
        WeekFields weekFields = WeekFields.of(Locale.getDefault());

        // 获取日期是一年中的第几周
        int weekOfYear = date.get(weekFields.weekOfWeekBasedYear());

        System.out.println("日期 " + date + " 是一年中的第 " + weekOfYear + " 周");



        System.out.println(DateUtil.getfWeekOfYear(new Date()));
        System.out.println(DateUtil.getDayOfWeek(DateUtil.parseDate("2025-07-13")));



        *//*int year = 2025; // 年份
        int weekNumber = 29; // 周数，注意这里的周数是从1开始的
        DayOfWeek dayOfWeek = DayOfWeek.MONDAY; // 星期几，例如周一

        // 创建一个该年的第一天
        LocalDate date = LocalDate.of(year, 1, 1);
        // 计算第一周的第一个周一的日期
        date = date.with(TemporalAdjusters.firstInMonth(dayOfWeek));
        // 然后加上周数-1的天数（因为我们是从第一周开始计算的）
        date = date.plusWeeks(weekNumber - 1);

        System.out.println("对应的日期是: " + date);*//*

     *//*int year = 2025; // 年份
        int weekNumber = 29; // 周数，注意这里的周数是从1开始的
        DayOfWeek firstDayOfWeek = DayOfWeek.SUNDAY; // 每周的第一天，例如周一
        DayOfWeek targetDayOfWeek = DayOfWeek.SUNDAY; // 你想要得到的星期几，例如周一

        // 创建该年的第一天，并设置为指定周的第一天（例如周一）
        LocalDate firstWeekDay = YearMonth.of(year, 1).atDay(1).with(TemporalAdjusters.nextOrSame(firstDayOfWeek));
        // 根据周数调整日期
        LocalDate targetDate = firstWeekDay.plusWeeks(weekNumber - 1);
        // 如果需要调整到特定的星期几（例如周一），可以进一步调整
        if (targetDayOfWeek != firstDayOfWeek) {
            targetDate = targetDate.with(TemporalAdjusters.nextOrSame(targetDayOfWeek));
        }

        System.out.println("对应的日期是: " + targetDate);
        // 创建一个 DateTimeFormatter 对象，指定日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 使用 formatter 将 LocalDate 转换为字符串
        String formattedDate = targetDate.format(formatter);

        // 输出结果
        System.out.println(formattedDate);
        System.out.println(DateUtil.addDate(DateUtil.parse("yyyy-MM-dd", formattedDate), -6));*//*

        System.out.println("yyyy-MM-dd hh:mm:ss".substring(0, 10));
        int num = 12345;
        int tensDigit =   (11+10)/10*10;
        System.out.println(tensDigit);
    }*/

}
