package com.haha.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.haha.entity.DeviceInventory;
import com.haha.entity.InventoryLog;
import com.haha.entity.Order;
import com.haha.entity.Product;
import com.haha.entity.RefundItem;
import com.haha.service.DeviceInventoryService;
import com.haha.service.InventoryLogService;
import com.haha.service.OrderInventoryService;
import com.haha.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 订单库存服务实现类
 */
@Slf4j
@Service
public class OrderInventoryServiceImpl implements OrderInventoryService {

    @Autowired
    private DeviceInventoryService deviceInventoryService;

    @Autowired
    private InventoryLogService inventoryLogService;

    @Autowired
    private ProductService productService;

    @Autowired
    private ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decreaseStockOnPaid(Order order) {
        String orderNo = order.getOrderNo();

        // 幂等性检查：已扣减过则跳过
        long deductedCount = inventoryLogService.countByOrderIdAndType(orderNo, InventoryLog.TYPE_SALE);
        if (deductedCount > 0) {
            log.info("订单库存已扣减，跳过重复扣减: orderNo={}", orderNo);
            return;
        }

        if (order.getItems() == null || order.getItems().isEmpty()) {
            log.warn("订单商品明细为空，跳过库存扣减: orderNo={}", orderNo);
            return;
        }

        try {
            List<Map<String, Object>> items = parseItems(order.getItems());

            String deviceId = order.getDeviceId();

            for (Map<String, Object> item : items) {
                Long productId = extractProductId(item);
                Integer quantity = extractQuantity(item);
                String productCode = extractProductCode(item);

                // AI识别返回的items只有code没有productId，需要通过code反查本地商品库
                if (productId == null && productCode != null) {
                    Product product = productService.getProductByCode(productCode);
                    if (product != null) {
                        productId = product.getId();
                    }
                }

                if (productId == null) {
                    log.warn("无法确定商品ID，跳过扣减: orderNo={}, productCode={}", orderNo, productCode);
                    continue;
                }

                try {
                    deviceInventoryService.decreaseStock(
                            deviceId,
                            productId,
                            quantity,
                            orderNo,
                            null,
                            "系统"
                    );
                    log.info("订单扣减库存: orderNo={}, deviceId={}, productCode={}, quantity={}",
                            orderNo, deviceId, productCode, quantity);
                } catch (Exception e) {
                    log.error("单件商品库存扣减失败: orderNo={}, productId={}, quantity={}, error={}",
                            orderNo, productId, quantity, e.getMessage());
                }
            }
        } catch (Exception e) {
            log.error("订单库存扣减失败: orderNo={}", orderNo, e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void restoreStockOnRefund(Order order, List<RefundItem> refundItems) {
        if (refundItems == null || refundItems.isEmpty()) {
            log.warn("退款商品明细为空，跳过库存恢复: orderNo={}", order.getOrderNo());
            return;
        }

        String deviceId = order.getDeviceId();
        String orderNo = order.getOrderNo();

        for (RefundItem item : refundItems) {
            if (item.getProductId() == null) {
                log.warn("退款商品ID为空，跳过库存恢复: orderNo={}", orderNo);
                continue;
            }

            try {
                DeviceInventory inventory = deviceInventoryService.getByDeviceAndProduct(deviceId, item.getProductId());
                if (inventory == null) {
                    log.warn("设备库存记录不存在，跳过恢复: deviceId={}, productId={}, orderNo={}",
                            deviceId, item.getProductId(), orderNo);
                    continue;
                }

                int newStock = inventory.getStock() + item.getQuantity();
                deviceInventoryService.adjustStock(
                        deviceId,
                        item.getProductId(),
                        newStock,
                        "退款恢复库存: orderNo=" + orderNo + ", refundId=" + item.getRefundId(),
                        null,
                        "系统"
                );
                log.info("退款恢复库存: orderNo={}, deviceId={}, productId={}, quantity={}, stockBefore={}, stockAfter={}",
                        orderNo, deviceId, item.getProductId(), item.getQuantity(), inventory.getStock(), newStock);
            } catch (Exception e) {
                log.error("退款恢复库存失败: orderNo={}, productId={}, error={}",
                        orderNo, item.getProductId(), e.getMessage());
            }
        }
    }

    @Override
    public boolean checkStockAvailable(String deviceId, String items) {
        if (items == null || items.isEmpty()) {
            return true;
        }

        try {
            List<Map<String, Object>> itemsList = parseItems(items);

            for (Map<String, Object> item : itemsList) {
                Long productId = extractProductId(item);
                Integer quantity = extractQuantity(item);
                String productCode = extractProductCode(item);

                // AI识别返回的items只有code没有productId，需要通过code反查本地商品库
                if (productId == null && productCode != null) {
                    Product product = productService.getProductByCode(productCode);
                    if (product != null) {
                        productId = product.getId();
                    }
                }

                if (productId != null) {
                    DeviceInventory inventory = deviceInventoryService.getByDeviceAndProduct(deviceId, productId);
                    if (inventory == null || inventory.getStock() < quantity) {
                        return false;
                    }
                }
            }
            return true;
        } catch (Exception e) {
            log.error("检查库存可用性失败", e);
            return true;
        }
    }

    /**
     * 解析items字段，兼容JSON数组和单个JSON对象两种格式
     */
    private List<Map<String, Object>> parseItems(String items) {
        try {
            return objectMapper.readValue(items,
                    new TypeReference<List<Map<String, Object>>>() {});
        } catch (Exception e) {
            try {
                Map<String, Object> single = objectMapper.readValue(items,
                        new TypeReference<Map<String, Object>>() {});
                return java.util.Collections.singletonList(single);
            } catch (Exception ex) {
                log.error("解析订单items失败: items={}", items, ex);
                return java.util.Collections.emptyList();
            }
        }
    }

    private Long extractProductId(Map<String, Object> item) {
        Object productIdObj = item.get("productId");
        if (productIdObj != null) {
            return Long.parseLong(productIdObj.toString());
        }
        return null;
    }

    private Integer extractQuantity(Map<String, Object> item) {
        Object qtyObj = item.get("quantity");
        if (qtyObj != null) {
            return Integer.parseInt(qtyObj.toString());
        }
        return 1;
    }

    private String extractProductCode(Map<String, Object> item) {
        String code = (String) item.get("productCode");
        if (code == null) {
            code = (String) item.get("code");
        }
        return code;
    }
}
