package model;

import java.sql.*;
import java.time.format.DateTimeFormatter;
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 inbound_records";
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(sql)) {
            while (rs.next()) {
                String id = rs.getString("goods_id");
                String name = rs.getString("goods_id"); // Assuming goods_id is also the name in inbound_records
                String specification = ""; // Not available in inbound_records
                String unit = ""; // Not available in inbound_records
                double price = 0; // Not available in inbound_records
                String category = ""; // Not available in inbound_records
                String remark = rs.getString("remark");

                Goods goods = new Goods(id, name, 0, remark);
                goodsMap.put(id, goods);
            }
        }
    }

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

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

    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()) {

            String sql = "SELECT " +
                    "    goods_id, " +
                    "    goods_id as goods_name, " +
                    "    SUM(quantity) as total_quantity, " +
                    "    GROUP_CONCAT(DISTINCT supplier) as supplier, " +
                    "    CASE " +
                    "        WHEN SUM(quantity) < 10 THEN '库存偏低' " +
                    "        ELSE '库存正常' " +
                    "    END as remark " +
                    "FROM warehouse " +
                    "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());
    }


    public void addGoodsToDatabase(Goods goods) {
        String url = "jdbc:sqlite:db/dbuml.db3";
        String sql = "INSERT INTO warehouse (id, goods_id, quantity, supplier, inbound_time, operator, remark) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(url);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            // Generate a unique ID for each record
            String recordId = "REC" + System.currentTimeMillis();
            pstmt.setString(1, recordId);

            pstmt.setString(2, goods.getId());
            pstmt.setInt(3, goods.getQuantity());
            pstmt.setString(4, goods.getSupplier());

            // Format LocalDateTime to ISO_LOCAL_DATE_TIME format
            DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
            String inboundTimeString = goods.getInboundTime().format(formatter);
            pstmt.setString(5, inboundTimeString);

            pstmt.setString(6, goods.getOperator());
            pstmt.setString(7, goods.getRemark());

            pstmt.executeUpdate();

            // Synchronize memory data
            addGoods(goods);

            // Add operation log
            addOperationLog("新增", goods.getId(), "当前用户", "新增货物: " + goods.getName());
        } catch (SQLException e) {
            e.printStackTrace();
            showAlert("错误", "添加货物失败：" + e.getMessage());
        }
    }


    public void updateGoodsInDatabase(Goods goods) {
        String url = "jdbc:sqlite:db/dbuml.db3";
        String sql = "UPDATE warehouse SET quantity = ?, supplier = ?, inbound_time = ?, operator = ?, remark = ? WHERE goods_id = ? ORDER BY inbound_time DESC LIMIT 1";
        try (Connection conn = DriverManager.getConnection(url);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, goods.getQuantity());
            pstmt.setString(2, goods.getSupplier());
            pstmt.setString(3, goods.getInboundTime().toString());
            pstmt.setString(4, goods.getOperator());
            pstmt.setString(5, goods.getRemark());
            pstmt.setString(6, goods.getId());

            pstmt.executeUpdate();
            addOperationLog("更新", goods.getId(), "当前用户", "更新货物: " + goods.getName());
        } catch (SQLException e) {
            e.printStackTrace();
            showAlert("错误", "更新货物失败：" + e.getMessage());
        }
    }


    private void showAlert(String 错误, String s) {
    }

    public List<String> getAllCategories() {
        return goodsMap.values().stream()
                .map(Goods::getCategory)
                .distinct()
                .collect(Collectors.toList());
    }
}
