package com.hzs.bonus.bonus.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.bonus.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.bonus.bonus.mapper.CuBonusExpandMapper;
import com.hzs.bonus.bonus.param.BonusExpandParam;
import com.hzs.bonus.bonus.service.IBonusSettleService;
import com.hzs.bonus.bonus.service.ICuBonusExpandService;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.bonus.CuBonusExpand;
import com.hzs.common.domain.member.ext.CuBonusExpandExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.sale.order.ISaOrderServiceApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 服务实现类
 */
@Service
public class CuBonusExpandServiceImpl extends ServiceImpl<CuBonusExpandMapper, CuBonusExpand> implements ICuBonusExpandService {

    @DubboReference
    ISaOrderServiceApi iSaOrderServiceApi;

    @Autowired
    private ICuMemberSettlePeriodService iCuMemberSettlePeriodService;
    @Autowired
    private IBonusSettleService iBonusSettleService;

    @Override
    public List<CuBonusExpandExt> queryBonusExpand(BonusExpandParam bonusExpandParam) {
        return baseMapper.queryBonusExpand(bonusExpandParam);
    }

    @Override
    public List<CuBonusExpandExt> queryBonusExpandDis(BonusExpandParam bonusExpandParam) {
        return baseMapper.queryBonusExpandDis(bonusExpandParam);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void firstSaveCuBonusExpand(BonusExpandParam bonusExpandParam) {
        List<CuBonusExpand> bonusExpandList = queryCuBonusExpand(bonusExpandParam.getSettleDate(), bonusExpandParam.getPkCountry());
        if (CollectionUtil.isEmpty(bonusExpandList)) {
            // 查询
            List<CuBonusExpand> cuBonusExpandList = queryCuBonusExpand(DateUtils.beforeDate(1, ChronoUnit.DAYS, bonusExpandParam.getSettleDate()), bonusExpandParam.getPkCountry());
            Map<Long, CuBonusExpand> cuBonusExpandMap = new HashMap<>();
            cuBonusExpandList.forEach(cuBonusExpand -> cuBonusExpandMap.put(cuBonusExpand.getPkMember(), cuBonusExpand));
            // 查询0线
            List<CuBonusExpand> saveBonusExpandList = baseMapper.queryZeroMemberByVertex();
            for (CuBonusExpand saveBonusExpand : saveBonusExpandList) {
                saveBonusExpand.setSettleDate(bonusExpandParam.getSettleDate());
                saveBonusExpand.setPkCreator(MagicNumberConstants.PK_ADMIN);
                if (cuBonusExpandMap.containsKey(saveBonusExpand.getPkMember())) {
                    CuBonusExpand cuBonusExpand = cuBonusExpandMap.get(saveBonusExpand.getPkMember());
                    saveBonusExpand.setAddTouch(cuBonusExpand.getAddTouch());
                    saveBonusExpand.setExpandRatio(cuBonusExpand.getExpandRatio());
                    saveBonusExpand.setExpandNumber(cuBonusExpand.getExpandNumber());
                }
                if (bonusExpandParam.getAddTouch() != null) {
                    saveBonusExpand.setAddTouch(bonusExpandParam.getAddTouch());
                    saveBonusExpand.setExpandRatio(bonusExpandParam.getExpandRatio());
                    saveBonusExpand.setExpandNumber(bonusExpandParam.getExpandNumber());
                }
            }
            saveBatch(saveBonusExpandList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCuBonusExpandRatio(BonusExpandParam bonusExpandParam, String tableName) {
        // 查询结算的4-n碰次设置
        List<CuBonusExpand> cuBonusExpandList = queryCuBonusExpand(bonusExpandParam.getSettleDate(), bonusExpandParam.getPkCountry());
        if (CollectionUtil.isNotEmpty(cuBonusExpandList)) {
            Date settleDate = bonusExpandParam.getSettleDate();
            Map<Long, CuBonusExpand> bonusExpandMap = new HashMap<>();
            List<Long> memberIdList = new ArrayList<>();
            cuBonusExpandList.forEach(cuBonusExpand -> {
                bonusExpandMap.put(cuBonusExpand.getPkMember(), cuBonusExpand);
                memberIdList.add(cuBonusExpand.getPkMember());
            });
            bonusExpandParam.setMemberIdList(memberIdList);
            // 计算所有体系日波比
            packageBonusExpandParam(bonusExpandParam, settleDate, settleDate);

            // TODO new 当日首购拨比：奖金 除 订单金额
            List<CuBonusExpand> dayBonusExpandList = baseMapper.calculateDayRatioByBonusExpandParam(bonusExpandParam, tableName);
            if (CollectionUtil.isNotEmpty(dayBonusExpandList)) {
                for (CuBonusExpand cuBonusExpand : dayBonusExpandList) {
                    if (bonusExpandMap.containsKey(cuBonusExpand.getPkMember())) {
                        CuBonusExpand bonusExpand = bonusExpandMap.get(cuBonusExpand.getPkMember());
                        bonusExpand.setDayAchieve(cuBonusExpand.getDayAchieve());
                        bonusExpand.setDayBonus(cuBonusExpand.getDayBonus());
                        if ("cu_member_bonus".equals(tableName) || !ComputeUtil.compareValue(bonusExpand.getYesDayRatio())) {
                            bonusExpand.setYesDayRatio(cuBonusExpand.getYesDayRatio());
                        }
                        bonusExpand.setCurDayRatio(cuBonusExpand.getYesDayRatio());
                    }
                }
            }
            // TODO new 当日复购拨比：奖金 除 订单金额
            List<CuBonusExpand> dayRepBonusExpandList = baseMapper.calculateDayRepRatioByBonusExpandParam(bonusExpandParam, tableName);
            if (CollectionUtil.isNotEmpty(dayRepBonusExpandList)) {
                for (CuBonusExpand cuBonusExpand : dayRepBonusExpandList) {
                    if (bonusExpandMap.containsKey(cuBonusExpand.getPkMember())) {
                        CuBonusExpand bonusExpand = bonusExpandMap.get(cuBonusExpand.getPkMember());
                        bonusExpand.setDayRepAchieve(cuBonusExpand.getDayRepAchieve());
                        bonusExpand.setDayRepBonus(cuBonusExpand.getDayRepBonus());
                        bonusExpand.setCurDayRepRatio(cuBonusExpand.getCurDayRepRatio());
                    }
                }
            }

            // 计算所有体系月波比
            // 获得当前月第一天，获得当前月最后一天
            packageBonusExpandParam(bonusExpandParam, DateUtils.currentMonthFirstDate(settleDate), settleDate);
            // TODO new 当月首购拨比：奖金 除 订单金额
            List<CuBonusExpand> monthBonusExpandList = baseMapper.calculateDayRatioByBonusExpandParam(bonusExpandParam, tableName);
            if (CollectionUtil.isNotEmpty(monthBonusExpandList)) {
                for (CuBonusExpand cuBonusExpand : monthBonusExpandList) {
                    if (bonusExpandMap.containsKey(cuBonusExpand.getPkMember())) {
                        CuBonusExpand bonusExpand = bonusExpandMap.get(cuBonusExpand.getPkMember());
                        bonusExpand.setMonthAchieve(cuBonusExpand.getDayAchieve());
                        bonusExpand.setMonthBonus(cuBonusExpand.getDayBonus());
                        bonusExpand.setMonthRatio(cuBonusExpand.getYesDayRatio());
                    }
                }
            }
            // 批量更新数据，更新4-n的波比
            baseMapper.mergeBonusExpandByList(new ArrayList<>(bonusExpandMap.values()));
        }
    }

    private void packageBonusExpandParam(BonusExpandParam bonusExpandParam, Date settleDate, Date endDate) {
        bonusExpandParam.setStartDate(settleDate);
        bonusExpandParam.setEndDate(DateUtils.afterDate(1, ChronoUnit.DAYS, endDate));
        CuMemberSettlePeriod startPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, bonusExpandParam.getStartDate()));
        CuMemberSettlePeriod endPeriod = iCuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, endDate));
        bonusExpandParam.setStartPeriod(startPeriod.getPkId());
        bonusExpandParam.setEndPeriod(endPeriod.getPkId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveCuBonusExpand(BonusExpandParam bonusExpandParam) {
        if (bonusExpandParam.getPkId() == null) {
            firstSaveCuBonusExpand(bonusExpandParam);
        } else {
            // 查询原数据  增加明细表
            CuBonusExpand cuBonusExpand = baseMapper.selectById(bonusExpandParam.getPkId());
            CuBonusExpand saveBonusExpand = BeanUtil.copyProperties(cuBonusExpand, CuBonusExpand.class);
            saveBonusExpand.setPkId(null);
            saveBonusExpand.setPkParent(cuBonusExpand.getPkId());
            save(saveBonusExpand);
            // 2 更新主表
            LambdaUpdateWrapper<CuBonusExpand> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.set(CuBonusExpand::getAddTouch, bonusExpandParam.getAddTouch());
            updateWrapper.set(CuBonusExpand::getExpandRatio, bonusExpandParam.getExpandRatio());
            updateWrapper.set(CuBonusExpand::getExpandNumber, bonusExpandParam.getExpandNumber());
            updateWrapper.set(CuBonusExpand::getPkModified, bonusExpandParam.getPkModified());
            updateWrapper.set(CuBonusExpand::getModifiedTime, DateUtils.currentDateTime());
            updateWrapper.eq(CuBonusExpand::getPkId, bonusExpandParam.getPkId());
            update(updateWrapper);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void repeatCuBonusByExpand(BonusExpandParam bonusExpandParam) {
        String settleDate = DateUtils.parseDateToFormat(DateUtils.YYYY_MM_DD, bonusExpandParam.getSettleDate());
        Date endDate = DateUtils.afterDate(1, ChronoUnit.DAYS, bonusExpandParam.getSettleDate());
        // 查询订单
        List<SaOrderExt> saOrderExtList = iSaOrderServiceApi.queryRepeatSaOrderByDay(bonusExpandParam.getSettleDate(), endDate).getData();
        baseMapper.truncateTable();
        // 重算奖金
        iBonusSettleService.repeatCuMemberBonusByExpand(settleDate, saOrderExtList);
        // 更新波比、业绩
        updateCuBonusExpandRatio(bonusExpandParam, "cu_member_repeat_bonus");
    }

    private List<CuBonusExpand> queryCuBonusExpand(Date settleDate, Integer pkCountry) {
        LambdaQueryWrapper<CuBonusExpand> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CuBonusExpand::getSettleDate, settleDate);
        if (pkCountry != null) {
            queryWrapper.eq(CuBonusExpand::getPkCountry, pkCountry);
        }
        queryWrapper.isNull(CuBonusExpand::getPkParent);
        return baseMapper.selectList(queryWrapper);
    }

}
