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 (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());
            bs.setMallAmount(so.getMallAmount());
            bs.setCooperateAmount(so.getCooperateAmount());
            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.setFictitiousPv(so.getFictitiousPv());
            /**
             *直播订单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 {
                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 RETAIL_REGISTER:
                        oldSo.setMainRegAmount(addOrInitializeAmount(oldSo.getMainRegAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainRegPv(addOrInitializeAmount(oldSo.getMainRegPv(), newSo.getOrderAchieve(), type));
                        break;
                    // 复购 43
                    case RETAIL_REPURCHASE:
                        oldSo.setMainRepurAmount(addOrInitializeAmount(oldSo.getMainRepurAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainRepurPv(addOrInitializeAmount(oldSo.getMainRepurPv(), 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 RANGE_INCOME:
                oldBon.setRepurRangeBonus(addOrInitializeAmount(oldBon.getRepurRangeBonus(), 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.setRepurCouponSubtotal(cb.getRepurCouponSubtotal());
            bs.setRepurPushIncome(cb.getRepurPushIncome());

            // 查询数据库判断记录是否存在
            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> 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.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);

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

            if (CollectionUtil.isNotEmpty(vertexList)) {
                for (Map.Entry<Date, List<CuBonusStatisVO>> entry : orderListMap.entrySet()) {
                    for (CuBonusStatisVO ve : entry.getValue()) {
                        CuBonusStatisVO oldSo = new CuBonusStatisVO();
                        addOrderAmount(oldSo, null, ve.getPkVertex(), entry.getValue(), 2);
                        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();
    }

}
