package com.hzs.member.detail.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.constant.TableNameConstants;
import com.hzs.common.core.enums.*;
import com.hzs.common.core.utils.ComputeUtil;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.core.utils.StringUtils;
import com.hzs.common.domain.member.achieve.CuMemberSettlePeriod;
import com.hzs.common.domain.member.detail.CuMemberAssess;
import com.hzs.common.domain.member.detail.CuMemberAssessDetail;
import com.hzs.common.domain.member.ext.CuMemberAssessExt;
import com.hzs.common.domain.member.ext.CuMemberSettleExt;
import com.hzs.common.domain.sale.order.SaOrder;
import com.hzs.common.domain.system.config.BdAwards;
import com.hzs.member.achieve.service.ICuMemberSettlePeriodService;
import com.hzs.member.achieve.service.ICuMemberTreeService;
import com.hzs.member.achieve.service.impl.CuMemberBonusSettle;
import com.hzs.member.detail.mapper.CuMemberAssessMapper;
import com.hzs.member.detail.service.ICuMemberAssessDetailService;
import com.hzs.member.detail.service.ICuMemberAssessService;
import com.hzs.member.detail.vo.CuMemberAssessVO;
import com.hzs.system.config.IAwardsServiceApi;
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.math.BigDecimal;
import java.time.temporal.ChronoUnit;
import java.util.*;

/**
 * 会员信息-会员考核记录 服务实现类
 */
@Service
public class CuMemberAssessServiceImpl extends ServiceImpl<CuMemberAssessMapper, CuMemberAssess> implements ICuMemberAssessService {

    private ICuMemberTreeService cuMemberTreeService;

    private ICuMemberSettlePeriodService cuMemberSettlePeriodService;

    private ICuMemberAssessDetailService cuMemberAssessDetailService;

    @Autowired
    private CuMemberBonusSettle cuMemberBonusSettle;

    @DubboReference
    IAwardsServiceApi awardsServiceApi;

    @Autowired
    public void setCuMemberAssessDetailService(ICuMemberAssessDetailService cuMemberAssessDetailService) {
        this.cuMemberAssessDetailService = cuMemberAssessDetailService;
    }

    @Autowired
    public void setCuMemberSettlePeriodService(ICuMemberSettlePeriodService cuMemberSettlePeriodService) {
        this.cuMemberSettlePeriodService = cuMemberSettlePeriodService;
    }

