package com.erp.example.seata;

import com.erp.example.seata.entity.Order;
import com.erp.example.seata.mapper.OrderMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.UUID;

/**
 * 订单服务 - AT模式实现
 */
@Service
public class OrderService {

    private static final Logger log = LoggerFactory.getLogger(OrderService.class);

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 创建订单
     */
    @Transactional
    public String createOrder(Long customerId, Long productId, Integer quantity) {
        String orderNo = "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
        
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setCustomerId(customerId);
        order.setProductId(productId);
        order.setQuantity(quantity);
        order.setTotalAmount(quantity * 100.00); // 假设单价100元
        order.setStatus("PENDING");
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        
        orderMapper.insert(order);
        log.info("订单创建成功: {}", order);
        
        return orderNo;
    }

    /**
     * 更新订单状态
     */
    @Transactional
    public void updateOrderStatus(String orderNo, String status) {
        Order order = orderMapper.findByOrderNo(orderNo);
        if (order != null) {
            order.setStatus(status);
            order.setUpdateTime(LocalDateTime.now());
            orderMapper.update(order);
            log.info("订单状态更新: {} -> {}", orderNo, status);
        }
    }

    /**
     * 取消订单
     */
    @Transactional
    public void cancelOrder(String orderNo) {
        Order order = orderMapper.findByOrderNo(orderNo);
        if (order != null) {
            order.setStatus("CANCELLED");
            order.setUpdateTime(LocalDateTime.now());
            orderMapper.update(order);
            log.info("订单已取消: {}", orderNo);
        }
    }

    /**
     * 根据订单号查询订单
     */
    public Order findByOrderNo(String orderNo) {
        return orderMapper.findByOrderNo(orderNo);
    }
}
