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.constant.TableNameConstants;
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.CuBonusVertexStatis;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.statis.mapper.CuBonusVertexStatisMapper;
import com.hzs.member.statis.service.ICuBonusVertexStatisService;
import com.hzs.member.statis.vo.CuBonusVertexStaticTotalVO;
import com.hzs.member.statis.vo.CuBonusVertexStatisVO;
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.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 奖金拨比零线统计 服务实现类
 */
@Service
public class CuBonusVertexStatisServiceImpl extends ServiceImpl<CuBonusVertexStatisMapper, CuBonusVertexStatis> implements ICuBonusVertexStatisService {

    @Autowired
    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;

    /**
     * 通过日期范围，返回范围内每天的日期
     **/
    public static List<String> getDatesInRange(String startDate, String endDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate start = LocalDate.parse(startDate, formatter);
        LocalDate end = LocalDate.parse(endDate, formatter);
        List<String> dates = new ArrayList<>();
        LocalDate current = start;
        while (!current.isAfter(end)) {
            dates.add(current.format(formatter));
            current = current.plusDays(1);
        }
        return dates;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean anewStatisHistoryBonus(String startDate, String endDate) {
        //查询顶点会员
        List<CuBonusVertexStatisVO> vertexList = vertexList(null);
        //会员订单信息
        List<CuBonusVertexStatisVO> orachListAll = new ArrayList<>();
        //查询新增订单
        CuBonusVertexStatisVO cbs = new CuBonusVertexStatisVO();
        //日期集合
        List<String> dates = getDatesInRange(startDate, endDate);
        for (String date : dates) {
            int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
            String settleTableName = TableNameConstants.CU_MEMBER_SETTLE + period;
            //累加好的数据存入soAll
            List<CuBonusVertexStatisVO> soAll = new ArrayList<>();
            cbs.setDelFlag(EDelFlag.UN_DELETE.getValue());
            cbs.setOrderStatus(EOrderStatus.PAY.getValue());
            cbs.setStartDate(date);
            cbs.setEndDate(date);
            cbs.setPeriod(period);
            cbs.setSettleTableName(settleTableName);
            cbs.setPkCountry(CountryConstants.CHINA_COUNTRY);
            for (CuBonusVertexStatisVO ve : vertexList) {
                cbs.setPkVertex(ve.getPkVertex());
                List<CuBonusVertexStatisVO> orachList = baseMapper.queryAnewSaOrderByLessDay(cbs);
                orachListAll.addAll(orachList);
            }
            //先查中国订单
            Map<Date, List<CuBonusVertexStatisVO>> orachListMap = orachListAll.stream().collect(Collectors.groupingBy(CuBonusVertexStatisVO::getCreationTime));
            //查询所有体系
            if (CollectionUtil.isNotEmpty(orachListAll)) {
                if (CollectionUtil.isNotEmpty(vertexList)) {
                    for (Map.Entry<Date, List<CuBonusVertexStatisVO>> entry : orachListMap.entrySet()) {
                        for (CuBonusVertexStatisVO ve : vertexList) {
                            CuBonusVertexStatisVO oldSo = new CuBonusVertexStatisVO();
                            addOrderAmount(oldSo, null, ve.getPkVertex(), entry.getValue(), 2);
                            if (oldSo.getPkCountry() != null) {
                                soAll.add(oldSo);
                            }
                        }
                    }
                }
            }
            //累加好的数据存入acAll
            List<CuBonusVertexStatisVO> acAll = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(vertexList)) {
                for (CuBonusVertexStatisVO ve : vertexList) {
                    cbs.setPkVertex(ve.getPkVertex());
                    //查询中国统计奖金
                    List<CuBonusVertexStatisVO> listCn = baseMapper.queryVertexChinaCountryBonus(cbs);
                    Map<Date, List<CuBonusVertexStatisVO>> listCnMap = listCn.stream().collect(Collectors.groupingBy(CuBonusVertexStatisVO::getCreationTime));
                    if (CollectionUtil.isNotEmpty(listCn)) {
                        for (Map.Entry<Date, List<CuBonusVertexStatisVO>> entry : listCnMap.entrySet()) {
                            CuBonusVertexStatisVO oldSo = new CuBonusVertexStatisVO();
                            for (CuBonusVertexStatisVO 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, List<Integer> pkVertexList) {
        return baseMapper.delStatis(startDate, endDate, pkVertexList);
    }

    @Override
    public List<CuBonusVertexStatisVO> bonusDeductlist(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.bonusDeductlist(cuBonusVertexStatisVO);
    }

    @Override
    public List<CuBonusVertexStatisVO> queryCuBonusStatis(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.queryCuBonusStatis(cuBonusVertexStatisVO);
    }

    @Override
    public List<CuBonusVertexStaticTotalVO> queryCuBonusStatisTotal(CuBonusVertexStaticTotalVO cuBonusVertexStaticTotalVO) {
        return baseMapper.queryCuBonusStatisTotal(cuBonusVertexStaticTotalVO);
    }

    @Override
    public CuBonusVertexStaticTotalVO queryCuBonusStatisSum(CuBonusVertexStaticTotalVO cuBonusVertexStaticTotalVO) {
        return baseMapper.queryCuBonusStatisSum(cuBonusVertexStaticTotalVO);
    }

    @Override
    public List<CuBonusVertexStaticTotalVO> queryCuBonusVertex(CuBonusVertexStaticTotalVO cuBonusVertexStaticTotalVO) {
        return baseMapper.queryCuBonusVertex(cuBonusVertexStaticTotalVO);
    }

    @Override
    public CuBonusVertexStaticTotalVO queryOrgTopNumber(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.queryOrgTopNumber(cuBonusVertexStatisVO);
    }

    @Override
    public CuBonusVertexStaticTotalVO queryTouch(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.queryTouch(cuBonusVertexStatisVO);
    }

    @Override
    public CuBonusVertexStatisVO queryCuBonusSumStatis(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.queryCuBonusSumStatis(cuBonusVertexStatisVO);
    }

    //累计中国奖金
    private CuBonusVertexStatisVO addChAchieve(CuBonusVertexStatisVO oldBon, CuBonusVertexStatisVO 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;
    }

    @Override
    public List<CuBonusVertexStatisVO> countrylist(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.countrylist(cuBonusVertexStatisVO);
    }

    @Override
    public List<CuBonusVertexStatisVO> vertexList(Integer pkVertex) {
        return baseMapper.vertexList(pkVertex);
    }

    /**
     * 累加订单金额
     **/
    private CuBonusVertexStatisVO addOrderAmount(CuBonusVertexStatisVO oldSo, Integer pkCountry, Integer pkVertex, List<CuBonusVertexStatisVO> orachList, int type) {
        for (CuBonusVertexStatisVO 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 void saveBonusStatisAchieve(List<CuBonusVertexStatisVO> cblist) {
        for (CuBonusVertexStatisVO cb : cblist) {
            if (cb.getPkCountry() == null) {
                continue;
            }
            //查询体系是否添加
            CuBonusVertexStatis bs = new CuBonusVertexStatis();
            bs.setPkBdVertex(cb.getPkVertex());
            bs.setPkTeamCode(cb.getPkTeamCode());
            bs.setCreationTime(cb.getCreationTime());
            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.setRepurPushIncome(cb.getRepurPushIncome());
            bs.setHiFunIncome(cb.getHiFunIncome());
            bs.setCalFirAchieve(cb.getCalFirAchieve());
            bs.setCalRepAchieve(cb.getCalRepAchieve());

            // 查询数据库判断记录是否存在
            List<CuBonusVertexStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                // 不存在则插入新记录
                baseMapper.insert(bs);
            } else {
                // 设置主键ID
                bs.setPkId(existingRecord.get(0).getPkId());
                // 存在则更新记录
                baseMapper.updateById(bs);
            }
        }
    }

    /**
     * 保存奖金拨比订单数据
     **/
    private void saveBonusStatis(List<CuBonusVertexStatisVO> soList) {
        for (CuBonusVertexStatisVO so : soList) {
            if (so.getPkCountry() == null) {
                continue;
            }
            CuBonusVertexStatis bs = new CuBonusVertexStatis();
            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());
            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<CuBonusVertexStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                // 不存在则插入新记录
                baseMapper.insert(bs);
            } else {
                // 设置主键ID
                bs.setPkId(existingRecord.get(0).getPkId());
                // 存在则更新记录
                baseMapper.updateById(bs);
            }
        }
    }

    @Override
    public List<CuBonusVertexStatisVO> queryChinaCountryBonus(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.queryChinaCountryBonus(cuBonusVertexStatisVO);
    }

    // 获取或初始化金额
    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;
            }
        }
    }

    /**
     * 查询当天顶点统计数据
     **/
    public List<CuBonusVertexStatis> getCuBonusStatis(CuBonusVertexStatis CuBonusVertexStatis) {
        return baseMapper.getCuBonusStatis(CuBonusVertexStatis);
    }

}