    @Autowired
    public void setCuMemberTreeService(ICuMemberTreeService cuMemberTreeService) {
        this.cuMemberTreeService = cuMemberTreeService;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initCuMemberAssessData(String settleDate, int period) {
        // 复购考核，初始化值，值的来源是cu_member_tree上月最后一天的那一期的网体数据
        // 初始化值跟最终运算需要分开，防止凌晨12点正好有人支付。
        // 根据网体获得需要考核的人员，所有人员
        // 免考状态为 免考的顺道修改为考核通过
        // 每年一张表，查询的时候只能查询进2年的值
        // 结算的是月底那天需要进行考核
        Date currentDate = DateUtils.afterDate(1, ChronoUnit.DAYS, DateUtils.parseStringToDate(settleDate));
        // 每年1月1日开始创建表
        // 判断当前时间是每年第一天，需要初始化表
        if (DateUtils.currentDay(currentDate) == 1) {
            // 考核表
            String tableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.currentYear(currentDate);
            Integer num = cuMemberTreeService.queryExistOracleTable(tableName);
            if (num == null || num <= 0) {
                // 判断是否存在年表
                baseMapper.createCuMemberAssessTable(tableName);
                baseMapper.createCuMemberTableUniqueIndex(tableName);
                cuMemberTreeService.createCuMemberTableSequence(tableName, TableNameConstants.CU_MEMBER_ASSESS_SEQ);
            }
            calculationCuMemberAssess(currentDate);
        }

    }

    /**
     * 复购考核每月第一次考核调用此方法
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void calculationCuMemberAssess(Date currentDate) {
        // 查询当前时间的第一天跟最后一天
        // 需要验证考核国家是否有复购考核 分红考核
        // 考核日期不能跨越考核，只能当月考核，当月考核上月
        if (DateUtils.currentDay(currentDate) == 1) {
            String currentMonthFirstDate = DateUtils.currentMonthFirstDateStr(currentDate);
            Integer currentPeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(currentMonthFirstDate).getPkId();
            String currentTableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.getYear(currentMonthFirstDate);
            // 清空数据  根据期数清空cu_member_assess  cu_member_assess_detail表数据
            initCurrentAssess(currentDate, currentTableName, currentPeriod);
            // 初始化复购考核的上月结余
            initCurrentAssessByBeforeMonth(currentDate, currentTableName, currentPeriod, EAssessmentType.REPURCHASE_ASSESS.getValue());
            // 初始化分红考核的上月结余
            initCurrentAssessByBeforeMonth(currentDate, currentTableName, currentPeriod, EAssessmentType.SHARE_ASSESS.getValue());
            // 更新当月结余 结余会同时更新复购跟分红，只需要更新一次
            // 1 有免考状态的 本月使用是 0，考核状态是免考通过，免考将所有的值更改一下期末 期末= 期初+本月
            // 注意 不修改考核状态为通过的值，可能存在之前考核通过，又手动免考的人
            baseMapper.updateAssessPeriodExemptBalanceByUsed(currentTableName, currentPeriod);
            // 2 需要扣除通过的，需要记录流水
            // 记录流水，新增或修改
            cuMemberAssessDetailService.updateCuMemberAssessDetailByPeriod(currentTableName, currentPeriod);
            baseMapper.updateAssessPeriodCheckBalanceByUsed(currentTableName, currentPeriod);
        }
    }

    @Override
    public Map<Long, CuMemberAssess> queryCuMemberAssessByMember(String assessTableName, Integer period, Integer assessType, List<CuMemberSettleExt> cuMemberSettleExtList) {
        List<CuMemberAssess> cuMemberAssessList = new ArrayList<>();
        List<List<?>> listList = cuMemberBonusSettle.handleCutList(cuMemberSettleExtList);
        listList.forEach(list ->
                cuMemberAssessList.addAll(baseMapper.queryCuMemberAssessByMember(assessTableName, period, assessType, list)));
        Map<Long, CuMemberAssess> cuMemberAssessMap = new HashMap<>(ComputeUtil.mapInitCapacity(cuMemberAssessList.size()));
        cuMemberAssessList.forEach(cuMemberAssess -> cuMemberAssessMap.put(cuMemberAssess.getPkMember(), cuMemberAssess));
        return cuMemberAssessMap;
    }

    @Override
    public List<CuMemberAssess> queryCuMemberShareAssess(String tableName, Integer period) {
        return baseMapper.queryCuMemberShareAssess(tableName, period);
    }

    @Override
    public List<CuMemberAssessVO> selectAssessList(CuMemberAssessVO cuMemberAssessVO, List<Integer> orderTypeList) {
        Integer year;
        if (StringUtils.isNotNull(cuMemberAssessVO) && StringUtils.isNotNull(cuMemberAssessVO.getStartDate())) {
            year = DateUtils.currentYear(cuMemberAssessVO.getStartDate());
        } else {
            year = DateUtils.currentYear(new Date());
        }
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + year;
        if (StringUtils.isNotEmpty(tableName)) {
            return baseMapper.selectAssessList(tableName, cuMemberAssessVO.getPkMember(),
                    cuMemberAssessVO.getPkCountry(), cuMemberAssessVO.getAssessStatus(),
                    cuMemberAssessVO.getAssessType(), cuMemberAssessVO.getChangeType(), cuMemberAssessVO.getStartDate(),
                    cuMemberAssessVO.getEndDate(), orderTypeList, cuMemberAssessVO.getStartTradeTime(),
                    cuMemberAssessVO.getEndDateTradeTime()
            );
        }
        return null;
    }

    @Override
    public List<CuMemberAssessVO> getMemberAssessMonthList(CuMemberAssessVO cuMemberAssessVO) {
        Integer year;
        //获取期数
        Date date = new Date();
        if (StringUtils.isNotNull(cuMemberAssessVO) && StringUtils.isNotNull(cuMemberAssessVO.getStartDate())) {
            year = DateUtils.currentYear(cuMemberAssessVO.getStartDate());
        } else {
            year = DateUtils.currentYear(date);
        }
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + year;
        if (StringUtils.isNotEmpty(tableName)) {
            return baseMapper.getMemberAssessMonthList(tableName, cuMemberAssessVO.getPkMember(), cuMemberAssessVO.getAssessType(),
                    cuMemberAssessVO.getPkCountry(), null);
        }
        return null;
    }

    @Override
    public List<CuMemberAssessVO> getMemberAssessMonth(CuMemberAssessVO cuMemberAssessVO) {
        Integer year;
        //获取期数
        Date date = new Date();
        int period;
        if (StringUtils.isNotNull(cuMemberAssessVO) && StringUtils.isNotNull(cuMemberAssessVO.getStartDate())) {
            year = DateUtils.currentYear(cuMemberAssessVO.getStartDate());
            if (DateUtils.compareDateBefore(date, cuMemberAssessVO.getStartDate()) || DateUtils.compareDateEqual(date, cuMemberAssessVO.getStartDate())) {
                //获取当前月第一天
                Date date1 = DateUtils.currentMonthFirstDate(date);
                period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                        DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date1)).getPkId();
            } else {
                Date date1 = DateUtils.currentMonthFirstDate(cuMemberAssessVO.getStartDate());
                period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                        DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date1)).getPkId();
            }
        } else {
            year = DateUtils.currentYear(date);
            Date date1 = DateUtils.currentMonthFirstDate(date);
            period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(
                    DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, date1)).getPkId();
        }
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + year;
        if (StringUtils.isNotEmpty(tableName)) {
            return baseMapper.getMemberAssessMonthList(tableName, cuMemberAssessVO.getPkMember(), cuMemberAssessVO.getAssessType(),
                    cuMemberAssessVO.getPkCountry(), period);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void retryCalculationAssess(Date currentDate, Boolean flag) {
        String beforeDateStr = DateUtils.beforeDateStr(1, ChronoUnit.DAYS, DateUtils.YYYY_MM_DD, currentDate);
        Integer beforePeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(beforeDateStr).getPkId();
        Integer currentPeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, currentDate)).getPkId();
        String beforeTableName = TableNameConstants.CU_MEMBER_SETTLE + beforePeriod;
//        a)更新结算表会员前2部分会员免考状态 满足首次注册的会员 满足满足首次升级的会员
        String tableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.currentYear(currentDate);
        String currentMonthFirstDateStr = DateUtils.currentMonthFirstDateStr(currentDate);
        Integer monthFirstPeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(currentMonthFirstDateStr).getPkId();
        // 结算日期月份的第一天
        Date startDate = DateUtils.beforeMonthFirstDate(currentDate);
        // 结算日期后一天
        Date endDate = DateUtils.afterDate(1, ChronoUnit.DAYS, currentDate);
        String settleTableName = TableNameConstants.CU_MEMBER_SETTLE + currentPeriod;
        // 首次晋升、首次升级都是当月加下月考核，查询出上月1号到考核日期的值，
        // 等级看会员表支付时间，奖衔看奖衔变更表是否免考（分组取）,手动免考查看 最新的结算表手动考核
//        d)前一天不免考，后一天免考，需要做重新考核，直接变考核通过，原来考核通过的不回退考核金额，且考核状态为考核通过，不是免考通过
        // todo 所有的海粉会员设置复购考核失败，存在任意订单的海粉会员复购考核成功
        // 复购免考通过
        baseMapper.updateAssessCuMemberToRepExempt(tableName, settleTableName, monthFirstPeriod, startDate, endDate);
        // 奖金重算时更新结算表,flag=true代表奖金重算时，重算考核需要更新网体 flag=false 代表重算考核
        if (flag) {
            baseMapper.updateCuMemberSettleToRepExempt(settleTableName, startDate, endDate);
        }
        // 分红免考通过
        baseMapper.updateAssessCuMemberToShareExempt(tableName, settleTableName, monthFirstPeriod);
        // 查询出考核表免考的数据
        List<CuMemberAssess> oldCuMemberAssessList = baseMapper.queryExemptAssessCuMember(tableName, monthFirstPeriod);
//        b)查询前一天的会员免考记录，查询结算日会员免考记录
        List<CuMemberSettleExt> oldCuMemberSettleExtList = cuMemberTreeService.queryExemptCuMemberSettle(beforeTableName);
//        c)比较会员2天免考发生的状态，只需要计算变化的值，去掉没有发生变化的值
        List<CuMemberSettleExt> newCuMemberSettleExtList = new ArrayList<>();
        if (oldCuMemberAssessList.size() > 0 && oldCuMemberSettleExtList != null && oldCuMemberSettleExtList.size() > 0) {
            Map<String, CuMemberAssess> cuMemberAssessMap = new HashMap<>(ComputeUtil.mapInitCapacity(oldCuMemberAssessList.size()));
            oldCuMemberAssessList.forEach(cuMemberAssess ->
                    cuMemberAssessMap.put(cuMemberAssess.getPkMember().toString() + cuMemberAssess.getAssessType().toString(), cuMemberAssess));
            oldCuMemberSettleExtList.forEach(cuMemberSettleExt -> {
                String key = cuMemberSettleExt.getPkMember().toString() + cuMemberSettleExt.getAssessType().toString();
                if (!cuMemberAssessMap.containsKey(key)) {
                    newCuMemberSettleExtList.add(cuMemberSettleExt);
                }
            });
        }
//        e)查询有没有撤单，更新撤单的数据
        List<CuMemberAssessExt> cuMemberAssessExtList = handleCuMemberAssessByRevokeOrder(currentDate, newCuMemberSettleExtList, tableName, monthFirstPeriod, settleTableName);
        if (cuMemberAssessExtList.size() > 0) {
            // 将变更的插入临时表
            baseMapper.insertTmpCuMemberAssess(cuMemberAssessExtList);
            // 根据临时表里面的值进行更新会员表
            baseMapper.updateAssessPeriodByRevokeOrder(tableName);
        }
//        f)前一天免考后一天不免考，需要做重新考核，看上月是否可以考核通过
        if (newCuMemberSettleExtList.size() > 0) {
            //  处理考核数据
            // 记录流水，新增或修改
            cuMemberAssessDetailService.insertCuMemberAssessDetailByPeriod(tableName, monthFirstPeriod, newCuMemberSettleExtList);
            List<List<?>> cutCuMemberSettleExtList = cuMemberBonusSettle.handleCutList(newCuMemberSettleExtList);
            cutCuMemberSettleExtList.forEach(assessExtList ->
                    baseMapper.updateAssessPeriodCheckBalanceByTmp(tableName, monthFirstPeriod, assessExtList));
        }
        // 网体数据修改，修改复购免考类型 0=正常 1=手动免考 2=注册免考 3=晋升免考，修改是否复购免考（0=是,1=否）
    }

    /**
     * 根据撤销订单，进行重算考核数据
     *
     * @param currentDate           考核日期
     * @param cuMemberSettleExtList 前一天的会员免考记录
     * @param tableName             会员
     * @param currentPeriod         考核期间
     * @param settleTableName       考核表
     */
    private List<CuMemberAssessExt> handleCuMemberAssessByRevokeOrder(Date currentDate, List<CuMemberSettleExt> cuMemberSettleExtList,
                                                                      String tableName, Integer currentPeriod, String settleTableName) {
//        e)查询有没有撤单，更新撤单的数据
//        List<Integer> orderTypeList = new ArrayList<>();
//        orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
//        List<SaOrder> saOrderList = saOrderServiceApi.querySaOrderBySettleDate(currentDate, orderTypeList).getData();
//        Map<String, SaOrder> saOrderMap = new HashMap<>(ComputeUtil.mapInitCapacity(saOrderList.size()));
//        saOrderList.forEach(saOrder -> {
//            String key = saOrder.getPkMember().toString() + saOrder.getOrderType().toString();
//            saOrderMap.put(key, saOrder);
//        });
//        if (cuMemberSettleExtList.size() > 0) {
//            List<CuMemberSettleExt> memberSettleExtList = new ArrayList<>();
//            for (CuMemberSettleExt cuMemberSettleExt : cuMemberSettleExtList) {
//                String key = cuMemberSettleExt.getPkMember().toString();
//                if (EAssessmentType.REPURCHASE_ASSESS.getValue() == cuMemberSettleExt.getAssessType()) {
//                    key = key + EOrderType.REPURCHASE_ORDER.getValue();
//                } else {
//                    key = key + EOrderType.WELFARE_ORDER.getValue();
//                }
//                if (!saOrderMap.containsKey(key)) {
//                    memberSettleExtList.add(cuMemberSettleExt);
//                }
//            }
//            cuMemberSettleExtList.clear();
//            cuMemberSettleExtList.addAll(memberSettleExtList);
//        }
        // 前一天免考第二天不免考的重新考核
        List<CuMemberAssessExt> memberAssessExtList = new ArrayList<>();
        if (cuMemberSettleExtList.size() > 0) {
            List<List<?>> orderHandleCutList = cuMemberBonusSettle.handleCutList(cuMemberSettleExtList);
            orderHandleCutList.forEach(handlerCutList ->
                    memberAssessExtList.addAll(baseMapper.queryAssessPeriodByRevokeOrder(tableName, settleTableName, currentPeriod, handlerCutList)));
            memberAssessExtList.forEach(cuMemberAssessExt -> {
                // 需要进行考核的 先变为考核不通过，使用值修改为0
                cuMemberAssessExt.setIsExamine(EYesNo.NO.getIntValue());
                cuMemberAssessExt.setAssessStatus(EAssessStatus.EXAMINE_NO_PASS.getValue());
                cuMemberAssessExt.setMonthUsed(BigDecimal.ZERO);
                cuMemberAssessExt.setMonthSurplus(ComputeUtil.computeAdd(cuMemberAssessExt.getMonthBalance(), cuMemberAssessExt.getMonthAdd()));
            });
        }
        // 撤单的也只验证一次，查询新增金额没有进行变更的值
        List<CuMemberAssessExt> cuMemberAssessExtList = new ArrayList<>();
//        if (saOrderList.size() > 0) {
//            List<List<?>> orderHandleCutList = cuMemberBonusSettle.handleCutList(saOrderList);
//            orderHandleCutList.forEach(handlerCutList ->
//                    cuMemberAssessExtList.addAll(baseMapper.queryAssessPeriodByRevokeOrder(tableName, settleTableName, currentPeriod, handlerCutList)));
//            packageRetryExamine(cuMemberSettleExtList, saOrderMap, cuMemberAssessExtList);
//        }
        if (memberAssessExtList.size() > 0) {
            cuMemberAssessExtList.addAll(memberAssessExtList);
        }
        return cuMemberAssessExtList;
    }

    private void packageRetryExamine(List<CuMemberSettleExt> cuMemberSettleExtList, Map<String, SaOrder> saOrderMap, List<CuMemberAssessExt> cuMemberAssessExtList) {
        // 先计算免考的
        // 将需要重新考核的考核明细删除
        List<CuMemberAssessDetail> revokeDetailList = new ArrayList<>();
        cuMemberAssessExtList.forEach(cuMemberAssessExt -> {
            String key = cuMemberAssessExt.getPkMember().toString();
            if (EAssessmentType.REPURCHASE_ASSESS.getValue() == cuMemberAssessExt.getAssessType()) {
                key = key + EOrderType.REPURCHASE_ORDER.getValue();
            } else {
                key = key + EOrderType.WELFARE_ORDER.getValue();
            }
            SaOrder saOrder = saOrderMap.get(key);
            BigDecimal orderAchieve = BigDecimal.ZERO;
            if (saOrder != null) {
                orderAchieve = saOrder.getOrderAchieve();
            }
            // 判断考核类型
            CuMemberAssessDetail cuMemberAssessDetail = CuMemberAssessDetail.builder()
                    .changeType(EAssessmentType.REPURCHASE_ASSESS.getValue() == cuMemberAssessExt.getAssessType() ?
                            EChangeType.PURCHASE_ASSESSMENT_DEDUCT.getValue() : EChangeType.SHARE_ASSESSMENT_DEDUCT.getValue())
                    .pkMember(cuMemberAssessExt.getPkMember())
                    .pkAssess(cuMemberAssessExt.getPkId())
                    .build();
            if (EYesNo.YES.getIntValue() == cuMemberAssessExt.getIsExamine()) {
                // 免考的有2种状态 考核通过的需要扣除 免考通过的不扣除
                if (EAssessStatus.EXAMINE_PASS.getValue() == cuMemberAssessExt.getAssessStatus()) {
//                    考核月新增业绩  month_add  考核月剩余业绩  month_surplus 发生变化
                    // 剩余 = 结余 + 新增-使用 此条考核记录不能删除
                    cuMemberAssessExt.setMonthSurplus(ComputeUtil.computeSubtract(ComputeUtil.computeAdd(cuMemberAssessExt.getMonthBalance(), orderAchieve), cuMemberAssessExt.getMonthUsed()));
                } else {
//                    考核月新增业绩  month_add  考核月剩余业绩  month_surplus 发生变化 考核月使用业绩  month_used 发生变化
                    // 剩余 = 结余 + 新增
                    cuMemberAssessExt.setAssessStatus(EAssessStatus.EXEMPT_PASS.getValue());
                    cuMemberAssessExt.setMonthUsed(BigDecimal.ZERO);
                    cuMemberAssessExt.setMonthSurplus(ComputeUtil.computeAdd(cuMemberAssessExt.getMonthBalance(), orderAchieve));
                    revokeDetailList.add(cuMemberAssessDetail);
                }
            } else {
                // 判断奖衔是否发生了变化，发生了变化需要修改目标值 免考的不变更目标值
                if (!Objects.equals(cuMemberAssessExt.getPkOriginalAwards(), cuMemberAssessExt.getPkAwards())) {
                    BdAwards bdAwards = awardsServiceApi.getAwardsOne(cuMemberAssessExt.getPkAwards()).getData();
                    cuMemberAssessExt.setAssessTarget(EAssessmentType.REPURCHASE_ASSESS.getValue() == cuMemberAssessExt.getAssessType() ?
                            bdAwards.getPurchaseCheck() : bdAwards.getShareCheck());
                }
                // 需要进行考核的 先变为考核不通过，使用值修改为0
                cuMemberAssessExt.setAssessStatus(EAssessStatus.EXAMINE_NO_PASS.getValue());
                cuMemberAssessExt.setMonthUsed(BigDecimal.ZERO);
                cuMemberAssessExt.setMonthSurplus(ComputeUtil.computeAdd(cuMemberAssessExt.getMonthBalance(), orderAchieve));
                CuMemberSettleExt cuMemberSettleExt = new CuMemberSettleExt();
                cuMemberSettleExt.setPkMember(cuMemberAssessExt.getPkMember());
                cuMemberSettleExt.setAssessType(cuMemberAssessExt.getAssessType());
                cuMemberSettleExtList.add(cuMemberSettleExt);
                revokeDetailList.add(cuMemberAssessDetail);
            }
        });
        // 将历史考核明细删除
        if (revokeDetailList.size() > 0) {
            cuMemberAssessDetailService.deleteCuMemberAssessDetailByList(revokeDetailList);
        }
    }

    private void initCurrentAssess(Date currentDate, String currentTableName, Integer currentPeriod) {
        // 获取上月最后一天
        String beforeLastDate = DateUtils.beforeMonthLastDateStr(currentDate);
        CuMemberSettlePeriod cuMemberSettlePeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(beforeLastDate);
        int period = cuMemberSettlePeriod.getPkId();
        String sourceTable = TableNameConstants.CU_MEMBER_SETTLE + period;
        // 清空子表、主表数据
        cuMemberAssessDetailService.deleteCuMemberAssessDetailByPeriod(currentTableName, currentPeriod);
//        baseMapper.deleteCuMemberAssessByPeriod(currentTableName, currentPeriod);
        // 初始化复购考核
        String month = DateUtils.getMonth(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, currentDate));
        // 结算日期后一天
        baseMapper.insertRepCuMemberAssess(currentTableName, sourceTable, currentPeriod, month);
        // 初始化分红考核
        baseMapper.insertShareCuMemberAssess(currentTableName, sourceTable, currentPeriod, month);
        // 初始化订单数据，将当月新增加入数据库
        // 上月第一天，上月最后一天
        Date beforeFirstDate = DateUtils.beforeMonthFirstDate(currentDate);
        Date currentFirstDate = DateUtils.currentMonthFirstDate(currentDate);
        cuMemberAssessDetailService.insertCuMemberAssesDetailByOrder(currentTableName, currentPeriod, beforeFirstDate, currentFirstDate);
    }

