package cn.qihangerp.erp.serviceImpl;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.*;

/**
 * 库存与销售示例分析（演示数据处理）；报告由本地规则生成，不调用外部大模型 API。
 *
 * @author guochengyu
 */
public class InventorySalesAnalyzer {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 你的数据
    private static final String INVENTORY_JSON = "[{\"id\":1,\"goods_title\":\"雷士照明led吸顶灯灯芯替换圆形灯板节能灯芯冷光高显护眼健康\",\"sku_name\":\"白光12W\",\"stock_num\":12},{\"id\":2,\"goods_title\":\"雷士照明led吸顶灯灯芯替换圆形灯板节能灯芯冷光高显护眼健康\",\"sku_name\":\"白光18W\",\"stock_num\":12},{\"id\":3,\"goods_title\":\"雷士照明led吸顶灯灯芯替换圆形灯板节能灯芯冷光高显护眼健康\",\"sku_name\":\"白光24W\",\"stock_num\":12},{\"id\":4,\"goods_title\":\"雷士照明led吸顶灯灯芯替换圆形灯板节能灯芯冷光高显护眼健康\",\"sku_name\":\"双色36W\",\"stock_num\":12}]";

    private static final String SALES_JSON = "[{\"order_num\":\"1\",\"sku_id\":1,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":3,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":1,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":2,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":4,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":1,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":1,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":3,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":1,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":1,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"},{\"order_num\":\"1\",\"sku_id\":2,\"count\":1,\"item_amount\":29.32,\"order_time\":\"2025-05-24 23:19:51\"}]";

    public static void main(String[] args) {
        try {
            System.out.println("开始分析库存与销售数据...\n");

            List<InventoryItem> inventoryList = parseInventoryData();
            List<SalesOrder> salesList = parseSalesData();

            String analysisResult = analyzeInventoryAndSales(inventoryList, salesList);

            System.out.println("=== 分析报告 ===\n");
            System.out.println(analysisResult);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 核心分析方法
     */
    public static String analyzeInventoryAndSales(List<InventoryItem> inventory,
                                                  List<SalesOrder> sales) {

        Map<Integer, SkuAnalysis> analysisMap = new HashMap<>();

        for (InventoryItem item : inventory) {
            SkuAnalysis analysis = new SkuAnalysis();
            analysis.id = item.id;
            analysis.goodsTitle = item.goodsTitle;
            analysis.skuName = item.skuName;
            analysis.stockNum = item.stockNum;
            analysisMap.put(item.id, analysis);
        }

        for (SalesOrder order : sales) {
            if (analysisMap.containsKey(order.skuId)) {
                SkuAnalysis analysis = analysisMap.get(order.skuId);
                analysis.totalSales += order.count;
                analysis.totalRevenue += order.itemAmount;
                analysis.orderCount++;
                analysis.salesTimes.add(order.orderTime);
            }
        }

        for (SkuAnalysis analysis : analysisMap.values()) {
            analysis.dailyAvgSales = analysis.totalSales / 30.0;
            if (analysis.dailyAvgSales > 0) {
                analysis.daysOfSupply = analysis.stockNum / analysis.dailyAvgSales;
            } else {
                analysis.daysOfSupply = 999;
            }
            analysis.stockStatus = determineStockStatus(analysis.stockNum, analysis.dailyAvgSales);
        }

        return buildLocalAnalysisReport(analysisMap);
    }

    private static String buildLocalAnalysisReport(Map<Integer, SkuAnalysis> analysisMap) {
        StringBuilder sb = new StringBuilder();
        sb.append("## 库存健康度与销售概览（规则生成，非云端大模型）\n\n");
        sb.append("产品：雷士照明 LED 吸顶灯灯芯 | 分析时间：").append(new Date()).append("\n\n");

        List<SkuAnalysis> rows = new ArrayList<>(analysisMap.values());
        rows.sort(Comparator.comparingInt(a -> a.id));

        sb.append("| SKU | 规格 | 库存 | 总销量 | 销售额 | 可售天数(估) | 状态 |\n");
        sb.append("|-----|------|------|--------|--------|-------------|------|\n");
        for (SkuAnalysis a : rows) {
            sb.append(String.format("| %d | %s | %d | %d | %.2f | %.1f | %s |\n",
                    a.id, a.skuName, a.stockNum, a.totalSales, a.totalRevenue, a.daysOfSupply, a.stockStatus));
        }

        sb.append("\n### 补货与运营建议（基于可售天数与状态）\n");
        for (SkuAnalysis a : rows) {
            if ("缺货".equals(a.stockStatus) || "急需补货".equals(a.stockStatus)) {
                sb.append("- SKU ").append(a.id).append(" (").append(a.skuName)
                        .append("): 建议优先补货，当前可售天数约 ").append(String.format("%.1f", a.daysOfSupply)).append(" 天。\n");
            } else if ("库存积压".equals(a.stockStatus) || "库存偏高".equals(a.stockStatus)) {
                sb.append("- SKU ").append(a.id).append(" (").append(a.skuName)
                        .append("): 库存偏高，可考虑促销或调整采购节奏。\n");
            } else if ("滞销".equals(a.stockStatus)) {
                sb.append("- SKU ").append(a.id).append(" (").append(a.skuName)
                        .append("): 近周期销量低，建议核查定价/曝光或搭配销售。\n");
            }
        }
        sb.append("\n> 若需自然语言深度解读，请在本机启动 Ollama 后通过工作助手选择本地模型。\n");
        return sb.toString();
    }

    private static String determineStockStatus(int stock, double dailySales) {
        if (stock == 0) {
            return "缺货";
        }
        if (dailySales == 0) {
            return "滞销";
        }
        double daysOfSupply = stock / dailySales;
        if (daysOfSupply < 7) {
            return "急需补货";
        }
        if (daysOfSupply < 14) {
            return "需要补货";
        }
        if (daysOfSupply < 30) {
            return "库存正常";
        }
        if (daysOfSupply < 60) {
            return "库存偏高";
        }
        return "库存积压";
    }

    private static List<InventoryItem> parseInventoryData() throws IOException {
        return objectMapper.readValue(INVENTORY_JSON,
                new TypeReference<List<InventoryItem>>() {
                });
    }

    private static List<SalesOrder> parseSalesData() throws IOException {
        return objectMapper.readValue(SALES_JSON,
                new TypeReference<List<SalesOrder>>() {
                });
    }

    static class InventoryItem {
        public int id;
        @JsonProperty("goods_title")
        public String goodsTitle;
        @JsonProperty("sku_name")
        public String skuName;
        @JsonProperty("stock_num")
        public int stockNum;
    }

    static class SalesOrder {
        @JsonProperty("order_num")
        public String orderNum;
        @JsonProperty("sku_id")
        public int skuId;
        public int count;
        @JsonProperty("item_amount")
        public double itemAmount;
        @JsonProperty("order_time")
        public String orderTime;
    }

    static class SkuAnalysis {
        public int id;
        public String goodsTitle;
        public String skuName;
        public int stockNum;
        public int totalSales = 0;
        public double totalRevenue = 0.0;
        public int orderCount = 0;
        public double dailyAvgSales = 0.0;
        public double daysOfSupply = 0.0;
        public String stockStatus = "未知";
        public List<String> salesTimes = new ArrayList<>();
    }
}
