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.EDelFlag;
import com.hzs.common.core.enums.EOrderStatus;
import com.hzs.common.core.enums.EOrderType;
import com.hzs.common.domain.member.ext.CuMemberExt;
import com.hzs.common.domain.member.statis.CuBonusVertexStatis;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.statis.mapper.CuBonusVertexStatisMapper;
import com.hzs.member.statis.service.ICuBonusVertexStatisService;
import com.hzs.member.statis.vo.CuBonusVertexStatisPvVO;
import com.hzs.member.statis.vo.CuBonusVertexStatisTotalVO;
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.*;
import java.util.stream.Collectors;

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

    @Autowired
    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;
    @Autowired
    private ICuMemberService iCuMemberService;

    /**
     * 通过日期范围，返回范围内每天的日期
     **/
    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_RETAIL_RANGE + 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> queryCuBonusStatis(CuBonusVertexStatisVO cuBonusVertexStatisVO) {
        return baseMapper.queryCuBonusStatis(cuBonusVertexStatisVO);
    }

    @Override
    public List<CuBonusVertexStatisPvVO> queryCuBonusPvStatis(CuBonusVertexStatisPvVO cuBonusVertexStatisPvVO) {
        return baseMapper.queryCuBonusPvStatis(cuBonusVertexStatisPvVO);
    }

    @Override
    public List<CuBonusVertexStatisTotalVO> queryCuBonusStatisTotal(CuBonusVertexStatisTotalVO cuBonusVertexStatisTotalVO) {
        return baseMapper.queryCuBonusStatisTotal(cuBonusVertexStatisTotalVO);
    }

    @Override
    public CuBonusVertexStatisTotalVO queryCuBonusStatisSum(CuBonusVertexStatisTotalVO cuBonusVertexStatisTotalVO) {
        return baseMapper.queryCuBonusStatisSum(cuBonusVertexStatisTotalVO);
    }

    @Override
    public List<CuBonusVertexStatisTotalVO> queryCuBonusVertex(CuBonusVertexStatisTotalVO cuBonusVertexStatisTotalVO) {
        return baseMapper.queryCuBonusVertex(cuBonusVertexStatisTotalVO);
    }

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

    @Override
    public CuBonusVertexStatisPvVO queryCuBonusPvSumStatis(CuBonusVertexStatisPvVO cuBonusVertexStatisPvVO) {
        return baseMapper.queryCuBonusPvSumStatis(cuBonusVertexStatisPvVO);
    }

    //累计中国奖金
    private CuBonusVertexStatisVO addChAchieve(CuBonusVertexStatisVO oldBon, CuBonusVertexStatisVO newBon) {
        oldBon.setPkCountry(newBon.getPkCountry());
        oldBon.setCreationTime(newBon.getCreationTime());
        oldBon.setPkVertex(newBon.getPkVertex());
        oldBon.setPkTeamCode(newBon.getPkTeamCode());
        oldBon.setRetailRangeIncome(newBon.getRetailRangeIncome());
//        oldBon.setRetailSameLevelIncomeV1V4(newBon.getRetailSameLevelIncomeV1V4());
        oldBon.setRetailSameLevelIncomeV5(newBon.getRetailSameLevelIncomeV5());
        oldBon.setRetailAreaIncome(newBon.getRetailAreaIncome());
        oldBon.setRetailBenefitRangeIncome(newBon.getRetailBenefitRangeIncome());
        oldBon.setRetailBenefitAvgIncome(newBon.getRetailBenefitAvgIncome());
        oldBon.setRetailBenefitIncome(newBon.getRetailBenefitIncome());
        oldBon.setBackPoints(newBon.getBackPoints());
        oldBon.setRealIncomeTotal(newBon.getRealIncomeTotal());
        return oldBon;
    }

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

    @Override
    public List<CuBonusVertexStatisVO> vertexList(Integer pkVertex) {
        List<CuBonusVertexStatisVO> list = new ArrayList<>();

        List<CuMemberExt> memberList = iCuMemberService.vertexList();
        if (CollectionUtil.isNotEmpty(memberList)) {
            for (CuMemberExt cuMemberExt : memberList) {
                list.add(CuBonusVertexStatisVO.builder()
                        .pkVertex(cuMemberExt.getPkVertex().intValue())
                        .memberCode(cuMemberExt.getMemberCode())
                        .memberName(cuMemberExt.getMemberName())
                        .build());
            }
        }
        return list;
    }

    /**
     * 累加订单金额
     **/
    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 RETAIL_REGISTER:
                        oldSo.setMainRegAmount(addOrInitializeAmount(oldSo.getMainRegAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainRegPv(addOrInitializeAmount(oldSo.getMainRegPv(), newSo.getOrderAchieve(), type));
                        break;
                    // 升级
                    case RETAIL_UPGRADE:
                        oldSo.setMainUpAmount(addOrInitializeAmount(oldSo.getMainUpAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainUpPv(addOrInitializeAmount(oldSo.getMainUpPv(), 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;
                    //重消 44
                    case RETAIL_CONSUME:
                        oldSo.setRetailConsumeAmount(addOrInitializeAmount(oldSo.getRetailConsumeAmount(), newSo.getOrderAmount(), type));
                        oldSo.setRetailConsumePv(addOrInitializeAmount(oldSo.getRetailConsumePv(), 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.setPkCountry(cb.getPkCountry());
            bs.setPkBdVertex(cb.getPkVertex());
            bs.setCreationTime(cb.getCreationTime());
            bs.setRetailRangeIncome(cb.getRetailRangeIncome());
            bs.setRetailSameLevelIncomeV1V4(cb.getRetailSameLevelIncomeV1V4());
            bs.setRetailSameLevelIncomeV5(cb.getRetailSameLevelIncomeV5());
            bs.setRetailAreaIncome(cb.getRetailAreaIncome());
            bs.setRetailBenefitAvgIncome(cb.getRetailBenefitAvgIncome());
            bs.setRetailBenefitRangeIncome(cb.getRetailBenefitRangeIncome());
            bs.setRetailBenefitIncome(cb.getRetailBenefitIncome());
            bs.setRealIncomeTotal(cb.getRealIncomeTotal());
            // 查询数据库判断记录是否存在
            List<CuBonusVertexStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                baseMapper.insert(bs); // 不存在则插入新记录
            } else {
                bs.setPkId(existingRecord.get(0).getPkId()); // 设置主键ID
                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.setMainRegPv(so.getMainRegPv());
            bs.setMainUpAmount(so.getMainUpAmount());
            bs.setMainUpPv(so.getMainUpPv());
            bs.setMainRepurAmount(so.getMainRepurAmount());
            bs.setMainRepurPv(so.getMainRepurPv());
            bs.setRetailConsumeAmount(so.getRetailConsumeAmount());
            bs.setRetailConsumePv(so.getRetailConsumePv());
            // 查询数据库判断记录是否存在
            List<CuBonusVertexStatis> 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;
            }
        }
    }

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

}
