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

import cn.hutool.core.collection.CollectionUtil;
import com.hzs.bonus.achieve.service.impl.CuMemberBonusSettle;
import com.hzs.bonus.order.mapper.BonusOrderMapper;
import com.hzs.bonus.order.service.IBonusOrderService;
import com.hzs.common.core.constant.MagicNumberConstants;
import com.hzs.common.domain.sale.ext.SaOrderExt;
import com.hzs.common.domain.sale.ext.SaOrderItemsExt;
import com.hzs.common.domain.sale.order.SaOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class BonusOrderServiceImpl implements IBonusOrderService {

    @Resource
    private BonusOrderMapper bonusOrderMapper;
    @Autowired
    private CuMemberBonusSettle cuMemberBonusSettle;

    @Override
    public List<SaOrderExt> queryRetailSaOrderByDay(Date startDate, Date endDate, String orderCode) {
        return bonusOrderMapper.queryRetailSaOrderByDay(startDate, endDate, orderCode);
    }

    @Override
    public SaOrderExt querySaOrderByDay(Date startDate, Date endDate, String orderCode) {
        List<SaOrderExt> saOrderList = bonusOrderMapper.querySaOrderByTime(startDate, endDate, orderCode);
        if (CollectionUtil.isNotEmpty(saOrderList)) {
            return saOrderList.get(0);
        }
        return null;
    }

    @Override
    public List<SaOrder> listSaOrderByTime(Date startDate, Date endDate, List<Integer> orderType) {
        return bonusOrderMapper.listSaOrderByTime(startDate, endDate, orderType);
    }

    @Override
    public Map<Long, List<SaOrderItemsExt>> getWaresRange(List<SaOrderExt> orderList) {
        Map<Long, List<SaOrderItemsExt>> resultMap = new HashMap<>();

        List<SaOrderItemsExt> resultList = new ArrayList<>();
        List<List<?>> handleCutList = cuMemberBonusSettle.handleCutList(orderList, MagicNumberConstants.BATCH_UPDATE_NUM);
        handleCutList.forEach(list -> {
            resultList.addAll(bonusOrderMapper.listOrderWaresRange(orderList));
        });
        for (SaOrderItemsExt saOrderItemsExt : resultList) {
            if (resultMap.containsKey(saOrderItemsExt.getPkOrder())) {
                resultMap.get(saOrderItemsExt.getPkOrder()).add(saOrderItemsExt);
            } else {
                List<SaOrderItemsExt> tmpList = new ArrayList<>();
                tmpList.add(saOrderItemsExt);
                resultMap.put(saOrderItemsExt.getPkOrder(), tmpList);
            }
        }

        return resultMap;
    }

}
