package com.sxyz.rfid.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Build;
import android.os.Environment;

import com.sxyz.rfid.BuildConfig;
import com.sxyz.rfid.utils.L;

import org.greenrobot.greendao.identityscope.IdentityScopeType;
import org.greenrobot.greendao.query.QueryBuilder;

import java.io.File;

import sql.com.yz.db.DaoMaster;
import sql.com.yz.db.DaoSession;

public class GreenDaoManager {
    private static final String TAG = GreenDaoManager.class.getSimpleName();
    public static final String DB_NAME = "wms_data.db";

    private Context context;
    private volatile static GreenDaoManager manager = new GreenDaoManager();
    private DaoMaster sDaoMaster;
    private DaoMaster.DevOpenHelper sHelper;
    private DaoSession sDaoSession;
    private String currentDbPath; // 记录当前数据库路径

    public static GreenDaoManager getInstance() {
        return manager;
    }

    private GreenDaoManager() {
        setDebug();
    }

    public void init(Context context) {
        this.context = context;
        // 初始化时记录数据库路径
        File dbFile = getDatabaseFile(context);
        this.currentDbPath = dbFile.getAbsolutePath();
    }

    /**
     * 获取数据库文件
     */
    public File getDatabaseFile(Context context) {
        File dbDir = getExternalDatabaseDir(context);
        if (!dbDir.exists()) {
            dbDir.mkdirs();
        }
        return new File(dbDir, DB_NAME);
    }

    private static File getExternalDatabaseDir(Context context) {
        // Android 10 以下版本
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            return new File(Environment.getExternalStorageDirectory(), "Android/data/" + context.getPackageName() + "/files/databases/" + DB_NAME);
        }
        // Android 10 及以上版本 - 使用应用专属外部存储
        return new File(context.getExternalFilesDir(null), "databases");
    }

    /**
     * 重置数据库连接 - 关键方法
     */
    public void resetConnection() {
        closeConnection();
        sDaoMaster = null;
        sDaoSession = null;
        sHelper = null;
    }

    /**
     * 检查是否需要重新创建连接
     */
    private boolean needRecreateConnection() {
        if (sDaoMaster == null || sDaoSession == null) {
            return true;
        }

        // 检查数据库文件是否存在
        File dbFile = getDatabaseFile(context);
        boolean fileExists = dbFile.exists();

        // 如果文件不存在但连接存在，需要重置
        if (!fileExists && sDaoMaster != null) {
            return true;
        }

        // 检查路径是否变化
        if (currentDbPath != null && !currentDbPath.equals(dbFile.getAbsolutePath())) {
            return true;
        }

        return false;
    }

    public DaoMaster getDaoMaster() {
        // 每次获取前检查是否需要重建连接
        if (needRecreateConnection()) {
            resetConnection();
        }
        if (sDaoMaster == null) {
            File dbFile = getDatabaseFile(context);
            currentDbPath = dbFile.getAbsolutePath();

            if (dbFile.exists()) {
                try {
                    // 检查数据库是否可以正常打开
                    SQLiteDatabase db = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
                    sDaoMaster = new DaoMaster(db);
                } catch (Exception e) {
                    L.i("打开数据库失败===>" + dbFile.getAbsolutePath());
                    // 删除损坏的数据库文件
                    if (dbFile.exists()) {
                        dbFile.delete();
                    }
                    resetConnection();
                    return null;
                }
            } else {
                // 数据库文件不存在，返回null
                L.i("数据库文件不存在===>" + dbFile.getAbsolutePath());
                return null;
            }
        }
        return sDaoMaster;
    }

    public DaoSession getDaoSession() {
        resetConnection();
        if (needRecreateConnection()) {
            resetConnection();
        }
        if (sDaoSession == null) {
            DaoMaster daoMaster = getDaoMaster();
            if (daoMaster != null) {
                sDaoSession = daoMaster.newSession(IdentityScopeType.None);
            }
        }
        return sDaoSession;
    }

    /**
     * 删除数据库文件的完整方法
     */
    public boolean deleteDatabaseFile() {
        resetConnection(); // 先关闭所有连接

        File dbFile = getDatabaseFile(context);
        if (dbFile.exists()) {
            boolean deleted = dbFile.delete();
            if (deleted) {
                // 清除所有缓存
                resetConnection();
                // 也删除数据库的journal文件等
                File journalFile = new File(dbFile.getPath() + "-journal");
                if (journalFile.exists()) {
                    journalFile.delete();
                }
                File walFile = new File(dbFile.getPath() + "-wal");
                if (walFile.exists()) {
                    walFile.delete();
                }
                File shmFile = new File(dbFile.getPath() + "-shm");
                if (shmFile.exists()) {
                    shmFile.delete();
                }
                return true;
            }
        }
        return false;
    }

    // 其他方法保持不变...

    /**
     * 打开输出日志，默认关闭
     */
    public void setDebug() {
        if (BuildConfig.DEBUG) {
            QueryBuilder.LOG_SQL = true;
            QueryBuilder.LOG_VALUES = true;
        }
    }

    /**
     * 关闭所有的操作，数据库开启后，使用完毕要关闭
     */
    public void closeConnection() {
        closeHelper();
        closeDaoSession();
    }

    public void closeHelper() {
        if (sHelper != null) {
            sHelper.close();
            sHelper = null;
        }
    }

    public void closeDaoSession() {
        if (sDaoSession != null) {
            sDaoSession.clear();
            sDaoSession = null;
        }
    }
}
