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.domain.member.statis.CuBonusVertexStatis;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.base.service.ICuMemberService;
import com.hzs.member.statis.mapper.CuBonusLenjoyStatisMapper;
import com.hzs.member.statis.service.ICuBonusLenjoyStatisService;
import com.hzs.member.statis.vo.CuBonusLenjoyStatisVO;
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 CuBonusLenjoyStatisServiceImpl extends ServiceImpl<CuBonusLenjoyStatisMapper, CuBonusVertexStatis> implements ICuBonusLenjoyStatisService {

    @Autowired
    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;
    @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<CuBonusLenjoyStatisVO> vertexList = vertexList(null);
        //会员订单信息
        List<CuBonusLenjoyStatisVO> orachListAll = new ArrayList<>();
        //查询新增订单
        CuBonusLenjoyStatisVO cbs = new CuBonusLenjoyStatisVO();
        //日期集合
        List<String> dates = getDatesInRange(startDate, endDate);
        for (String date : dates) {
            int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(date).getPkId();
            String settleTableName = TableNameConstants.CU_MEMBER_RANGE + period;
            Integer count = iCuMemberService.selectExistTable(settleTableName);
            if (count == 0) {
                continue;
            }
            //累加好的数据存入soAll
            List<CuBonusLenjoyStatisVO> 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 (CuBonusLenjoyStatisVO ve : vertexList) {
                cbs.setPkVertex(ve.getPkVertex());
                List<CuBonusLenjoyStatisVO> orachList = baseMapper.queryAnewSaOrderByLessDay(cbs);
                orachListAll.addAll(orachList);
            }
            Map<Date, List<CuBonusLenjoyStatisVO>> orachListMap = orachListAll.stream()
                    .collect(Collectors.groupingBy(CuBonusLenjoyStatisVO::getCreationTime));
            if (CollectionUtil.isNotEmpty(orachListAll)) {
                if (CollectionUtil.isNotEmpty(vertexList)) {
                    for (Map.Entry<Date, List<CuBonusLenjoyStatisVO>> entry : orachListMap.entrySet()) {
                        for (CuBonusLenjoyStatisVO ve : vertexList) {
                            CuBonusLenjoyStatisVO oldSo = new CuBonusLenjoyStatisVO();
                            oldSo = addOrderAmount(oldSo, null, ve.getPkVertex(), entry.getValue(), 2);
                            if (oldSo.getPkCountry() != null) {
                                soAll.add(oldSo);
                            }
                        }
                    }
                }
            }
            //累加好的数据存入acAll
            List<CuBonusLenjoyStatisVO> acAll = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(vertexList)) {
                for (CuBonusLenjoyStatisVO ve : vertexList) {
                    cbs.setPkVertex(ve.getPkVertex());
                    //查询中国统计奖金
                    List<CuBonusLenjoyStatisVO> listCn = baseMapper.queryVertexChinaCountryBonus(cbs);
                    Map<Date, List<CuBonusLenjoyStatisVO>> listCnMap = listCn.stream()
                            .collect(Collectors.groupingBy(CuBonusLenjoyStatisVO::getCreationTime));
                    if (CollectionUtil.isNotEmpty(listCn)) {
                        for (Map.Entry<Date, List<CuBonusLenjoyStatisVO>> entry : listCnMap.entrySet()) {
                            CuBonusLenjoyStatisVO oldSo = new CuBonusLenjoyStatisVO();
                            for (CuBonusLenjoyStatisVO cb : entry.getValue()) {
                                if (ve.getPkVertex().equals(cb.getPkVertex())) {
                                    oldSo = 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<CuBonusLenjoyStatisVO> queryCuBonusStatis(CuBonusLenjoyStatisVO CuBonusLenjoyStatisVO) {
        return baseMapper.queryCuBonusStatis(CuBonusLenjoyStatisVO);
    }

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

    //累计中国奖金
    private CuBonusLenjoyStatisVO addChAchieve(CuBonusLenjoyStatisVO oldBon, CuBonusLenjoyStatisVO newBon) {
        oldBon.setPkCountry(newBon.getPkCountry());
        oldBon.setCreationTime(newBon.getCreationTime());
        oldBon.setPkVertex(newBon.getPkVertex());
        oldBon.setCloudRealSubtotal(addOrInitializeAmount(oldBon.getCloudRealSubtotal(), newBon.getRealIncome(), 2));
        return oldBon;
    }

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


    /**
     * 累加订单金额
     **/
    private CuBonusLenjoyStatisVO addOrderAmount(CuBonusLenjoyStatisVO oldSo, Integer pkCountry, Integer pkVertex, List<CuBonusLenjoyStatisVO> orachList, int type) {
        for (CuBonusLenjoyStatisVO 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());
                }
            }
        }
        return oldSo;
    }

    private void saveBonusStatisAchieve(List<CuBonusLenjoyStatisVO> cblist) {
        for (CuBonusLenjoyStatisVO cb : cblist) {
            if (cb.getPkCountry() == null) {
                continue;
            }
            //查询体系是否添加
            CuBonusVertexStatis bs = new CuBonusVertexStatis();
            bs.setPkBdVertex(cb.getPkVertex());
            bs.setCreationTime(cb.getCreationTime());
            bs.setPkCountry(cb.getPkCountry());
            bs.setCloudRealSubtotal(cb.getCloudRealSubtotal());
            // 查询数据库判断记录是否存在
            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<CuBonusLenjoyStatisVO> soList) {
        for (CuBonusLenjoyStatisVO so : soList) {
            if (so.getPkCountry() == null) {
                continue;
            }
            CuBonusVertexStatis bs = new CuBonusVertexStatis();
            bs.setPkBdVertex(so.getPkVertex());
            bs.setCreationTime(so.getCreationTime());
            bs.setPkCountry(so.getPkCountry());
            // 查询数据库判断记录是否存在
            List<CuBonusVertexStatis> existingRecord = getCuBonusStatis(bs);
            if (CollectionUtil.isEmpty(existingRecord)) {
                baseMapper.insert(bs); // 不存在则插入新记录
            } else {
                bs.setPkId(existingRecord.get(0).getPkId()); // 设置主键ID
                baseMapper.updateById(bs); // 存在则更新记录
            }
        }

    }

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

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

}
