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.service.DeviceInventoryService;
import com.haha.service.OrderInventoryService;
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 ObjectMapper objectMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void decreaseStockOnPaid(Order order) {
        if (order.getItems() == null || order.getItems().isEmpty()) {
            log.warn("订单商品明细为空，跳过库存扣减: orderNo={}", order.getOrderNo());
            return;
        }

        try {
            // 解析商品明细
            List<Map<String, Object>> items = objectMapper.readValue(
                    order.getItems(),
                    new TypeReference<List<Map<String, Object>>>() {}
            );

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

            for (Map<String, Object> item : items) {
                String productCode = (String) item.get("productCode");
                if (productCode == null) {
                    productCode = (String) item.get("code");
                }
                String productName = (String) item.get("productName");
                if (productName == null) {
                    productName = (String) item.get("name");
                }

                Integer quantity = 1;
                Object qtyObj = item.get("quantity");
                if (qtyObj != null) {
                    quantity = Integer.parseInt(qtyObj.toString());
                }

                Long productId = null;
                Object productIdObj = item.get("productId");
                if (productIdObj != null) {
                    productId = Long.parseLong(productIdObj.toString());
                }

                // 扣减库存
                if (productId != null) {
                    deviceInventoryService.decreaseStock(
                            deviceId,
                            productId,
                            quantity,
                            orderNo,
                            null, // 系统自动操作
                            "系统"
                    );
                    log.info("订单扣减库存: orderNo={}, deviceId={}, productCode={}, quantity={}",
                            orderNo, deviceId, productCode, quantity);
                }
            }
        } catch (Exception e) {
            log.error("订单库存扣减失败: orderNo={}", order.getOrderNo(), e);
            // 不抛出异常，避免影响订单流程
        }
    }

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

        try {
            // 解析商品明细
            List<Map<String, Object>> items = objectMapper.readValue(
                    order.getItems(),
                    new TypeReference<List<Map<String, Object>>>() {}
            );

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

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

                String productCode = (String) item.get("productCode");
                if (productCode == null) {
                    productCode = (String) item.get("code");
                }
                String productName = (String) item.get("productName");
                if (productName == null) {
                    productName = (String) item.get("name");
                }

                Integer quantity = 1;
                Object qtyObj = item.get("quantity");
                if (qtyObj != null) {
                    quantity = Integer.parseInt(qtyObj.toString());
                }

                // 恢复库存（使用调整方式）
                if (productId != null) {
                    DeviceInventory inventory = deviceInventoryService.getByDeviceAndProduct(deviceId, productId);
                    if (inventory != null) {
                        deviceInventoryService.adjustStock(
                                deviceId,
                                productId,
                                inventory.getStock() + quantity,
                                "订单退款恢复库存: " + orderNo,
                                null,
                                "系统"
                        );
                        log.info("退款恢复库存: orderNo={}, deviceId={}, productCode={}, quantity={}",
                                orderNo, deviceId, productCode, quantity);
                    }
                }
            }
        } catch (Exception e) {
            log.error("订单库存恢复失败: orderNo={}", order.getOrderNo(), e);
        }
    }

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

        try {
            List<Map<String, Object>> itemsList = objectMapper.readValue(
                    items,
                    new TypeReference<List<Map<String, Object>>>() {}
            );

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

                Integer quantity = 1;
                Object qtyObj = item.get("quantity");
                if (qtyObj != null) {
                    quantity = Integer.parseInt(qtyObj.toString());
                }

                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; // 解析失败默认可用，避免影响正常流程
        }
    }
}
