package model;

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

public class DataGoods {
    private static DataGoods instance;
    private Map<String, Goods> goodsMap;
    private Map<String, Integer> inventory;


    public DataGoods() {
        goodsMap = new HashMap<>();
        inventory = new HashMap<>();
        initializeData();
    }

    public static DataGoods getInstance() {
        if (instance == null) {
            instance = new DataGoods();
        }
        return instance;
    }
    private void initializeData() {
        // 电子产品类
        addGoodsWithStock("NO00000000001", "苹果手机", "iPhone 15", "台", 6999.00, "电子产品", 50);
        addGoodsWithStock("NO00000000002", "联想笔记本", "ThinkPad T14", "台", 5999.00, "电子产品", 30);
        addGoodsWithStock("G003", "华为平板", "MatePad Pro", "台", 3999.00, "电子产品", 40);
        addGoodsWithStock("G004", "戴尔显示器", "27寸 4K", "台", 2399.00, "电子产品", 25);

        // 办公家具类
        addGoodsWithStock("G005", "办公桌", "1.4米", "张", 799.00, "办公家具", 100);
        addGoodsWithStock("G006", "办公椅", "人体工学", "把", 599.00, "办公家具", 150);
        addGoodsWithStock("G007", "文件柜", "三层", "个", 459.00, "办公家具", 80);
        addGoodsWithStock("G008", "会议桌", "2.4米", "张", 1599.00, "办公家具", 20);

        // 办公用品类
        addGoodsWithStock("G009", "打印纸", "A4 70g", "箱", 89.00, "办公用品", 200);
        addGoodsWithStock("G010", "签字笔", "0.5mm黑色", "盒", 15.00, "办公用品", 500);
        addGoodsWithStock("G011", "订书机", "标准型", "个", 35.00, "办公用品", 300);
        addGoodsWithStock("G012", "文件夹", "A4蓝色", "个", 8.00, "办公用品", 1000);
    }

    private void addGoodsWithStock(String id, String name, String specification,
                                   String unit, double price, String category, int initialStock) {
        Goods goods = new Goods(id, name, specification, unit, price, category, initialStock, "");
        goodsMap.put(id, goods);
        inventory.put(id, initialStock);
    }

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

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

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

    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 addGoodsToDatabase(Goods goods) {
        String url = "jdbc:sqlite:db/dbuml.db3";
        String sql = "INSERT INTO goods (id, name, specification, unit, price, category, quantity, remark, inbound_time, operator, supplier) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        try (Connection conn = DriverManager.getConnection(url);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, goods.getId());
            pstmt.setString(2, goods.getName());
            pstmt.setString(3, goods.getSpecification());
            pstmt.setString(4, goods.getUnit());
            pstmt.setDouble(5, goods.getPrice());
            pstmt.setString(6, goods.getCategory());
            pstmt.setInt(7, goods.getQuantity());
            pstmt.setString(8, goods.getRemark());
            pstmt.setString(9, goods.getInboundTime().toString());
            pstmt.setString(10, goods.getOperator());
            pstmt.setString(11, goods.getSupplier());

            pstmt.executeUpdate();
            addGoods(goods); // 同步内存中的数据
            DataManager.getInstance().addOperationLog("新增", goods.getId(), "当前用户", "新增货物: " + goods.getName());
        } catch (SQLException e) {
            e.printStackTrace();
            DataManager.showAlert("错误", "添加货物失败：" + e.getMessage());
        }
    }

    public void updateGoodsInDatabase(Goods goods) {
        String url = "jdbc:sqlite:db/dbuml.db3";
        String sql = "UPDATE goods SET name = ?, specification = ?, unit = ?, price = ?, category = ?, " +
                "quantity = ?, remark = ?, inbound_time = ?, operator = ?, supplier = ? WHERE id = ?";
        try (Connection conn = DriverManager.getConnection(url);
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, goods.getName());
            pstmt.setString(2, goods.getSpecification());
            pstmt.setString(3, goods.getUnit());
            pstmt.setDouble(4, goods.getPrice());
            pstmt.setString(5, goods.getCategory());
            pstmt.setInt(6, goods.getQuantity());
            pstmt.setString(7, goods.getRemark());
            pstmt.setString(8, goods.getInboundTime().toString());
            pstmt.setString(9, goods.getOperator());
            pstmt.setString(10, goods.getSupplier());
            pstmt.setString(11, goods.getId());

            pstmt.executeUpdate();
            addGoods(goods); // 同步内存中的数据
            DataManager.getInstance().addOperationLog("更新", goods.getId(), "当前用户", "更新货物: " + goods.getName());
        } catch (SQLException e) {
            e.printStackTrace();
            DataManager.showAlert("错误", "更新货物失败：" + e.getMessage());
        }
    }

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