package model;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.time.LocalDateTime;
import java.util.stream.Collectors;

public class DataManager {
    private static DataManager instance;
    private Map<String, Goods> goodsMap;
    private List<String> suppliers;
    private Map<String, Integer> inventory;
    private List<OperationLog> operationLogs;

    private DataManager() {
        goodsMap = new HashMap<>();
        suppliers = new ArrayList<>();
        inventory = new HashMap<>();
        operationLogs = new ArrayList<>();
        initializeData();
    }

    public static DataManager getInstance() {
        if (instance == null) {
            instance = new DataManager();
        }
        return instance;
    }

    private void initializeData() {
        // 从数据库加载数据
        loadDataFromDatabase();
    }

    private void loadDataFromDatabase() {
        String url = "jdbc:sqlite:db/dbuml.db3";
        
        try (Connection conn = DriverManager.getConnection(url)) {
            // 加载商品数据
            loadGoods(conn);
            // 加载供应商数据
            loadSuppliers(conn);
            // 加载库存数据
            loadInventory(conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private void loadGoods(Connection conn) throws SQLException {
        String sql = "SELECT * FROM goods";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                String id = rs.getString("id");
                String name = rs.getString("name");
                String specification = rs.getString("specification");
                String unit = rs.getString("unit");
                double price = rs.getDouble("price");
                String category = rs.getString("category");
                String remark = rs.getString("remark");
                
                Goods goods = new Goods(id, name, specification, unit, price, category, 0, remark);
                goodsMap.put(id, goods);
            }
        }
    }

    private void loadSuppliers(Connection conn) throws SQLException {
        String sql = "SELECT supplier_name FROM suppliers";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                suppliers.add(rs.getString("supplier_name"));
            }
        }
    }

    private void loadInventory(Connection conn) throws SQLException {
        String sql = "SELECT goods_id, quantity FROM inventory";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                String goodsId = rs.getString("goods_id");
                int quantity = rs.getInt("quantity");
                inventory.put(goodsId, quantity);
            }
        }
    }

    public void addGoods(Goods goods) {
        goodsMap.put(goods.getId(), goods);
        if (!inventory.containsKey(goods.getId())) {
            inventory.put(goods.getId(), 0);
        }
    }

    public static List<InventoryReport> generateInventoryReport() {
        List<InventoryReport> reports = new ArrayList<>();
        String url = "jdbc:sqlite:db/dbuml.db3";

        try (Connection conn = DriverManager.getConnection(url);
             Statement stmt = conn.createStatement()) {
            
            // 使用与InboundView相同的表结构
            String sql = "SELECT " +
                        "    goods_id, " +
                        "    goods_id as goods_name, " +  // 因为InboundView中使用goods_id存储的是货物名称
                        "    SUM(quantity) as total_quantity, " +
                        "    GROUP_CONCAT(DISTINCT supplier) as supplier, " +
                        "    CASE " +
                        "        WHEN SUM(quantity) < 10 THEN '库存偏低' " +
                        "        ELSE '库存正常' " +
                        "    END as remark " +
                        "FROM inbound_records " +
                        "GROUP BY goods_id " +
                        "ORDER BY goods_id";

            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()) {
                String goodsId = rs.getString("goods_id");
                String goodsName = rs.getString("goods_name");
                int totalQuantity = rs.getInt("total_quantity");
                String supplier = rs.getString("supplier");
                String remark = rs.getString("remark");

                reports.add(new InventoryReport(goodsId, goodsName, totalQuantity, supplier, remark));
            }

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

        return reports;
    }

    public Goods getGoods(String id) {
        return goodsMap.get(id);
    }

    public List<Goods> getAllGoods() {
        return new ArrayList<>(goodsMap.values());
    }

    public List<String> getSuppliers() {
        return new ArrayList<>(suppliers);
    }

    public int getStock(String goodsId) {
        return inventory.getOrDefault(goodsId, 0);
    }

    public void updateStock(String goodsId, int quantity) {
        inventory.put(goodsId, inventory.getOrDefault(goodsId, 0) + quantity);
    }

    public Map<String, Integer> getAllStock() {
        return new HashMap<>(inventory);
    }

    public void addOperationLog(String operationType, String operationTarget, String operator, String details) {
        String id = "LOG" + System.currentTimeMillis();
        OperationLog log = new OperationLog(id, operationType, operationTarget, 
                                          operator, LocalDateTime.now(), details);
        operationLogs.add(log);
    }

    public List<OperationLog> getOperationLogs() {
        return new ArrayList<>(operationLogs);
    }

    public List<OperationLog> getFilteredOperationLogs(LocalDateTime startDate, LocalDateTime endDate, String operationType) {
        return operationLogs.stream()
            .filter(log -> {
                boolean timeMatch = true;
                if (startDate != null && endDate != null) {
                    timeMatch = !log.getOperationTime().isBefore(startDate) && 
                               !log.getOperationTime().isAfter(endDate);
                }
                boolean typeMatch = "全部".equals(operationType) || 
                                  operationType.equals(log.getOperationType());
                return timeMatch && typeMatch;
            })
            .collect(Collectors.toList());
    }
}
