package com.remy.order.service.impl;

import com.remy.common.module.GoodsDTO;
import com.remy.common.module.UserDTO;
import com.remy.order.dao.OrderDAO;
import com.remy.order.entity.Order;
import com.remy.order.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

@Service
public class OrderServiceImpl implements OrderService {

    private static Map<Integer, BigDecimal> discountMapping;

    static {
        discountMapping = new HashMap<>();
        discountMapping.put(1, new BigDecimal("0.90"));
        discountMapping.put(2, new BigDecimal("0.85"));
        discountMapping.put(3, new BigDecimal("0.80"));
    }

    @Autowired
    OrderDAO orderDAO;
    @Value("${rest.api.users-endpoint}")
    private String userAPIEndpoint;
    @Value("${rest.api.goods-endpoint}")
    private String goodsAPIEndpoint;

    @Override
    public Order findByOrderNo(String orderNo) {
        return orderDAO.findOrderByOrderNo(orderNo);
    }

    @Override
    public List<Order> findAllByGoodsSerialNo(String goodsSerialNo) {
        return orderDAO.findAllByGoodsSerialNo(goodsSerialNo);
    }

    @Override
    public List<Order> findByCondition(Order order) {
        return orderDAO.findAll(Example.of(order));
    }

    @Override
    public List<Order> findAll() {
        return orderDAO.findAll();
    }

    @Override
    public Order save(Order order) {

        UserDTO user = new RestTemplate().getForObject(userAPIEndpoint + order.getUserID(), UserDTO.class);
        BigDecimal discountBase = discountMapping.get(user.getLevel());

        GoodsDTO goods = new RestTemplate().getForObject(goodsAPIEndpoint + order.getGoodsSerialNo(), GoodsDTO.class);

        order.setOriginalAmount(goods.getPrice());
        order.setDiscount(discountBase);
        order.setDiscountAmount(goods.getPrice().multiply(discountBase));

        return orderDAO.save(order);
    }
}