    /**
     * 初始化期初数据，将上月结余作为本月期初，更新当月新增
     *
     * @param currentDate      结算日期
     * @param currentTableName 当前月结算表
     * @param currentPeriod    当前结算期间
     * @param assessmentType   考核类型 0=复购考核 1=分红考核
     */
    private void initCurrentAssessByBeforeMonth(Date currentDate, String currentTableName, Integer currentPeriod, Integer assessmentType) {
        List<Integer> orderTypeList = new ArrayList<>();
        if (EAssessmentType.REPURCHASE_ASSESS.getValue() == assessmentType) {
            orderTypeList.add(EOrderType.REPURCHASE_ORDER.getValue());
            orderTypeList.add(EOrderType.MALL_ORDER.getValue());
            orderTypeList.add(EOrderType.COOPERATE_ORDER.getValue());
        } else {
            orderTypeList.add(EOrderType.WELFARE_ORDER.getValue());
        }
        // 更新考核值，期初是上月考核表的当月剩余业绩
        // 获取结算日月初第一天，获取期间
        // 获取结算日上月最后一天，获取期间
        Date beforeMonthFirstDate = DateUtils.beforeMonthFirstDate(currentDate);
        String beforeMonthFirstDateStr = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, beforeMonthFirstDate);
        Integer beforePeriod = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(beforeMonthFirstDateStr).getPkId();
        String beforeTableName = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.getYear(beforeMonthFirstDateStr);
        Date currentMonthFirstDate = DateUtils.currentMonthFirstDate(currentDate);
        // 初始化复购考核的上月结余 // 更新当月结余
        baseMapper.updateAssessPeriodBeginByBeforeMonth(beforeTableName, currentTableName, beforePeriod, currentPeriod, assessmentType);
        // 更新当月新增
        baseMapper.updateAssessPeriodAddBySaOrder(currentTableName, currentPeriod, assessmentType,
                beforeMonthFirstDate, currentMonthFirstDate, orderTypeList);
    }

    @Override
    public CuMemberAssessVO getOrderAssessList(CuMemberAssessVO cuMemberAssessVO) {
        return baseMapper.getOrderAssessList(cuMemberAssessVO);
    }

    @Override
    public List<CuMemberAssessVO> getOrderByAssessList(CuMemberAssessVO cuMemberAssessVO) {
        return baseMapper.getOrderByAssessList(cuMemberAssessVO);
    }

    @Override
    public List<CuMemberAssess> queryCuMemberAssTotal(String startDate, Integer pkCountry) {
        int period = cuMemberSettlePeriodService.getCuMemberSettlePeriodByDate(startDate).getPkId();
        String tableTable = TableNameConstants.CU_MEMBER_ASSESS + DateUtils.getYear(startDate);
        return baseMapper.queryCuMemberAssTotal(tableTable, period, pkCountry);
    }
}
