package com.bofeng.service;

import com.bofeng.entity.Order;
import com.bofeng.entity.OrderCms;
import com.google.common.collect.Lists;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CalcService {

    @Autowired
    private UserPlaceService userPlaceService;

    @Autowired
    private UserService userService;

    public List<OrderCms> dispatch(Order order) {

        List<OrderCms> r = Lists.newArrayList();

        val userPlace = userPlaceService.getByUserIdAndPlaceId(order.getSaleUserId(), order.getPlaceId());
        if (userPlace == null) {
            throw new RuntimeException("用户不存在");
        }
        val user = userService.getUserById(order.getSaleUserId());
        val higherId = userPlace.getHigherId();
        if (higherId == null || higherId <= 0) {
            //本人就是1级
            val cms = new OrderCms(
                    order.getOrderId(),
                    user,
                    order.getPayAmount().multiply(new BigDecimal(0.4)));
            r.add(cms);

        } else {
            //1级、2级
            val userHigher = userService.getUserById(higherId);

            if (userHigher == null) {
                throw new RuntimeException("上级销售不存在");
            }

            val cms = new OrderCms(
                    order.getOrderId(),
                    user,
                    order.getPayAmount().multiply(new BigDecimal(0.1)));

            val cmsHeighter = new OrderCms(
                    order.getOrderId(),
                    userHigher,
                    order.getPayAmount().multiply(new BigDecimal(0.3)));

            r.add(cms);
            r.add(cmsHeighter);
        }

        return r;
    }
}
