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
    public Boolean delStatis(String startDate, String endDate, List<Integer> pkVertexList) {
        return baseMapper.delStatis(startDate, endDate, pkVertexList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void anewStatisHistoryBonus(String startDate, String endDate) {
        //查询顶点会员
        List<CuBonusVertexStatisVO> topMemberList = vertexList(null);
        //会员订单信息
        List<CuBonusVertexStatisVO> orderListAll = new ArrayList<>();
        //日期集合
        List<String> dates = getDatesInRange(startDate, endDate);

        if (CollectionUtil.isNotEmpty(topMemberList)) {
            for (String date : dates) {
                int period = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
                String settleTableName = TableNameConstants.CU_MEMBER_RETAIL_RANGE + period;
                //累加好的数据存入soAll
                List<CuBonusVertexStatisVO> soAll = new ArrayList<>();
                //累加好的数据存入acAll
                List<CuBonusVertexStatisVO> acAll = new ArrayList<>();

                //查询新增订单
                CuBonusVertexStatisVO cbs = new CuBonusVertexStatisVO();
                cbs.setDelFlag(EDelFlag.UN_DELETE.getValue());
                cbs.setOrderStatus(EOrderStatus.PAY.getValue());
                cbs.setStartDate(date);
                cbs.setEndDate(date);
                cbs.setSettleTableName(settleTableName);
                cbs.setPkCountry(CountryConstants.CHINA_COUNTRY);

                for (CuBonusVertexStatisVO ve : topMemberList) {
                    // 使用的是顶点会员ID
                    cbs.setPkVertex(ve.getPkVertex());
                    orderListAll.addAll(baseMapper.queryAnewSaOrderByLessDay(cbs));
                }

                if (CollectionUtil.isNotEmpty(orderListAll)) {
                    // 订单map
                    Map<Date, List<CuBonusVertexStatisVO>> orderMap = orderListAll.stream().collect(Collectors.groupingBy(CuBonusVertexStatisVO::getCreationTime));
                    for (Map.Entry<Date, List<CuBonusVertexStatisVO>> entry : orderMap.entrySet()) {
                        for (CuBonusVertexStatisVO ve : topMemberList) {
                            CuBonusVertexStatisVO oldSo = new CuBonusVertexStatisVO();
                            addOrderAmount(oldSo, ve.getPkVertex(), entry.getValue(), 2);
                            if (null != oldSo.getPkVertex()) {
                                soAll.add(oldSo);
                            }
                        }
                    }
                }

                for (CuBonusVertexStatisVO ve : topMemberList) {
                    cbs.setPkVertex(ve.getPkVertex());
                    // 查询奖金
                    List<CuBonusVertexStatisVO> listCn = baseMapper.queryVertexChinaCountryBonus(cbs);
                    if (CollectionUtil.isNotEmpty(listCn)) {
                        Map<Date, List<CuBonusVertexStatisVO>> listCnMap = listCn.stream().collect(Collectors.groupingBy(CuBonusVertexStatisVO::getCreationTime));
                        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);
                                }
                            }
                            acAll.add(oldSo);
                        }
                    }
                }
                //存入订单信息
                saveBonusStatis(soAll);
                //存入国内奖金信息
                saveBonusStatisAchieve(acAll);
            }
        }
    }

    @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 void addChAchieve(CuBonusVertexStatisVO oldBon, CuBonusVertexStatisVO newBon) {
        oldBon.setPkCountry(newBon.getPkCountry());
        oldBon.setCreationTime(newBon.getCreationTime());
        oldBon.setPkVertex(newBon.getPkVertex());
        oldBon.setPkTeamCode(newBon.getPkTeamCode());
        oldBon.setRealIncomeTotal(newBon.getRealIncomeTotal());
        oldBon.setDirectIncome(newBon.getDirectIncome());
        oldBon.setStoreIncome(newBon.getStoreIncome());
        oldBon.setRetailRangeIncome(newBon.getRetailRangeIncome());
        oldBon.setRetailSameLevelIncome(newBon.getRetailSameLevelIncome());
        oldBon.setGlobalPoints(newBon.getGlobalPoints());
        oldBon.setRangeIncome41(newBon.getRangeIncome41());
        oldBon.setRangeIncome43(newBon.getRangeIncome43());
        oldBon.setRangeIncome47(newBon.getRangeIncome47());
        oldBon.setSameLevelIncome41(newBon.getSameLevelIncome41());
        oldBon.setSameLevelIncome43(newBon.getSameLevelIncome43());
    }

    @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()
                        // 此处使用的是会员ID
                        .pkVertex(cuMemberExt.getPkVertex().intValue())
                        .memberCode(cuMemberExt.getMemberCode())
                        .memberName(cuMemberExt.getMemberName())
                        .build());
            }
        }
        return list;
    }

    /**
     * 累加订单金额
     **/
    private void addOrderAmount(CuBonusVertexStatisVO oldSo, Integer pkVertex, List<CuBonusVertexStatisVO> orachList, int type) {
        for (CuBonusVertexStatisVO newSo : orachList) {
            // 修改统计数据
            if (pkVertex != null && pkVertex.equals(newSo.getPkVertex())) {
                oldSo.setPkCountry(newSo.getPkCountry());
                oldSo.setCreationTime(newSo.getCreationTime());
                oldSo.setPkVertex(newSo.getPkVertex());
                if (newSo.getPkTeamCode() != null) {
                    oldSo.setPkTeamCode(newSo.getPkTeamCode());
                }
                switch (EOrderType.getEnumByValue(newSo.getOrderType())) {
                    case RETAIL_REGISTER:
                        // 精品专区（41）
                        oldSo.setMainRegAmount(addOrInitializeAmount(oldSo.getMainRegAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainRegPv(addOrInitializeAmount(oldSo.getMainRegPv(), newSo.getOrderAchieve(), type));
                        break;
                    case RETAIL_UPGRADE:
                        // 甄选专区（42）
                        oldSo.setMainUpAmount(addOrInitializeAmount(oldSo.getMainUpAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainUpPv(addOrInitializeAmount(oldSo.getMainUpPv(), newSo.getOrderAchieve(), type));
                        break;
                    case RETAIL_REPURCHASE:
                        // 商城专区（43）
                        oldSo.setMainRepurAmount(addOrInitializeAmount(oldSo.getMainRepurAmount(), newSo.getOrderAmount(), type));
                        oldSo.setMainRepurPv(addOrInitializeAmount(oldSo.getMainRepurPv(), newSo.getOrderAchieve(), type));
                        break;
                    case DISCOUNT_ORDER:
                        // 五折专区（47）
                        oldSo.setRetailConsumeAmount(addOrInitializeAmount(oldSo.getRetailConsumeAmount(), newSo.getOrderAmount(), type));
                        oldSo.setRetailConsumePv(addOrInitializeAmount(oldSo.getRetailConsumePv(), newSo.getOrderAchieve(), type));
                        break;
                    default:
                        break;
                }
            }
        }
    }

    /**
     * 存入国内奖金信息
     **/
    private void saveBonusStatisAchieve(List<CuBonusVertexStatisVO> cblist) {
        for (CuBonusVertexStatisVO cb : cblist) {
            // 查询是否添加
            CuBonusVertexStatis bs = new CuBonusVertexStatis();
            bs.setPkBdVertex(cb.getPkVertex());
            bs.setPkCountry(cb.getPkCountry());
            bs.setCreationTime(cb.getCreationTime());
            bs.setRealIncomeTotal(cb.getRealIncomeTotal());

            bs.setIntroduceBonus(cb.getDirectIncome());
            bs.setGlobalPoints(cb.getGlobalPoints());
            bs.setStoreIncome(cb.getStoreIncome());
            bs.setRetailRangeIncome(cb.getRetailRangeIncome());
            bs.setRetailSameLevelIncome(cb.getRetailSameLevelIncome());
            bs.setRangeIncome41(cb.getRangeIncome41());
            bs.setRangeIncome43(cb.getRangeIncome43());
            bs.setRangeIncome47(cb.getRangeIncome47());
            bs.setSameLevelIncome41(cb.getSameLevelIncome41());
            bs.setSameLevelIncome43(cb.getSameLevelIncome43());

            // 查询数据库判断记录是否存在
            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) {
            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 (currentAmount != null) {
            if (type == 1) {
                return currentAmount.subtract(newAmount);
            } else {
                return currentAmount.add(newAmount);
            }
        }
        return newAmount;
    }

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

}
