package com.example.myapplication.DataBase;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.example.myapplication.model.ImageSourceItem;
import com.example.myapplication.model.PartResponse;
import com.example.myapplication.model.Project;
import com.example.myapplication.model.Turbine;
import com.google.firebase.crashlytics.buildtools.reloc.com.google.common.reflect.TypeToken;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class DatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "AppDB";
    private static final int DATABASE_VERSION = 7;
    private static final String TABLE_USERS = "users";
    private static final String TABLE_PROJECTS = "projects";
    private static final String TABLE_TURBINES = "turbines";
    // 用户表列名
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_USERNAME = "username";
    public static final String COLUMN_PASSWORD = "password";
    public static final String COLUMN_USER_PROJECT_ID = "user_project_id";
    public static final String COLUMN_USER_PROJECT_NAME = "user_project_name";

    // 项目表列名
    public static final String COLUMN_PROJECT_ID = "project_id";
    public static final String COLUMN_PROJECT_NAME = "project_name";
    public static final String COLUMN_LAST_UPDATED = "last_updated";
    private static final String TABLE_PARTS = "parts";
    public static final String COLUMN_PART_ID = "part_id";
    public static final String COLUMN_PART_NAME = "part_name";
    public static final String COLUMN_PART_CODE = "part_code";
    public static final String COLUMN_PART_TYPE = "part_type";
    public static final String COLUMN_PART_TYPE_LABEL = "part_type_label";
    public static final String COLUMN_Part_PROJECT_ID = "project_id";
    public static final String COLUMN_Part_PROJECT_NAME = "project_name";
    public static final String COLUMN_TURBINE_ID = "turbine_id";
    public static final String COLUMN_TURBINE_NAME = "turbine_name";
    public static final String COLUMN_LAST_SYNC = "last_sync";
    public static final String TABLE_IMAGE_SOURCES = "image_sources";
    public static final String COLUMN_SOURCE_KEY = "source_key";
    public static final String COLUMN_SOURCE_VALUE = "source_value";
    private static final String TABLE_DYNAMIC_DATA = "dynamic_data";
    private static final String COLUMN_JSON_DATA = "json_data";
    private static final String COLUMN_DATA_TYPE = "data_type"; // 用于区分不同类型的数据

    private final Gson gson = new Gson();
    private static final Type MAP_LIST_TYPE = new TypeToken<List<Map<String, String>>>() {}.getType();

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // 创建用户表
        String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_USERNAME + " TEXT UNIQUE,"
                + COLUMN_PASSWORD + " TEXT,"
                + COLUMN_USER_PROJECT_ID + " TEXT,"
                + COLUMN_USER_PROJECT_NAME + " TEXT" + ")";
        db.execSQL(CREATE_USERS_TABLE);

        // 创建项目表
        String CREATE_PROJECTS_TABLE = "CREATE TABLE " + TABLE_PROJECTS + "("
                + COLUMN_PROJECT_ID + " TEXT PRIMARY KEY,"
                + COLUMN_PROJECT_NAME + " TEXT,"
                + COLUMN_LAST_UPDATED + " INTEGER" + ")";
        db.execSQL(CREATE_PROJECTS_TABLE);
        String CREATE_TURBINE_TABLE = "CREATE TABLE " + TABLE_TURBINES + "("
                + COLUMN_TURBINE_ID + " TEXT PRIMARY KEY,"
                + COLUMN_TURBINE_NAME + " TEXT,"
                + COLUMN_PROJECT_ID + " TEXT,"
                + COLUMN_LAST_UPDATED + " INTEGER" + ")";
        db.execSQL(CREATE_TURBINE_TABLE);
        String CREATE_PARTS_TABLE = "CREATE TABLE " + TABLE_PARTS + "("
                + COLUMN_PART_ID + " TEXT PRIMARY KEY,"
                + COLUMN_PART_NAME + " TEXT,"
                + COLUMN_PART_CODE + " TEXT,"
                + COLUMN_PART_TYPE + " TEXT,"
                + COLUMN_PART_TYPE_LABEL + " TEXT,"
                + COLUMN_Part_PROJECT_ID + " TEXT,"
                + COLUMN_Part_PROJECT_NAME + " TEXT,"
                + COLUMN_TURBINE_ID + " TEXT,"
                + COLUMN_TURBINE_NAME + " TEXT,"
                + COLUMN_LAST_SYNC + " INTEGER" + ")";
        db.execSQL(CREATE_PARTS_TABLE);
        String CREATE_IMAGE_SOURCES_TABLE = "CREATE TABLE " + TABLE_IMAGE_SOURCES + "("
                + COLUMN_SOURCE_KEY + " TEXT PRIMARY KEY,"
                + COLUMN_SOURCE_VALUE + " TEXT,"
                + COLUMN_LAST_SYNC + " INTEGER" + ")";
        db.execSQL(CREATE_IMAGE_SOURCES_TABLE);
        // 新增动态数据表
        String CREATE_DYNAMIC_DATA_TABLE = "CREATE TABLE " + TABLE_DYNAMIC_DATA + "("
                + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                + COLUMN_DATA_TYPE + " TEXT NOT NULL,"
                + COLUMN_JSON_DATA + " TEXT NOT NULL,"
                + COLUMN_LAST_SYNC + " INTEGER DEFAULT 0" + ")";
        db.execSQL(CREATE_DYNAMIC_DATA_TABLE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion < 2) {
            // 版本1到版本2的迁移
            db.execSQL("CREATE TABLE " + TABLE_USERS + "_temp" + "("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + COLUMN_USERNAME + " TEXT UNIQUE,"
                    + COLUMN_PASSWORD + " TEXT,"
                    + COLUMN_USER_PROJECT_ID + " TEXT" + ")");

            db.execSQL("INSERT INTO " + TABLE_USERS + "_temp ("
                    + COLUMN_USERNAME + ", " + COLUMN_PASSWORD + ", " + COLUMN_USER_PROJECT_ID + ") "
                    + "SELECT username, password, project FROM " + TABLE_USERS);

            db.execSQL("DROP TABLE " + TABLE_USERS);
            db.execSQL("ALTER TABLE " + TABLE_USERS + "_temp RENAME TO " + TABLE_USERS);
        }

        if (oldVersion < 3) {
            // 版本2到版本3的迁移，添加项目名称列
            db.execSQL("ALTER TABLE " + TABLE_USERS + " ADD COLUMN " + COLUMN_USER_PROJECT_NAME + " TEXT");
        }
        if (oldVersion < 4) {
            // 版本3到版本4的迁移，添加部件表
            String CREATE_PARTS_TABLE = "CREATE TABLE " + TABLE_PARTS + "("
                    + COLUMN_PART_ID + " TEXT PRIMARY KEY,"
                    + COLUMN_PART_NAME + " TEXT,"
                    + COLUMN_PART_CODE + " TEXT,"
                    + COLUMN_PART_TYPE + " TEXT,"
                    + COLUMN_PART_TYPE_LABEL + " TEXT,"
                    + COLUMN_Part_PROJECT_ID + " TEXT,"
                    + COLUMN_Part_PROJECT_NAME + " TEXT,"
                    + COLUMN_TURBINE_ID + " TEXT,"
                    + COLUMN_TURBINE_NAME + " TEXT,"
                    + COLUMN_LAST_SYNC + " INTEGER" + ")";
            db.execSQL(CREATE_PARTS_TABLE);
        }
        if(oldVersion<5)
        {
            String CREATE_IMAGE_SOURCES_TABLE = "CREATE TABLE " + TABLE_IMAGE_SOURCES + "("
                    + COLUMN_SOURCE_KEY + " TEXT PRIMARY KEY,"
                    + COLUMN_SOURCE_VALUE + " TEXT,"
                    + COLUMN_LAST_SYNC + " INTEGER" + ")";
            db.execSQL(CREATE_IMAGE_SOURCES_TABLE);
        }
        if (oldVersion < 6) {
            // 版本5到版本6的迁移：添加动态数据表
            String CREATE_DYNAMIC_DATA_TABLE = "CREATE TABLE " + TABLE_DYNAMIC_DATA + "("
                    + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
                    + COLUMN_DATA_TYPE + " TEXT NOT NULL,"
                    + COLUMN_JSON_DATA + " TEXT NOT NULL,"
                    + COLUMN_LAST_SYNC + " INTEGER DEFAULT 0" + ")";
            db.execSQL(CREATE_DYNAMIC_DATA_TABLE);
        }
        if (oldVersion < 7) {
            // 版本5到版本6的迁移：添加机组表
            String CREATE_TURBINE_TABLE = "CREATE TABLE " + TABLE_TURBINES + "("
                    + COLUMN_TURBINE_ID + " TEXT PRIMARY KEY,"
                    + COLUMN_TURBINE_NAME + " TEXT,"
                    + COLUMN_PROJECT_ID + " TEXT,"
                    + COLUMN_LAST_UPDATED + " INTEGER" + ")";
            db.execSQL(CREATE_TURBINE_TABLE);
        }
    }
    /**
     * 保存动态数据列表
     * @param dataType 数据类型标识（如"work_types"）
     * @param dataList 要保存的数据列表
     */
    public void saveDynamicData(String dataType, List<Map<String, String>> dataList) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            // 删除旧数据
            db.delete(TABLE_DYNAMIC_DATA,
                    COLUMN_DATA_TYPE + " = ?",
                    new String[]{dataType});

            // 插入新数据
            ContentValues values = new ContentValues();
            values.put(COLUMN_DATA_TYPE, dataType);
            values.put(COLUMN_JSON_DATA, gson.toJson(dataList));
            values.put(COLUMN_LAST_SYNC, System.currentTimeMillis());

            db.insert(TABLE_DYNAMIC_DATA, null, values);
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 获取动态数据列表
     * @param dataType 数据类型标识
     * @return 对应的数据列表，如果没有则返回空列表
     */
    public List<Map<String, String>> getDynamicData(String dataType) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_DYNAMIC_DATA,
                new String[]{COLUMN_JSON_DATA},
                COLUMN_DATA_TYPE + " = ?",
                new String[]{dataType},
                null, null,
                COLUMN_LAST_SYNC + " DESC",
                "1"); // 只获取最新的一条

        try {
            if (cursor.moveToFirst()) {
                String jsonData = cursor.getString(0);
                return gson.fromJson(jsonData, MAP_LIST_TYPE);
            }
        } finally {
            cursor.close();
        }
        return new ArrayList<>(); // 返回空列表而非null
    }

    /**
     * 获取指定数据类型的最后同步时间
     */
    public long getDynamicDataLastSync(String dataType) {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_DYNAMIC_DATA,
                new String[]{"MAX(" + COLUMN_LAST_SYNC + ")"},
                COLUMN_DATA_TYPE + " = ?",
                new String[]{dataType},
                null, null, null);

        try {
            if (cursor.moveToFirst()) {
                return cursor.getLong(0);
            }
        } finally {
            cursor.close();
        }
        return 0;
    }

    /**
     * 清除指定类型的数据
     */
    public void clearDynamicData(String dataType) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_DYNAMIC_DATA,
                COLUMN_DATA_TYPE + " = ?",
                new String[]{dataType});
    }
    public void saveImageSources(List<ImageSourceItem> sources) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(TABLE_IMAGE_SOURCES, null, null);

            for (ImageSourceItem source : sources) {
                ContentValues values = new ContentValues();
                values.put(COLUMN_SOURCE_KEY, source.getKey());
                values.put(COLUMN_SOURCE_VALUE, source.getValue());
                values.put(COLUMN_LAST_SYNC, System.currentTimeMillis());
                db.insert(TABLE_IMAGE_SOURCES, null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    public List<ImageSourceItem> getImageSources() {
        List<ImageSourceItem> sources = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_IMAGE_SOURCES,
                new String[]{COLUMN_SOURCE_KEY, COLUMN_SOURCE_VALUE},
                null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                sources.add(new ImageSourceItem(
                        cursor.getString(0),
                        cursor.getString(1)
                ));
            } while (cursor.moveToNext());
        }
        cursor.close();
        return sources;
    }

    /**
     * 保存部件列表到数据库
     */
    public void saveTurbines(List<Turbine> turbines) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            // 先清空表
            db.delete(TABLE_TURBINES, null, null);

            // 插入新数据
            for (Turbine turbine : turbines) {
                ContentValues values = new ContentValues();
                values.put(COLUMN_PROJECT_ID, turbine.getProjectId());
                values.put(COLUMN_TURBINE_ID, turbine.getTurbineId());
                values.put(COLUMN_TURBINE_NAME, turbine.getTurbineName());
                values.put(COLUMN_LAST_SYNC, System.currentTimeMillis());

                db.insert(TABLE_TURBINES, null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    @SuppressLint("Range")
    public List<Turbine> getTurbinesByProjectId(String projectId) {
        List<Turbine> turbines = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        // 定义查询条件
        String selection = COLUMN_PROJECT_ID + " = ?";
        String[] selectionArgs = { projectId };

        Cursor cursor = db.query(TABLE_TURBINES,
                null,
                selection, selectionArgs, null, null, COLUMN_TURBINE_NAME + " ASC");

        if (cursor.moveToFirst()) {
            do {
                Turbine turbine = new Turbine();
                turbine.setProjectId(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_ID)));
                turbine.setTurbineId(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_ID)));
                turbine.setTurbineName(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_NAME)));
                turbines.add(turbine);
            } while (cursor.moveToNext());
        }
        cursor.close();
        // 关闭游标
        cursor.close();
        return turbines;
    }


    /**
     * 获取所有部件
     */
    @SuppressLint("Range")
    public List<Turbine> getAllTurbines() {
        List<Turbine> turbines = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_TURBINES,
                null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                Turbine turbine = new Turbine();
                turbine.setProjectId(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_ID)));
                turbine.setTurbineId(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_ID)));
                turbine.setTurbineName(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_NAME)));

                turbines.add(turbine);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return turbines;
    }

    @SuppressLint("Range")
    public List<Turbine> searchTurbines(String query) {
        List<Turbine> turbines = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_TURBINE_NAME + " LIKE ? OR " + COLUMN_TURBINE_ID + " LIKE ?";
        String[] selectionArgs = new String[]{"%" + query + "%", "%" + query + "%"};

        Cursor cursor = db.query(TABLE_TURBINES,
                null, selection, selectionArgs, null, null, COLUMN_TURBINE_NAME + " ASC");

        if (cursor.moveToFirst()) {
            do {
                Turbine part = new Turbine();
                part.setProjectId(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_ID)));
                part.setTurbineId(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_ID)));
                part.setTurbineName(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_NAME)));

                turbines.add(part);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return turbines;
    }
    /**
     * 保存部件列表到数据库
     */
    public void saveParts(List<PartResponse> parts) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            // 先清空表
            db.delete(TABLE_PARTS, null, null);

            // 插入新数据
            for (PartResponse part : parts) {
                ContentValues values = new ContentValues();
                values.put(COLUMN_PART_ID, part.getPartId());
                values.put(COLUMN_PART_NAME, part.getPartName());
                values.put(COLUMN_PART_CODE, part.getPartCode());
                values.put(COLUMN_PART_TYPE, part.getPartType());
                values.put(COLUMN_PART_TYPE_LABEL, part.getPartTypeLabel());
                values.put(COLUMN_PROJECT_ID, part.getProjectId());
                values.put(COLUMN_PROJECT_NAME, part.getProjectName());
                values.put(COLUMN_TURBINE_ID, part.getTurbineId());
                values.put(COLUMN_TURBINE_NAME, part.getTurbineName());
                values.put(COLUMN_LAST_SYNC, System.currentTimeMillis());

                db.insert(TABLE_PARTS, null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    /**
     * 根据部件名称获取部件ID
     */
    public String getPartIdByName(String partName) {
        SQLiteDatabase db = this.getReadableDatabase();
        String partId = null;

        Cursor cursor = db.query(TABLE_PARTS,
                new String[]{COLUMN_PART_ID},
                COLUMN_PART_NAME + " = ?",
                new String[]{partName},
                null, null, null);

        if (cursor.moveToFirst()) {
            partId = cursor.getString(0);
        }
        cursor.close();
        return partId;
    }

    /**
     * 获取所有部件
     */
    @SuppressLint("Range")
    public List<PartResponse> getAllParts() {
        List<PartResponse> parts = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_PARTS,
                null, null, null, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                PartResponse part = new PartResponse();
                part.setPartId(cursor.getString(cursor.getColumnIndex(COLUMN_PART_ID)));
                part.setPartName(cursor.getString(cursor.getColumnIndex(COLUMN_PART_NAME)));
                part.setPartCode(cursor.getString(cursor.getColumnIndex(COLUMN_PART_CODE)));
                part.setPartType(cursor.getString(cursor.getColumnIndex(COLUMN_PART_TYPE)));
                part.setPartTypeLabel(cursor.getString(cursor.getColumnIndex(COLUMN_PART_TYPE_LABEL)));
                part.setProjectId(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_ID)));
                part.setProjectName(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_NAME)));
                part.setTurbineId(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_ID)));
                part.setTurbineName(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_NAME)));

                parts.add(part);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return parts;
    }
    @SuppressLint("Range")
    public List<PartResponse> getPartsByTurbineId(String turbineId) {
        List<PartResponse> parts = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();

        // 定义查询条件
        String selection = COLUMN_TURBINE_ID + " = ?";
        String[] selectionArgs = { turbineId };

        // 执行查询
        Cursor cursor = db.query(
                TABLE_PARTS,                     // 表名
                null,                            // 查询的列（null 表示查询所有列）
                selection,                       // WHERE 条件
                selectionArgs,                   // WHERE 条件的参数
                null,                            // GROUP BY
                null,                            // HAVING
                null                             // ORDER BY
        );

        // 遍历查询结果
        if (cursor.moveToFirst()) {
            do {
                PartResponse part = new PartResponse();
                part.setPartId(cursor.getString(cursor.getColumnIndex(COLUMN_PART_ID)));
                part.setPartName(cursor.getString(cursor.getColumnIndex(COLUMN_PART_NAME)));
                part.setPartCode(cursor.getString(cursor.getColumnIndex(COLUMN_PART_CODE)));
                part.setPartType(cursor.getString(cursor.getColumnIndex(COLUMN_PART_TYPE)));
                part.setPartTypeLabel(cursor.getString(cursor.getColumnIndex(COLUMN_PART_TYPE_LABEL)));
                part.setProjectId(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_ID)));
                part.setProjectName(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_NAME)));
                part.setTurbineId(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_ID)));
                part.setTurbineName(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_NAME)));

                parts.add(part);
            } while (cursor.moveToNext());
        }

        // 关闭游标
        cursor.close();
        return parts;
    }

    @SuppressLint("Range")
    public List<PartResponse> searchParts(String query) {
        List<PartResponse> parts = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PART_NAME + " LIKE ? OR " + COLUMN_PART_ID + " LIKE ?";
        String[] selectionArgs = new String[]{"%" + query + "%", "%" + query + "%"};

        // 执行查询
        Cursor cursor = db.query(
                TABLE_PARTS,                     // 表名
                null,                            // 查询的列（null 表示查询所有列）
                selection,                       // WHERE 条件
                selectionArgs,                   // WHERE 条件的参数
                null,                            // GROUP BY
                null,                            // HAVING
                COLUMN_PART_NAME + " ASC"                             // ORDER BY
        );

        // 遍历查询结果
        if (cursor.moveToFirst()) {
            do {
                PartResponse part = new PartResponse();
                part.setPartId(cursor.getString(cursor.getColumnIndex(COLUMN_PART_ID)));
                part.setPartName(cursor.getString(cursor.getColumnIndex(COLUMN_PART_NAME)));
                part.setPartCode(cursor.getString(cursor.getColumnIndex(COLUMN_PART_CODE)));
                part.setPartType(cursor.getString(cursor.getColumnIndex(COLUMN_PART_TYPE)));
                part.setPartTypeLabel(cursor.getString(cursor.getColumnIndex(COLUMN_PART_TYPE_LABEL)));
                part.setProjectId(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_ID)));
                part.setProjectName(cursor.getString(cursor.getColumnIndex(COLUMN_Part_PROJECT_NAME)));
                part.setTurbineId(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_ID)));
                part.setTurbineName(cursor.getString(cursor.getColumnIndex(COLUMN_TURBINE_NAME)));

                parts.add(part);
            } while (cursor.moveToNext());
        }

        cursor.close();
        return parts;
    }
    /**
     * 获取最后同步时间
     */
    public long getLastSyncTime() {
        SQLiteDatabase db = this.getReadableDatabase();
        long lastSync = 0;

        Cursor cursor = db.query(TABLE_PARTS,
                new String[]{"MAX(" + COLUMN_LAST_SYNC + ")"},
                null, null, null, null, null);

        if (cursor.moveToFirst()) {
            lastSync = cursor.getLong(0);
        }
        cursor.close();
        return lastSync;
    }
    // 用户操作方法
    public boolean addUser(String username, String password) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USERNAME, username);
        values.put(COLUMN_PASSWORD, password);

        long result = db.insert(TABLE_USERS, null, values);
        db.close();
        return result != -1;
    }

    public boolean updateUserProject(String username, String newProjectId, String newProjectName) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(COLUMN_USER_PROJECT_ID, newProjectId);
        values.put(COLUMN_USER_PROJECT_NAME, newProjectName);
        int result = db.update(TABLE_USERS, values,
                COLUMN_USERNAME + " = ?",
                new String[]{username});
        db.close();
        return result > 0;
    }

    public Cursor getAllUsers() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.query(TABLE_USERS,
                new String[]{COLUMN_ID, COLUMN_USERNAME, COLUMN_PASSWORD,
                        COLUMN_USER_PROJECT_ID, COLUMN_USER_PROJECT_NAME},
                null, null, null, null, null);
    }

    public boolean deleteUser(String username) {
        SQLiteDatabase db = this.getWritableDatabase();
        int result = db.delete(TABLE_USERS,
                COLUMN_USERNAME + " = ?",
                new String[]{username});
        db.close();
        return result > 0;
    }

    public boolean checkUser(String username, String password) {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {COLUMN_ID};
        String selection = COLUMN_USERNAME + " = ? AND " + COLUMN_PASSWORD + " = ?";
        String[] selectionArgs = {username, password};

        Cursor cursor = db.query(TABLE_USERS, columns, selection, selectionArgs,
                null, null, null);
        int count = cursor.getCount();
        cursor.close();
        db.close();
        return count > 0;
    }

    public boolean userExists(String username) {
        SQLiteDatabase db = this.getReadableDatabase();
        String[] columns = {COLUMN_ID};
        String selection = COLUMN_USERNAME + " = ?";
        String[] selectionArgs = {username};

        Cursor cursor = db.query(TABLE_USERS, columns, selection, selectionArgs,
                null, null, null);
        int count = cursor.getCount();
        cursor.close();
        db.close();
        return count > 0;
    }

    // 项目操作方法
    public void saveProjects(List<Project> projects) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.beginTransaction();
        try {
            db.delete(TABLE_PROJECTS, null, null);

            for (Project project : projects) {
                ContentValues values = new ContentValues();
                values.put(COLUMN_PROJECT_ID, project.getProjectId());
                values.put(COLUMN_PROJECT_NAME, project.getProjectName());
                values.put(COLUMN_LAST_UPDATED, System.currentTimeMillis());
                db.insert(TABLE_PROJECTS, null, values);
            }
            db.setTransactionSuccessful();
        } finally {
            db.endTransaction();
        }
    }

    public List<Project> getAllProjects() {
        List<Project> projects = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PROJECTS,
                new String[]{COLUMN_PROJECT_ID, COLUMN_PROJECT_NAME},
                null, null, null, null, COLUMN_PROJECT_NAME + " ASC");

        if (cursor.moveToFirst()) {
            do {
                Project project = new Project(
                        cursor.getString(0),
                        cursor.getString(1)
                );
                projects.add(project);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return projects;
    }

    public List<Project> searchProjects(String query) {
        List<Project> projects = new ArrayList<>();
        SQLiteDatabase db = this.getReadableDatabase();
        String selection = COLUMN_PROJECT_NAME + " LIKE ? OR " + COLUMN_PROJECT_ID + " LIKE ?";
        String[] selectionArgs = new String[]{"%" + query + "%", "%" + query + "%"};

        Cursor cursor = db.query(TABLE_PROJECTS,
                new String[]{COLUMN_PROJECT_ID, COLUMN_PROJECT_NAME},
                selection, selectionArgs, null, null, COLUMN_PROJECT_NAME + " ASC");

        if (cursor.moveToFirst()) {
            do {
                Project project = new Project(
                        cursor.getString(0),
                        cursor.getString(1)
                );
                projects.add(project);
            } while (cursor.moveToNext());
        }
        cursor.close();
        return projects;
    }

    public void updateLastUpdateTime(long time) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("last_update_time", time);

        // 更新或插入最后更新时间
        db.insertWithOnConflict("app_settings", null, values, SQLiteDatabase.CONFLICT_REPLACE);
        db.close();
    }

    // 添加这个方法

    public long getLastUpdateTime() {
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.query(TABLE_PROJECTS,
                new String[]{"MAX(" + COLUMN_LAST_UPDATED + ")"},
                null, null, null, null, null);

        long lastUpdated = 0;
        if (cursor.moveToFirst()) {
            lastUpdated = cursor.getLong(0);
        }
        cursor.close();
        return lastUpdated;
    }
}