package com.cxyxiaomo.epp.shop.service;

import com.cxyxiaomo.epp.common.enums.OrderStatus;
import com.cxyxiaomo.epp.common.pojo.Good;
import com.cxyxiaomo.epp.common.pojo.Order;
import com.cxyxiaomo.epp.common.pojo.OrderDetail;
import com.cxyxiaomo.epp.common.utils.SnowflakeManager;
import com.cxyxiaomo.epp.common.vo.OrderDetailVO;
import com.cxyxiaomo.epp.shop.dao.GoodsDao;
import com.cxyxiaomo.epp.shop.dao.OrderDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderService {

    @Resource
    private GoodsDao goodsDao;

    @Resource
    private OrderDao orderDao;

    /**
     * 创建订单，返回订单编号
     *
     * @param userId
     * @param orderItemList
     * @return
     * @throws Exception
     */
    @Transactional(rollbackFor = Exception.class)
    public long createOrder(int userId, List<OrderDetail> orderItemList) throws Exception {
        // 创建订单编号
        SnowflakeManager snowflakeManager = new SnowflakeManager(1L, 1L);
        long orderId = snowflakeManager.nextValue();


        // 订单总金额
        BigDecimal totalPrice = new BigDecimal(0);

        // 创建订单
        Order order = new Order();
        order.setId(orderId);
        order.setUserId(userId);
        order.setOrderDate(LocalDateTime.now());
        order.setOrderStatus(OrderStatus.PENDING.getValue());

        // 创建订单详情
        for (OrderDetail orderItem : orderItemList) {
            if (orderItem == null || orderItem.getGoodId() == null || orderItem.getGoodCount() == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                throw new IllegalArgumentException("商品不存在");
            }

            // 查询商品价格
            Good good = goodsDao.selectById(orderItem.getGoodId());
            if (good == null || good.getDeleted() || good.getRetailPrice() == null) {
                throw new IllegalArgumentException("商品已删除或状态异常，无法下单");
            }
            Double retailPrice = good.getRetailPrice();

            // 手动塞入信息
            orderItem.setId(null);
            orderItem.setOrderId(orderId);
            orderItem.setUnitPrice(retailPrice);

            // 计入订单总价
            BigDecimal goodPrice = BigDecimal.valueOf(retailPrice * orderItem.getGoodCount());
            totalPrice = totalPrice.add(goodPrice);
        }

        // 订单总价
        order.setOrderPrice(totalPrice);

        orderDao.insertOrder(order);
        orderDao.batchInsertOrderDetail(orderItemList);
        return orderId;
    }

    /**
     * 获取订单
     *
     * @param orderId
     */
    public Order getOrderById(Long orderId) {
        Order order = orderDao.getOrderById(orderId);
        if (order == null) {
            return null;
        }
        return order;
    }

    /**
     * 获取订单详情
     *
     * @param orderId
     */
    public List<OrderDetailVO> getOrderDetailById(Long orderId) {
        List<OrderDetail> orderDetails = orderDao.getOrderDetailById(orderId);
        if (orderDetails == null) {
            return null;
        }
        List<OrderDetailVO> orderDetailVOS = OrderDetailVO.convertFrom(orderDetails);
        return orderDetailVOS;
    }

    /**
     * 通过用户 id 获取用户订单列表
     *
     * @param userId
     * @return
     */
    public List<Order> listUserOrder(Integer userId, String orderStatus) {
        List<Order> orders = orderDao.listOrderByUserId(userId, orderStatus);
        return orders;
    }

    /**
     * 更新订单状态
     *
     * @param orderId
     * @param orderStatus
     * @return
     */
    public Boolean updateOrderStatus(Long orderId, OrderStatus orderStatus) {
        int affectRows = orderDao.updateOrderStatus(orderId, orderStatus.getValue());
        return affectRows > 0;
    }
}
