package com.haha.common.enums;

public enum DeviceDoorStatus {

    ERROR("ERROR", "开门失败"),
    OPENED("OPENED", "门已开"),
    CLOSED("CLOSED", "门已关"),
    BUSY("ANOTHER", "设备繁忙");

    private final String code;
    private final String description;

    DeviceDoorStatus(String code, String description) {
        this.code = code;
        this.description = description;
    }

    public String getCode() {
        return code;
    }

    public String getDescription() {
        return description;
    }

    public static DeviceDoorStatus fromCode(String code) {
        if (code == null) {
            return null;
        }
        for (DeviceDoorStatus doorStatus : values()) {
            if (doorStatus.code.equals(code)) {
                return doorStatus;
            }
        }
        return null;
    }

    /**
     * 将原始状态码转换为数据库存储的字符串值
     * @param code 原始状态码("1","2","3","4")
     * @return 数据库存储的字符串值("ERROR","OPENED","CLOSED","ANOTHER")
     */
    public static String convertToDbValue(String code) {
        DeviceDoorStatus doorStatus = fromCode(code);
        return doorStatus != null ? doorStatus.getCode() : "UNKNOWN";
    }
    
    /**
     * 从数据库存储的字符串值获取枚举
     * @param dbValue 数据库中的字符串值
     * @return 对应的枚举值
     */
    public static DeviceDoorStatus fromDbValue(String dbValue) {
        if (dbValue == null) {
            return null;
        }
        for (DeviceDoorStatus doorStatus : values()) {
            if (doorStatus.getCode().equals(dbValue)) {
                return doorStatus;
            }
        }
        return null;
    }
    
    /**
     * 将数据库值转换为前端显示的状态
     * 返回简化的显示状态
     */
    public static String convertToStatus(String dbValue) {
        DeviceDoorStatus doorStatus = fromDbValue(dbValue);
        if (doorStatus == null) {
            return "unknown";
        }
        
        // 根据枚举值返回对应的简化状态
        return switch (doorStatus) {
            case ERROR -> "error";
            case OPENED -> "open";
            case CLOSED -> "close";
            case BUSY -> "busy";
        };
    }
}
