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.constant.CountryConstants;
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.statis.mapper.CuBonusStatisMapper;
import com.hzs.member.statis.service.ICuBonusStatisService;
import com.hzs.member.statis.vo.*;
import lombok.extern.slf4j.Slf4j;
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 {

    /**
     * 保存奖金拨比订单数据
     **/
    private void saveBonusStatis(List<CuBonusStatisVO> soList) {
        for (CuBonusStatisVO so : soList) {
            if (null == so.getPkCountry()) {
                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.setSpecialRegisterAmount(so.getSpecialRegisterAmount());
            bs.setSpecialUpgradeAmount(so.getSpecialUpgradeAmount());
            bs.setMainRepurAmount(so.getMainRepurAmount());
            bs.setMallAmount(so.getMallAmount());
            bs.setCooperateAmount(so.getCooperateAmount());
            bs.setSpecialRepurchaseAmount(so.getSpecialRepurchaseAmount());
            bs.setHaiFunUpgradeAmount(so.getHaiFunUpgradeAmount());
            bs.setHifansRegAmount(so.getHifansRegAmount());
            bs.setGiftOrder(so.getGiftOrder());
            bs.setThirdOrder(so.getThirdOrder());
            bs.setFictitiousAmount(so.getFictitiousAmount());
            bs.setWelfareOrder(so.getWelfareOrder());

            // 注册新增PV
            bs.setMainRegPv(so.getMainRegPv());
            // 升级新增PV
            bs.setMainUpPv(so.getMainUpPv());
            // 复购新增PV
            bs.setMainRepurPv(so.getMainRepurPv());
            // 特殊注册PV
            bs.setSpecialRegisterPv(so.getSpecialRegisterPv());
            // 特殊升级PV
            bs.setSpecialUpgradePv(so.getSpecialUpgradePv());
            // 特殊复购PV
            bs.setSpecialRepurchasePv(so.getSpecialRepurchasePv());
            // 虚拟订单PV
            bs.setFictitiousPv(so.getFictitiousPv());
            // 嗨粉注册PV
            bs.setHifansRegPv(so.getHifansRegPv());
            // 海粉升级PV
            bs.setHaiFunUpgradePv(so.getHaiFunUpgradePv());
            // 直播订单PV
            bs.setMallPv(so.getMallPv());
            // 合作订单PV
            bs.setCooperatePv(so.getCooperatePv());
            // 福利专区PV
            bs.setWelfareOrderPv(so.getWelfareOrderPv());

            // 查询数据库判断记录是否存在
            List<CuBonusStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                // 不存在则插入新记录
                baseMapper.insert(bs);
            } else {
                // 设置主键ID
                bs.setPkId(existingRecord.get(0).getPkId());
                // 存在则更新记录
                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.getOrderAmount(), type));
                        oldSo.setMainRegPv(addOrInitializeAmount(oldSo.getMainRegPv(), newSo.getOrderAchieve(), type));
                        break;
                    case UPGRADE_ORDER:
                        // 升级订单
                        oldSo.setMainUpAmount(addOrInitializeAmount(oldSo.getMainUpAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainUpPv(addOrInitializeAmount(oldSo.getMainUpPv(), newSo.getOrderAchieve(), type));
                        break;
                    case SPECIAL_REGISTER_ORDER:
                        // 乐学注册订单
                        oldSo.setSpecialRegisterAmount(addOrInitializeAmount(oldSo.getSpecialRegisterAmount(), newSo.getOrderAmount(), type));
                        oldSo.setSpecialRegisterPv(addOrInitializeAmount(oldSo.getSpecialRegisterPv(), newSo.getOrderAchieve(), type));
                        break;
                    case SPECIAL_UPGRADE_ORDER:
                        // 乐学升级订单
                        oldSo.setSpecialUpgradeAmount(addOrInitializeAmount(oldSo.getSpecialUpgradeAmount(), newSo.getOrderAmount(), type));
                        oldSo.setSpecialUpgradePv(addOrInitializeAmount(oldSo.getSpecialUpgradePv(), newSo.getOrderAchieve(), type));
                        break;
                    // 复购
                    case REPURCHASE_ORDER:
                    case CONSUME_ORDER:
                        // 复购订单、重消订单
                        oldSo.setMainRepurAmount(addOrInitializeAmount(oldSo.getMainRepurAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainRepurPv(addOrInitializeAmount(oldSo.getMainRepurPv(), newSo.getOrderAchieve(), type));
                        break;
                    case SPECIAL_REPURCHASE_ORDER:
                        // 乐学复购订单
                        oldSo.setSpecialRepurchaseAmount(addOrInitializeAmount(oldSo.getSpecialRepurchaseAmount(), newSo.getOrderAmount(), type));
                        oldSo.setSpecialRepurchasePv(addOrInitializeAmount(oldSo.getSpecialRepurchasePv(), newSo.getOrderAchieve(), type));
                        break;
                    case WELFARE_ORDER:
                        // 福利订单
                        oldSo.setWelfareOrder(addOrInitializeAmount(oldSo.getWelfareOrder(), newSo.getOrderAmount(), type));
                        oldSo.setWelfareOrderPv(addOrInitializeAmount(oldSo.getWelfareOrderPv(), newSo.getOrderAchieve(), type));
                        break;
                    default:
                        break;
                }
            }
        }
        return oldSo;
    }

    //累计中国奖金
    private CuBonusStatisVO addChAchieve(CuBonusStatisVO oldBon, CuBonusStatisVO newBon) {
        oldBon.setPkCountry(newBon.getPkCountry());
        oldBon.setCreationTime(newBon.getCreationTime());
        oldBon.setPkVertex(newBon.getPkVertex());
        oldBon.setPkTeamCode(newBon.getPkTeamCode());

        switch (EBonusItems.getEnumByValue(newBon.getBonusType())) {
            // 首购
            case DIRECT_INCOME:
                // 直推收益
                oldBon.setIntroduceBonus(addOrInitializeAmount(oldBon.getIntroduceBonus(), newBon.getRealIncome(), 2));
                break;
            case EXPANSION_INCOME:
                // 拓展收益
                oldBon.setOrgBonus(addOrInitializeAmount(oldBon.getOrgBonus(), newBon.getRealIncome(), 2));
                oldBon.setCalFirAchieve(addOrInitializeAmount(oldBon.getCalFirAchieve(), newBon.getCalFirAchieve(), 2));
                oldBon.setCalRepAchieve(addOrInitializeAmount(oldBon.getCalRepAchieve(), newBon.getCalRepAchieve(), 2));
                break;
            case COACHING_INCOME:
                // 辅导收益
                oldBon.setLeaderBonus(addOrInitializeAmount(oldBon.getLeaderBonus(), newBon.getRealIncome(), 2));
                break;
            case SERVICE_SUBSIDIES:
                // 服务补贴
                oldBon.setServiceBonus(addOrInitializeAmount(oldBon.getServiceBonus(), newBon.getRealIncome(), 2));
                break;
            // 复购
            case REPURCHASE_RANGE_INCOME:
                // 复购级差
                oldBon.setRepurRangeBonus(addOrInitializeAmount(oldBon.getRepurRangeBonus(), newBon.getRealIncome(), 2));
                break;
            case CONSUMPTION_EXPANSION_INCOME:
                // 消费拓展收益
                oldBon.setRepurOrgBonus(addOrInitializeAmount(oldBon.getRepurOrgBonus(), newBon.getRealIncome(), 2));
                break;
            case REPURCHASE_COACHING_INCOME:
                // 复购辅导收益
                oldBon.setRepurLeaderBonus(addOrInitializeAmount(oldBon.getRepurLeaderBonus(), newBon.getRealIncome(), 2));
            case REPURCHASE_COUPONS:
                // 复购券
                oldBon.setRepurCouponSubtotal(addOrInitializeAmount(oldBon.getRepurCouponSubtotal(), newBon.getRealIncome(), 2));
                break;
            case HELP_EACH_INCOME:
                // 复购直推收益
                oldBon.setRepurPushIncome(addOrInitializeAmount(oldBon.getRepurPushIncome(), newBon.getRealIncome(), 2));
                break;
        }
        return oldBon;
    }

    /**
     * 保存国内奖金拨比奖金数据
     **/
    private void saveBonusStatisAchieve(List<CuBonusStatisVO> cblist) {
        for (CuBonusStatisVO cb : cblist) {
            if (cb.getPkCountry() == null) {
                continue;
            }
            //查询体系是否添加
            CuBonusStatis bs = new CuBonusStatis();
            bs.setPkBdVertex(cb.getPkVertex());
            bs.setPkTeamCode(cb.getPkTeamCode());
            bs.setCreationTime(cb.getCreationTime());
            bs.setPeriod(cb.getPeriod());
            bs.setPkCountry(cb.getPkCountry());
            bs.setIntroduceBonus(cb.getIntroduceBonus());
            bs.setOrgBonus(cb.getOrgBonus());
            bs.setLeaderBonus(cb.getLeaderBonus());
            bs.setShareBonus(cb.getShareBonus());
            bs.setServiceBonus(cb.getServiceBonus());
            bs.setRepurRangeBonus(cb.getRepurRangeBonus());
            bs.setRepurOrgBonus(cb.getRepurOrgBonus());
            bs.setRepurLeaderBonus(cb.getRepurLeaderBonus());
            bs.setRepurCouponSubtotal(cb.getRepurCouponSubtotal());
            bs.setRepurPushIncome(cb.getRepurPushIncome());
            //嗨粉直推收益
            bs.setHiFunIncome(cb.getHiFunIncome());
            bs.setCalFirAchieve(cb.getCalFirAchieve());
            bs.setCalRepAchieve(cb.getCalRepAchieve());

            // 查询数据库判断记录是否存在
            List<CuBonusStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                // 不存在则插入新记录
                baseMapper.insert(bs);
            } else {
                // 设置主键ID
                bs.setPkId(existingRecord.get(0).getPkId());
                // 存在则更新记录
                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> queryCuBonusStatis(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.queryCuBonusStatis(cuBonusStatisVO);
    }

    /**
     * 查询体系合计的订单业绩
     **/
    @Override
    public CuBonusStatisVO queryOrderAchieveSum(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.queryOrderAchieveSum(cuBonusStatisVO);
    }

    /**
     * 奖金拨比列表统计小计（最后一行）
     **/
    @Override
    public CuBonusStatisVO queryCuBonusSumStatis(CuBonusStatisVO cuBonusStatisVO) {
        return baseMapper.queryCuBonusSumStatis(cuBonusStatisVO);
    }

    /**
     * 查询个人奖金拨比
     **/
    @Override
    public CuBonusSinglePersonStatisVO bonusSingleSum(CuBonusSinglePersonStatisVO csps) {
        return baseMapper.bonusSingleSum(csps);
    }

    /**
     * 奖金拨比图表
     **/
    @Override
    public List<CuBonusStatisChartVO> queryCuBonusStatisChart(CuBonusStatisChartVO chartVO) {
        return baseMapper.queryCuBonusStatisChart(chartVO);
    }

    /**
     * 奖金拨比图表合计
     **/
    @Override
    public CuBonusStatisChartVO queryCuBonusSumStatisChart(CuBonusStatisChartVO chartVO) {
        return baseMapper.queryCuBonusSumStatisChart(chartVO);
    }

    /**
     * 查询奖金拨比图形数据-柱形图
     **/
    @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<CuBonusStatis> getCuBonusStatis(CuBonusStatis cuBonusStatis) {
        return baseMapper.getCuBonusStatis(cuBonusStatis);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean statisHistoryBonus(String startDate, String endDate) {
        //查询所有体系
        List<CuBonusStatisVO> vertexlist = vertexList();

        //查询新增订单
        CuBonusStatisVO cbs = new CuBonusStatisVO();
        cbs.setDelFlag(EDelFlag.UN_DELETE.getValue());
        cbs.setOrderStatus(EOrderStatus.PAY.getValue());
        cbs.setStartDate(startDate);
        cbs.setEndDate(endDate);
        cbs.setPkCountry(CountryConstants.CHINA_COUNTRY);

        //累加好的数据存入soAll
        List<CuBonusStatisVO> soAll = new ArrayList<>();
        // 先查中国订单
        List<CuBonusStatisVO> orachList = baseMapper.querySaOrderByLessDay(cbs);
        if (CollectionUtil.isNotEmpty(orachList)) {
            // 按支付时间（年月日）把订单进行分组（key:支付时间（年月日），value：订单统计数据列表）
            Map<Date, List<CuBonusStatisVO>> orachListMap = orachList.stream().collect(Collectors.groupingBy(CuBonusStatisVO::getCreationTime));

            if (CollectionUtil.isNotEmpty(vertexlist)) {
                for (Map.Entry<Date, List<CuBonusStatisVO>> entry : orachListMap.entrySet()) {
                    for (CuBonusStatisVO ve : entry.getValue()) {
                        CuBonusStatisVO oldSo = new CuBonusStatisVO();
                        addOrderAmount(oldSo, null, ve.getPkVertex(), entry.getValue(), 2);
                        if (oldSo.getPkCountry() != null) {
                            soAll.add(oldSo);
                        }
                    }
                }
            }
        }

        //累加好的数据存入acAll
        List<CuBonusStatisVO> acAll = new ArrayList<>();
        //查询中国统计奖金
        List<CuBonusStatisVO> listCn = baseMapper.queryChinaCountryBonus(cbs);
        if (CollectionUtil.isNotEmpty(listCn)) {
            // 按支付时间（年月日）把订单进行分组（key:支付时间（年月日），value：订单统计数据列表）
            Map<Date, List<CuBonusStatisVO>> listCnMap = listCn.stream()
                    .collect(Collectors.groupingBy(CuBonusStatisVO::getCreationTime));

            if (CollectionUtil.isNotEmpty(vertexlist)) {
                for (CuBonusStatisVO ve : vertexlist) {
                    for (Map.Entry<Date, List<CuBonusStatisVO>> entry : listCnMap.entrySet()) {
                        CuBonusStatisVO oldSo = new CuBonusStatisVO();
                        for (CuBonusStatisVO cb : entry.getValue()) {
                            if (ve.getPkVertex().equals(cb.getPkVertex())) {
                                addChAchieve(oldSo, cb);
                                if (oldSo.getPkCountry() != null) {
                                    acAll.add(oldSo);
                                }
                            }
                        }
                    }
                }
            }
        }

        //存入订单信息
        saveBonusStatis(soAll);
        //存入国内奖金信息
        saveBonusStatisAchieve(acAll);

        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> vertexList() {
        return baseMapper.vertexList();
    }


}
