package com.hzs.member.statis.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.enums.EBonusItems;
import com.hzs.common.core.enums.EDelFlag;
import com.hzs.common.core.enums.EOrderStatus;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.domain.member.statis.CuBonusStatis;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.statis.mapper.CuBonusStatisMapper;
import com.hzs.member.statis.service.ICuBonusStatisService;
import com.hzs.member.statis.vo.CuBonusStatisColumnarVO;
import com.hzs.member.statis.vo.CuBonusStatisRoundVO;
import com.hzs.member.statis.vo.CuBonusStatisVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 奖金拨比统计 服务实现类
 */
@Service
@Slf4j
public class CuBonusStatisServiceImpl extends ServiceImpl<CuBonusStatisMapper, CuBonusStatis> implements ICuBonusStatisService {

    @Autowired
    ICuMemberSettlePeriodService cuMemberSettlePeriodService;

    /**
     * 保存奖金拨比订单数据
     **/
    private void saveBonusStatis(List<CuBonusStatisVO> soList) {
        for (CuBonusStatisVO so : soList) {
            if (so.getPkCountry() == null) {
                continue;
            }
            CuBonusStatis bs = new CuBonusStatis();
            bs.setPkBdVertex(so.getPkVertex());
            bs.setCreationTime(so.getCreationTime());
            bs.setPkCountry(so.getPkCountry());
            bs.setPkTeamCode(so.getPkTeamCode());
            bs.setMainRegAmount(so.getMainRegAmount());
            bs.setMainUpAmount(so.getMainUpAmount());
            bs.setMainRepurAmount(so.getMainRepurAmount());
            // 查询数据库判断记录是否存在
            List<CuBonusStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                baseMapper.insert(bs); // 不存在则插入新记录
            } else {
                bs.setPkId(existingRecord.get(0).getPkId()); // 设置主键ID
                baseMapper.updateById(bs); // 存在则更新记录
            }
        }

    }

    /**
     * 累加订单金额
     **/
    private CuBonusStatisVO addOrderAmount(CuBonusStatisVO oldSo, Integer pkCountry, Integer pkVertex, List<CuBonusStatisVO> orachList, int type) {
        for (CuBonusStatisVO newSo : orachList) {
            // 修改统计数据
            if ((pkCountry == null && pkVertex != null && pkVertex.equals(newSo.getPkVertex())) ||
                    (pkCountry != null && pkVertex == null && pkCountry.equals(newSo.getPkCountry()))) {
                oldSo.setPkCountry(newSo.getPkCountry());
                oldSo.setCreationTime(newSo.getCreationTime());
                if (newSo.getPkVertex() != null) {
                    oldSo.setPkVertex(newSo.getPkVertex());
                }
                if (newSo.getPkTeamCode() != null) {
                    oldSo.setPkTeamCode(newSo.getPkTeamCode());
                }
                switch (EOrderType.getEnumByValue(newSo.getOrderType())) {
                    // 首购
                    case REGISTER_ORDER:
                        oldSo.setMainRegAmount(addOrInitializeAmount(oldSo.getMainRegAmount(), newSo.getOrderAchieve(), type));
                        break;
                    case UPGRADE_ORDER:
                        oldSo.setMainUpAmount(addOrInitializeAmount(oldSo.getMainUpAmount(), newSo.getOrderAchieve(), type));
                        break;
                    case FICTITIOUS_ORDER:
                        oldSo.setFictitiousOrder(addOrInitializeAmount(oldSo.getFictitiousOrder(), newSo.getOrderAchieve(), type));
                        break;
                    // 复销
                    case RESALE_ORDER:
                        oldSo.setMainRepurAmount(addOrInitializeAmount(oldSo.getMainRepurAmount(), newSo.getOrderAchieve(), type));
                        break;
                    default:
                        break;
                }
            }
        }
        return oldSo;
    }

    /**
     * 累计国外奖金
     **/
    private CuBonusStatisVO addFcAchieve(CuBonusStatisVO oldBon, CuBonusStatisVO newBon) {
        oldBon.setPkCountry(newBon.getPkCountry());
        oldBon.setCreationTime(newBon.getCreationTime());

        switch (EBonusItems.getEnumByValue(newBon.getBonusType())) {
            // 首购
            case SEE_POINT_INCOME:
                oldBon.setSeePointIncome(addOrInitializeAmount(oldBon.getSeePointIncome(), newBon.getRealIncome(), 2));
                break;
            case DIRECT_INCOME:
                oldBon.setIntroduceBonus(addOrInitializeAmount(oldBon.getIntroduceBonus(), newBon.getRealIncome(), 2));
                break;
            case EXPANSION_INCOME:
                oldBon.setOrgBonus(addOrInitializeAmount(oldBon.getOrgBonus(), newBon.getRealIncome(), 2));
                break;
            case COACHING_INCOME:
                oldBon.setLeaderBonus(addOrInitializeAmount(oldBon.getLeaderBonus(), newBon.getRealIncome(), 2));
                break;
            case DIVIDEND_INCOME:
                oldBon.setShareIncome(addOrInitializeAmount(oldBon.getShareIncome(), newBon.getRealIncome(), 2));
                break;
            // 复销极差收益
            case RESALE_RANGE_INCOME:
                oldBon.setRepurRangeIncome(addOrInitializeAmount(oldBon.getRepurRangeIncome(), newBon.getRealIncome(), 2));
                break;
            //复销同级收益
            case RESALE_SAME_LEVEL_INCOME:
                oldBon.setSameLevelIncome(addOrInitializeAmount(oldBon.getSameLevelIncome(), newBon.getRealIncome(), 2));
                break;
        }
        return oldBon;
    }

    /**
     * 保存国外奖金拨比奖金数据
     **/
    private void saveForeignCountryBonus(List<CuBonusStatisVO> cblist) {
        for (CuBonusStatisVO cb : cblist) {
            if (cb.getPkCountry() == null) {
                continue;
            }
            //查询体系是否添加
            CuBonusStatis bs = new CuBonusStatis();
            bs.setCreationTime(cb.getCreationTime());
            bs.setPkCountry(cb.getPkCountry());
            bs.setSeePointIncome(cb.getSeePointIncome());
            bs.setShareIncome(cb.getShareIncome());
            bs.setIntroduceBonus(cb.getIntroduceBonus());
            bs.setOrgBonus(cb.getOrgBonus());
            bs.setLeaderBonus(cb.getLeaderBonus());
            bs.setRepurRangeIncome(cb.getRepurRangeIncome());
            bs.setSameLevelIncome(cb.getSameLevelIncome());
            // 查询数据库判断记录是否存在
            List<CuBonusStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                baseMapper.insert(bs); // 不存在则插入新记录
            } else {
                bs.setPkId(existingRecord.get(0).getPkId()); // 设置主键ID
                baseMapper.updateById(bs); // 存在则更新记录
            }
        }
    }

    // 获取或初始化金额
    private BigDecimal addOrInitializeAmount(BigDecimal currentAmount, BigDecimal newAmount, int type) {
        if (type == 1) {
            if (currentAmount != null) {
                return currentAmount.subtract(newAmount);
            } else {
                return newAmount;
            }
        } else {
            if (currentAmount != null) {
                return currentAmount.add(newAmount);
            } else {
                return newAmount;
            }
        }
    }

    @Override
    public List<CuBonusStatisVO> queryForeignCountryCuBonusStatis(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.queryForeignCountryCuBonusStatis(cuBonusStatisVO);
    }

    @Override
    public CuBonusStatisVO queryForeignCountryCuBonusStatisSum(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.queryForeignCountryCuBonusStatisSum(cuBonusStatisVO);
    }

    @Override
    public CuBonusStatisColumnarVO pillarRatio(CuBonusStatisColumnarVO columnarVO) {
        // 查询当年的数据
        CuBonusStatisColumnarVO thisYear = queryYearData(columnarVO);
        // 查询去年的数据
        LocalDate startDate = LocalDate.parse(columnarVO.getStartDate());
        LocalDate lastYearDate = startDate.minusYears(1);
        String startDateStr = lastYearDate.toString();
        columnarVO.setStartDate(startDateStr);

        LocalDate endDate = LocalDate.parse(columnarVO.getEndDate());
        lastYearDate = endDate.minusYears(1);
        String endDateStr = lastYearDate.toString();
        columnarVO.setEndDate(endDateStr);
        CuBonusStatisColumnarVO lastYear = queryYearData(columnarVO);

        // 设置去年数据的属性，如果查询结果为空，则设置为 BigDecimal.ZERO
        if (thisYear != null) {
            thisYear.setLastHifansRegAmount(lastYear != null ? lastYear.getHifansRegAmount() : BigDecimal.ZERO);
            thisYear.setLastMainRegAmount(lastYear != null ? lastYear.getMainRegAmount() : BigDecimal.ZERO);
            thisYear.setLastMainRepurAmount(lastYear != null ? lastYear.getMainRepurAmount() : BigDecimal.ZERO);
            thisYear.setLastMainUpAmount(lastYear != null ? lastYear.getMainUpAmount() : BigDecimal.ZERO);
        }
        return thisYear;
    }

    @Override
    public CuBonusStatisColumnarVO queryYearData(CuBonusStatisColumnarVO columnarVO) {
        Optional<CuBonusStatisColumnarVO> opt = Optional.ofNullable(baseMapper.queryYearData(columnarVO));
        return opt.orElse(null);
    }

    @Override
    public CuBonusStatisRoundVO queryDiallingRatio(CuBonusStatisRoundVO roundVO) {
        return baseMapper.queryDiallingRatio(roundVO);
    }

    /**
     * 查询小于当天全部已支付或撤单订单信息
     **/
    public List<CuBonusStatisVO> querySaOrderByLessDay(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.querySaOrderByLessDay(cuBonusStatisVO);
    }

    /**
     * 查询当天团队统计数据
     **/
    public List<CuBonusStatis> getCuBonusStatis(CuBonusStatis cuBonusStatis) {
        return baseMapper.getCuBonusStatis(cuBonusStatis);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean statisHistoryBonus(String startDate, String endDate) {
        //查询新增订单
        CuBonusStatisVO cbs = new CuBonusStatisVO();
        //累加好的数据存入soAll
        List<CuBonusStatisVO> soAll = new ArrayList<>();

        //查询国外国家列表 查询国外统计奖金
        //累加好的数据存入fcAll
        List<CuBonusStatisVO> fcAll = new ArrayList<>();
        List<CuBonusStatisVO> countrylist = countrylist(cbs);
        if (CollectionUtil.isNotEmpty(countrylist)) {
            for (CuBonusStatisVO con : countrylist) {
                cbs.setDelFlag(EDelFlag.UN_DELETE.getValue());
                cbs.setOrderStatus(EOrderStatus.PAY.getValue());
                cbs.setStartDate(startDate);
                cbs.setEndDate(endDate);
                cbs.setPkCountry(con.getPkCountry());
                //查询国外订单
                List<CuBonusStatisVO> orach = baseMapper.querySaOrderByLessDay(cbs);
                Map<Date, List<CuBonusStatisVO>> orachMap = orach.stream()
                        .collect(Collectors.groupingBy(CuBonusStatisVO::getCreationTime));
                if (CollectionUtil.isNotEmpty(orach)) {
                    for (Map.Entry<Date, List<CuBonusStatisVO>> entry : orachMap.entrySet()) {
                        CuBonusStatisVO oldSo = new CuBonusStatisVO();
                        oldSo = addOrderAmount(oldSo, con.getPkCountry(), null, entry.getValue(), 2);
                        if (oldSo.getPkCountry() != null) {
                            soAll.add(oldSo);
                        }
                    }
                }

                //查询国外统计奖金
                //累加好的数据存入fcAll
                CuBonusStatisVO cuBonusStatisVO = new CuBonusStatisVO();
                cuBonusStatisVO.setStartDate(startDate);
                cuBonusStatisVO.setEndDate(endDate);
                cuBonusStatisVO.setPkCountry(con.getPkCountry());
//                if(con.getPkCountry()==147){
//                    System.out.println();
//                }
                //查询国外奖金
                List<CuBonusStatisVO> bsList = queryForeignCountryBonus(cuBonusStatisVO);
                Map<Date, List<CuBonusStatisVO>> bsListMap = bsList.stream()
                        .collect(Collectors.groupingBy(CuBonusStatisVO::getCreationTime));
                if (CollectionUtil.isNotEmpty(bsList)) {
                    for (Map.Entry<Date, List<CuBonusStatisVO>> entry : bsListMap.entrySet()) {
                        CuBonusStatisVO oldSo1 = new CuBonusStatisVO();
                        for (CuBonusStatisVO cb : entry.getValue()) {
                            if (con.getPkCountry().equals(cb.getPkCountry())) {
                                oldSo1 = addFcAchieve(oldSo1, cb);
                            }
                        }
                        if (oldSo1.getPkCountry() != null) {
                            fcAll.add(oldSo1);
                        }
                    }
                }

            }
        }

        //存入订单信息
        saveBonusStatis(soAll);
        //存入国外奖金信息
        saveForeignCountryBonus(fcAll);
        return true;
    }

    @Override
    public Boolean delStatis(String startDate, String endDate) {
        return baseMapper.delStatis(startDate, endDate);
    }

    @Override
    public List<CuBonusStatisVO> bonusDeductlist(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.bonusDeductlist(cuBonusStatisVO);
    }

    @Override
    public List<CuBonusStatisVO> bonusDividendRatiolist(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.bonusDividendRatiolist(cuBonusStatisVO);
    }

    @Override
    public List<CuBonusStatisVO> queryForeignCountryBonus(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.queryForeignCountryBonus(cuBonusStatisVO);
    }

    @Override
    public List<CuBonusStatisVO> countrylist(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.countrylist(cuBonusStatisVO);
    }

}
