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

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.bonus.achieve.mapper.CuMemberRetailRangeMapper;
import com.hzs.bonus.achieve.service.ICuMemberRetailRangeService;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.domain.member.achieve.CuMemberRetailRange;
import com.hzs.common.domain.member.achieve.ext.CuMemberRetailRangeExt;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 服务实现类
 */
@Service
public class CuMemberRetailRangeServiceImpl extends ServiceImpl<CuMemberRetailRangeMapper, CuMemberRetailRange> implements ICuMemberRetailRangeService {

    @Autowired
    private CuMemberBonusSettle cuMemberBonusSettle;

    @Override
    public void mergeMemberRetailRangeByYesterday(Date settleEndDate, String rangeTableName, String yesterdayRangeTableName, Boolean isSameMonth) {
        // 当天数据全部更新为0
        baseMapper.mergeMemberRetailRangeInit(rangeTableName);
        if (isSameMonth) {
            // 结算期间和结算期间前一期是同月
            baseMapper.mergeMemberRetailRangeByYesterday(rangeTableName, yesterdayRangeTableName, 0);
        } else {
            baseMapper.mergeMemberRetailRangeByYesterday(rangeTableName, yesterdayRangeTableName, 1);
        }
    }

    @Override
    public List<CuMemberRetailRangeExt> queryCuMemberRetailRangeParent(String tableName, List<SaOrderExt> saOrderExtList) {
        List<CuMemberRetailRangeExt> memberRetailRangeExtList = new ArrayList<>();
        Set<Long> orderIdSet = new HashSet<>();
        for (SaOrderExt saOrderExt : saOrderExtList) {
            orderIdSet.add(saOrderExt.getPkMember());
        }
        List<List<?>> cutOrderList = cuMemberBonusSettle.handleCutList(orderIdSet, MagicNumberConstants.DELETE_DATA_BATCH_UPDATE_NUM);
        cutOrderList.forEach(orderList -> {
            List<CuMemberRetailRangeExt> rangeExtList = baseMapper.queryCuMemberRetailRangeParent(tableName, orderList);
            if (rangeExtList.size() > 0) {
                memberRetailRangeExtList.addAll(rangeExtList);
            }
        });
        return memberRetailRangeExtList;
    }

    @Override
    public void updateCuMemberRetailRange(String settleTableName, Map<Long, CuMemberRetailRangeExt> cuMemberTreeMap) {
        List<List<?>> treeList = setUpdCuMemberTreeLists(cuMemberTreeMap);
        treeList.forEach(list -> baseMapper.mergeCuMemberRetailRangeExt(settleTableName, list));
    }

    private List<List<?>> setUpdCuMemberTreeLists(Map<Long, CuMemberRetailRangeExt> cuMemberTreeMap) {
        List<CuMemberRetailRangeExt> cuMemberTreeList = new ArrayList<>();
        cuMemberTreeMap.forEach((key, value) -> cuMemberTreeList.add(value));
        return cuMemberBonusSettle.handleCutList(cuMemberTreeList);
    }
}
