/*
 * Copyright (c) 2010-2011, The MiCode Open Source Community (www.micode.net)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.micode.notes.ui;

import android.app.Activity;
import net.micode.notes.ui.PasswordInputActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.SearchManager;
import android.appwidget.AppWidgetManager;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.HapticFeedbackConstants;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.View.OnTouchListener;
import android.widget.TextView.OnEditorActionListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import net.micode.notes.R;
import net.micode.notes.data.Notes;
import net.micode.notes.data.Notes.NoteColumns;
import net.micode.notes.data.Notes.TextNote;
import net.micode.notes.data.NotesDatabaseHelper;
import net.micode.notes.gtask.remote.GTaskSyncService;
import net.micode.notes.model.ChecklistManager;
import net.micode.notes.model.WorkingNote;
import net.micode.notes.tool.BackupUtils;
import net.micode.notes.tool.DataUtils;
import net.micode.notes.tool.ResourceParser;
import net.micode.notes.ui.NotesListAdapter.AppWidgetAttribute;
import net.micode.notes.widget.NoteWidgetProvider_2x;
import net.micode.notes.widget.NoteWidgetProvider_4x;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.Set;

import android.os.Build;
import android.view.Gravity;
import android.view.ViewConfiguration;
import android.graphics.Color;
import java.lang.reflect.Field;

/**
 * 笔记列表活动 - 负责显示和管理笔记列表
 * 提供笔记的创建、编辑、删除、移动等功能
 * 支持文件夹管理和多选操作模式
 */
public class NotesListActivity extends Activity implements OnClickListener, OnItemLongClickListener {
    private static final int FOLDER_NOTE_LIST_QUERY_TOKEN = 0;

    private static final int FOLDER_LIST_QUERY_TOKEN      = 1;

    private static final int MENU_FOLDER_DELETE = 0;

    private static final int MENU_FOLDER_VIEW = 1;

    // 标签云相关控件
    private LinearLayout mTagCloudSection;         // 标签云区域
    private LinearLayout mTagCloudContainer;       // 标签云容器
    private Button mAllNotesTag;                   // 全部笔记标签
    private String mCurrentFilterTag;              // 当前过滤标签

    // 搜索历史相关
    private static final String PREFERENCE_SEARCH_HISTORY = "search_history";  // 搜索历史偏好设置键
    private static final int MAX_SEARCH_HISTORY = 20;  // 最大搜索历史记录数
    private String mSearchQuery;  // 当前搜索查询字符串
    private boolean mIsSearchMode;  // 是否处于搜索模式

    // 实时搜索相关
    private LinearLayout mSearchBar;  // 搜索栏容器
    private EditText mSearchEditText;  // 搜索输入框
    private ImageButton mClearSearchButton;  // 清除搜索按钮
    private static final int SEARCH_DEBOUNCE_DELAY = 300;  // 搜索防抖延迟时间（毫秒）
    private Runnable mSearchRunnable;  // 搜索任务
    private long mLastSearchTime;  // 上次搜索时间

    private static final int MENU_FOLDER_CHANGE_NAME = 2;

    private static final String PREFERENCE_ADD_INTRODUCTION = "net.micode.notes.introduction";

    private enum ListEditState {
        NOTE_LIST, SUB_FOLDER, CALL_RECORD_FOLDER
    };

    private ListEditState mState;
    private boolean mIsChecklistMode;                       // 是否为清单模式（OMO）
    private Button mNoteModeButton;                         // 笔记模式按钮（OMO）
    private Button mChecklistModeButton;                    // 清单模式按钮（OMO）
    private ChecklistManager mChecklistManager;             // 清单管理器（OMO）

    private BackgroundQueryHandler mBackgroundQueryHandler;

    private NotesListAdapter mNotesListAdapter;

    private ListView mNotesListView;

    private Button mAddNewNote;

    private boolean mDispatch;

    private int mOriginY;

    private int mDispatchY;

    private TextView mTitleBar;

    private long mCurrentFolderId;

    private ContentResolver mContentResolver;

    private ModeCallback mModeCallBack;

    private static final String TAG = "NotesListActivity";

    public static final int NOTES_LISTVIEW_SCROLL_RATE = 30;

    private NoteItemData mFocusNoteDataItem;

    private static final String NORMAL_SELECTION = NoteColumns.PARENT_ID + "=?";

    private static final String ROOT_FOLDER_SELECTION = "(" + NoteColumns.TYPE + "<>"
            + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" + " OR ("
            + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND "
            + NoteColumns.NOTES_COUNT + ">0)";

    private final static int REQUEST_CODE_OPEN_NODE = 102;
    private final static int REQUEST_CODE_NEW_NODE  = 103;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 隐藏标题栏OMO
        if (getActionBar() != null) {
            getActionBar().hide();
        }

        setContentView(R.layout.note_list); // 设置布局
        initResources(); // 初始化资源

        // 隐藏底部虚拟菜单按钮OMO
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = null;
            try {
                menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
                if (menuKeyField != null) {
                    menuKeyField.setAccessible(true);
                    menuKeyField.setBoolean(config, false);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        // 首次进入时插入“介绍”笔记
        setAppInfoFromRawRes(); // 设置应用信息（首次使用时添加介绍笔记）
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK
                && (requestCode == REQUEST_CODE_OPEN_NODE || requestCode == REQUEST_CODE_NEW_NODE)) {
            mNotesListAdapter.changeCursor(null);
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    private void setAppInfoFromRawRes() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (!sp.getBoolean(PREFERENCE_ADD_INTRODUCTION, false)) {
            StringBuilder sb = new StringBuilder();
            InputStream in = null;
            try {
                in = getResources().openRawResource(R.raw.introduction);
                if (in != null) {
                    InputStreamReader isr = new InputStreamReader(in);
                    BufferedReader br = new BufferedReader(isr);
                    char [] buf = new char[1024];
                    int len = 0;
                    while ((len = br.read(buf)) > 0) {
                        sb.append(buf, 0, len);
                    }
                } else {
                    Log.e(TAG, "Read introduction file error");
                    return;
                }
            } catch (IOException e) {
                e.printStackTrace();
                return;
            } finally {
                if(in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

            WorkingNote note = WorkingNote.createEmptyNote(this, Notes.ID_ROOT_FOLDER,
                    AppWidgetManager.INVALID_APPWIDGET_ID, Notes.TYPE_WIDGET_INVALIDE,
                    ResourceParser.RED);
            note.setWorkingText(sb.toString());
            if (note.saveNote()) {
                sp.edit().putBoolean(PREFERENCE_ADD_INTRODUCTION, true).commit();
            } else {
                Log.e(TAG, "Save introduction note error");
                return;
            }
        }
    }

    /**
     * 当活动开始时调用
     * 启动异步查询笔记列表
     */
    @Override
    protected void onStart() {
        super.onStart();
        startAsyncNotesListQuery();
    }

    /**
     * 初始化资源
     * 设置内容解析器、异步查询处理器、列表适配器等
     */
    private void initResources() {
        mContentResolver = this.getContentResolver();
        mBackgroundQueryHandler = new BackgroundQueryHandler(this.getContentResolver());
        mCurrentFolderId = Notes.ID_ROOT_FOLDER;
        mNotesListView = (ListView) findViewById(R.id.notes_list);
        mNotesListView.setOnItemClickListener(new OnListItemClickListener());
        mNotesListView.setOnItemLongClickListener(this);
        mNotesListAdapter = new NotesListAdapter(this);
        mNotesListView.setAdapter(mNotesListAdapter);
        mAddNewNote = (Button) findViewById(R.id.btn_new_note);
        mAddNewNote.setOnClickListener(this);
        mAddNewNote.setOnTouchListener(new NewNoteOnTouchListener());
        mDispatch = false;
        mDispatchY = 0;
        mOriginY = 0;
        mTitleBar = (TextView) findViewById(R.id.tv_title_bar);
        mState = ListEditState.NOTE_LIST;
        mModeCallBack = new ModeCallback();

        // 初始化模式切换按钮和清单管理器（OMO）
        mNoteModeButton = (Button) findViewById(R.id.btn_note_mode);
        mChecklistModeButton = (Button) findViewById(R.id.btn_checklist_mode);
        mIsChecklistMode = false;
        updateModeButtons();
        mChecklistManager = new ChecklistManager(mContentResolver);

        // 初始化搜索相关控件
        mSearchBar = (LinearLayout) findViewById(R.id.search_bar);
        mSearchEditText = findViewById(R.id.et_search);
        mClearSearchButton = (ImageButton) findViewById(R.id.btn_clear_search);

        // 设置搜索监听器
        initSearchListeners();

        // 标签云功能已移除，相关代码已注释
        // mTagCloudSection = findViewById(R.id.tag_cloud_section);
        // mTagCloudContainer = findViewById(R.id.tag_cloud_container);
        // mAllNotesTag = findViewById(R.id.tag_all_notes);
        // mCurrentFilterTag = null;
        //
        // // 加载标签云
        // loadTagCloud();
    }

    /**
     * 初始化搜索相关监听器
     */
    private void initSearchListeners() {
        // 初始化搜索任务
        mSearchRunnable = new Runnable() {
            @Override
            public void run() {
                // 执行搜索查询：如果已经处于搜索模式，只更新搜索结果，不退出搜索模式
                // 这样可以确保搜索栏在用户输入时保持可见
                if (mIsSearchMode) {
                    startAsyncNotesListQuery();
                } else if (!TextUtils.isEmpty(mSearchQuery)) {
                    // 如果不在搜索模式但有搜索字符串，进入搜索模式
                    setSearchMode(true, mSearchQuery);
                }
            }
        };

        // 搜索输入框文本变化监听器
        mSearchEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本变化前的处理
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本变化时的处理
                mSearchQuery = s.toString();
                Log.d(TAG, "Search text changed: '" + mSearchQuery + "'");
                // 移除之前的搜索任务
                mSearchEditText.removeCallbacks(mSearchRunnable);
                // 延迟执行搜索任务
                Log.d(TAG, "Posting search runnable with delay: " + SEARCH_DEBOUNCE_DELAY + "ms");
                mSearchEditText.postDelayed(mSearchRunnable, SEARCH_DEBOUNCE_DELAY);
            }

            @Override
            public void afterTextChanged(Editable s) {
                // 文本变化后的处理
            }
        });

        // 搜索输入框编辑器动作监听器（处理虚拟键盘上的搜索按钮）
        mSearchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // 检查是否是搜索动作
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 获取搜索查询
                    String query = mSearchEditText.getText().toString().trim();
                    if (!TextUtils.isEmpty(query)) {
                        // 设置搜索模式并执行搜索
                        setSearchMode(true, query);
                        // 保存搜索历史
                        saveSearchHistory(query);
                        // 隐藏软键盘
                        hideSoftInput(mSearchEditText);
                    }
                    return true;
                }
                return false;
            }
        });

        // 清除搜索按钮点击监听器
        mClearSearchButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 清除搜索内容
                mSearchEditText.setText("");
                // 移除未执行的搜索任务
                mSearchEditText.removeCallbacks(mSearchRunnable);
                // 退出搜索模式
                exitSearchMode();
            }
        });
    }

    /**
     * 多选模式回调类 - 处理笔记的多选操作
     * 实现了多选模式下的菜单创建、选择状态变化等功能
     */
    private class ModeCallback implements ListView.MultiChoiceModeListener, OnMenuItemClickListener {
        private DropdownMenu mDropDownMenu;
        private ActionMode mActionMode;
        private MenuItem mMoveMenu;

        /**
         * 创建操作模式时调用
         * 设置多选模式下的菜单和视图
         */
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            getMenuInflater().inflate(R.menu.note_list_options, menu);
            menu.findItem(R.id.delete).setOnMenuItemClickListener(this);
            mMoveMenu = menu.findItem(R.id.move);
            if (mFocusNoteDataItem.getParentId() == Notes.ID_CALL_RECORD_FOLDER
                    || DataUtils.getUserFolderCount(mContentResolver) == 0) {
                mMoveMenu.setVisible(false);
            } else {
                mMoveMenu.setVisible(true);
                mMoveMenu.setOnMenuItemClickListener(this);
            }
            mActionMode = mode;
            mNotesListAdapter.setChoiceMode(true);
            mNotesListView.setLongClickable(false);
            mAddNewNote.setVisibility(View.GONE);

            View customView = LayoutInflater.from(NotesListActivity.this).inflate(
                    R.layout.note_list_dropdown_menu, null);
            mode.setCustomView(customView);
            mDropDownMenu = new DropdownMenu(NotesListActivity.this,
                    (Button) customView.findViewById(R.id.selection_menu),
                    R.menu.note_list_dropdown);
            mDropDownMenu.setOnDropdownMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
                public boolean onMenuItemClick(MenuItem item) {
                    mNotesListAdapter.selectAll(!mNotesListAdapter.isAllSelected());
                    updateMenu();
                    return true;
                }

            });
            return true;
        }

        /**
         * 更新菜单状态
         * 根据选择的笔记数量更新下拉菜单标题和全选状态
         */
        private void updateMenu() {
            int selectedCount = mNotesListAdapter.getSelectedCount();
            // Update dropdown menu
            String format = getResources().getString(R.string.menu_select_title, selectedCount);
            mDropDownMenu.setTitle(format);
            MenuItem item = mDropDownMenu.findItem(R.id.action_select_all);
            if (item != null) {
                if (mNotesListAdapter.isAllSelected()) {
                    item.setChecked(true);
                    item.setTitle(R.string.menu_deselect_all);
                } else {
                    item.setChecked(false);
                    item.setTitle(R.string.menu_select_all);
                }
            }
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            // TODO Auto-generated method stub
            return false;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            // TODO Auto-generated method stub
            return false;
        }

        /**
         * 销毁操作模式时调用
         * 恢复普通模式下的视图状态
         */
        public void onDestroyActionMode(ActionMode mode) {
            mNotesListAdapter.setChoiceMode(false);
            mNotesListView.setLongClickable(true);
            mAddNewNote.setVisibility(View.VISIBLE);
        }

        /**
         * 结束操作模式
         */
        public void finishActionMode() {
            mActionMode.finish();
        }

        /**
         * 当列表项的选择状态改变时调用
         * 更新适配器中的选择状态并刷新菜单
         */
        public void onItemCheckedStateChanged(ActionMode mode, int position, long id,
                                              boolean checked) {
            mNotesListAdapter.setCheckedItem(position, checked);
            updateMenu();
        }

        /**
         * 处理菜单项点击事件
         * 支持删除和移动操作
         */
        public boolean onMenuItemClick(MenuItem item) {
            if (mNotesListAdapter.getSelectedCount() == 0) {
                Toast.makeText(NotesListActivity.this, getString(R.string.menu_select_none),
                        Toast.LENGTH_SHORT).show();
                return true;
            }

            switch (item.getItemId()) {
                case R.id.delete:
                    // 显示删除确认对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(getString(R.string.alert_title_delete));
                    builder.setIcon(android.R.drawable.ic_dialog_alert);
                    builder.setMessage(getString(R.string.alert_message_delete_notes,
                            mNotesListAdapter.getSelectedCount()));
                    builder.setPositiveButton(android.R.string.ok,
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    batchDelete(); // 执行批量删除
                                }
                            });
                    builder.setNegativeButton(android.R.string.cancel, null);
                    builder.show();
                    break;
                case R.id.move:
                    // 查询目标文件夹列表
                    startQueryDestinationFolders();
                    break;
                default:
                    return false;
            }
            return true;
        }
    }

    /**
     * 新建笔记按钮的触摸监听器
     * 处理特殊的触摸事件分发逻辑
     */
    private class NewNoteOnTouchListener implements OnTouchListener {

        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    Display display = getWindowManager().getDefaultDisplay();
                    int screenHeight = display.getHeight();
                    int newNoteViewHeight = mAddNewNote.getHeight();
                    int start = screenHeight - newNoteViewHeight;
                    int eventY = start + (int) event.getY();
                    // 子文件夹状态需减去标题栏高度
                    /**
                     * Minus TitleBar's height
                     */
                    if (mState == ListEditState.SUB_FOLDER) {
                        eventY -= mTitleBar.getHeight();
                        start -= mTitleBar.getHeight();
                    }
                    // HACKME: 点击“新建”按钮透明区时，将事件派发给下方列表。
                    // 透明区近似线性公式 y = -0.12x + 94（px），背景改动需同步更新该公式。
                    /**
                     * HACKME:When click the transparent part of "New Note" button, dispatch
                     * the event to the list view behind this button. The transparent part of
                     * "New Note" button could be expressed by formula y=-0.12x+94（Unit:pixel）
                     * and the line top of the button. The coordinate based on left of the "New
                     * Note" button. The 94 represents maximum height of the transparent part.
                     * Notice that, if the background of the button changes, the formula should
                     * also change. This is very bad, just for the UI designer's strong requirement.
                     */
                    if (event.getY() < (event.getX() * (-0.12) + 94)) {
                        View view = mNotesListView.getChildAt(mNotesListView.getChildCount() - 1
                                - mNotesListView.getFooterViewsCount());
                        if (view != null && view.getBottom() > start
                                && (view.getTop() < (start + 94))) {
                            mOriginY = (int) event.getY();
                            mDispatchY = eventY;
                            event.setLocation(event.getX(), mDispatchY);
                            mDispatch = true;
                            return mNotesListView.dispatchTouchEvent(event);
                        }
                    }
                    break;
                }
                case MotionEvent.ACTION_MOVE: {
                    if (mDispatch) {
                        mDispatchY += (int) event.getY() - mOriginY;
                        event.setLocation(event.getX(), mDispatchY);
                        return mNotesListView.dispatchTouchEvent(event);
                    }
                    break;
                }
                default: {
                    if (mDispatch) {
                        event.setLocation(event.getX(), mDispatchY);
                        mDispatch = false;
                        return mNotesListView.dispatchTouchEvent(event);
                    }
                    break;
                }
            }
            return false;
        }

    };

    /**
     * 开始异步查询笔记列表
     * 根据当前文件夹ID选择不同的查询条件
     */
    private void startAsyncNotesListQuery() {
        String selection;
        String[] selectionArgs;

        // 基础查询条件
        if (mIsSearchMode) {
            // 搜索模式：忽略清单模式，搜索所有笔记和清单
            if (mCurrentFolderId == Notes.ID_ROOT_FOLDER) {
                // 根文件夹下的搜索：显示所有类型的笔记（普通笔记、清单、文件夹、通话记录文件夹）
                selection = "(" + NoteColumns.TYPE + " IN (" + Notes.TYPE_NOTE + ", " + Notes.TYPE_CHECKLIST + ", " + Notes.TYPE_FOLDER + ") AND " + NoteColumns.PARENT_ID + "=?)" +
                        " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)";
            } else {
                // 普通文件夹下的搜索：显示所有类型的笔记（普通笔记和清单）
                selection = NoteColumns.PARENT_ID + "=? AND " + NoteColumns.TYPE + " IN (" + Notes.TYPE_NOTE + ", " + Notes.TYPE_CHECKLIST + ")";
            }
        } else {
            // 非搜索模式：使用原来的逻辑
            if (mCurrentFolderId == Notes.ID_ROOT_FOLDER) {
                if (mIsChecklistMode) {
                    // 根文件夹下的清单模式：只显示清单类型的笔记
                    selection = "(" + NoteColumns.TYPE + "=" + Notes.TYPE_CHECKLIST + " AND " + NoteColumns.PARENT_ID + "=?)" +
                            " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)";
                } else {
                    // 根文件夹下的笔记模式：显示文件夹、普通笔记和非空通话记录文件夹
                    selection = "(" + NoteColumns.TYPE + "<>" + Notes.TYPE_SYSTEM + " AND " + NoteColumns.PARENT_ID + "=?)" +
                            " OR (" + NoteColumns.ID + "=" + Notes.ID_CALL_RECORD_FOLDER + " AND " + NoteColumns.NOTES_COUNT + ">0)";
                }
            } else {
                if (mIsChecklistMode) {
                    // 普通文件夹下的清单模式：只显示清单类型的笔记
                    selection = NoteColumns.PARENT_ID + "=? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_CHECKLIST;
                } else {
                    // 普通文件夹下的笔记模式：只显示普通笔记
                    selection = NoteColumns.PARENT_ID + "=? AND " + NoteColumns.TYPE + "=" + Notes.TYPE_NOTE;
                }
            }
        }

        // 添加搜索过滤条件
        if (mIsSearchMode && !TextUtils.isEmpty(mSearchQuery)) {
            // 搜索过滤需要使用子查询，因为内容存储在data表中
            String searchFilter = " AND " + NoteColumns.ID + " IN (" +
                    "SELECT " + Notes.DataColumns.NOTE_ID +
                    " FROM " + NotesDatabaseHelper.TABLE.DATA +
                    " WHERE (" + Notes.DataColumns.MIME_TYPE + "=?" +
                    " AND " + Notes.DataColumns.CONTENT + " LIKE ?" +
                    ") OR (" + Notes.DataColumns.MIME_TYPE + "=?" +
                    " AND " + Notes.DataColumns.CONTENT + " LIKE ?" +
                    "))";

            // 将整个基础查询条件用括号括起来，确保搜索条件应用到所有笔记
            // 这是修复搜索功能的关键：解决SQL操作符优先级问题
            selection = "(" + selection + ")";
            selection += searchFilter;
        }

        // 添加标签过滤条件
        if (mCurrentFilterTag != null) {
            // 标签过滤需要使用子查询，因为标签存储在data表中
            String tagFilter = " AND " + NoteColumns.ID + " IN (" +
                    "SELECT " + Notes.DataColumns.NOTE_ID +
                    " FROM " + NotesDatabaseHelper.TABLE.DATA +
                    " WHERE " + Notes.DataColumns.MIME_TYPE + "=?" +
                    " AND " + Notes.DataColumns.CONTENT + "=?" +
                    ")";
            selection += tagFilter;
        }

        // 准备选择参数
        ArrayList<String> argsList = new ArrayList<>();
        argsList.add(String.valueOf(mCurrentFolderId));

        // 添加搜索参数
        if (mIsSearchMode && !TextUtils.isEmpty(mSearchQuery)) {
            String searchPattern = "%" + mSearchQuery + "%";
            // 搜索普通文本内容
            argsList.add(Notes.DataConstants.NOTE);
            argsList.add(searchPattern);
            // 搜索标签
            argsList.add(Notes.DataConstants.TAG);
            argsList.add(searchPattern);
        }

        // 添加标签参数
        if (mCurrentFilterTag != null) {
            argsList.add(Notes.DataConstants.TAG);
            argsList.add(mCurrentFilterTag);
        }

        selectionArgs = argsList.toArray(new String[argsList.size()]);

        mBackgroundQueryHandler.startQuery(FOLDER_NOTE_LIST_QUERY_TOKEN, null,
                Notes.CONTENT_NOTE_URI, NoteItemData.PROJECTION, selection, selectionArgs,
                NoteColumns.TYPE + " DESC," + NoteColumns.MODIFIED_DATE + " DESC");
    }

    /**
     * 加载标签云
     */
    private void loadTagCloud() {
        // 清空现有标签（保留"全部笔记"标签）
        while (mTagCloudContainer.getChildCount() > 1) {
            mTagCloudContainer.removeViewAt(1);
        }

        // 查询所有标签，按使用次数排序
        String tagQuery = "SELECT " + Notes.DataColumns.CONTENT +
                " FROM " + NotesDatabaseHelper.TABLE.DATA +
                " WHERE " + Notes.DataColumns.MIME_TYPE + "=?" +
                " GROUP BY " + Notes.DataColumns.CONTENT +
                " ORDER BY COUNT(*) DESC";

        Cursor cursor = mContentResolver.query(
                Notes.CONTENT_DATA_URI,
                new String[]{Notes.DataColumns.CONTENT},
                Notes.DataColumns.MIME_TYPE + "=?",
                new String[]{Notes.DataConstants.TAG},
                Notes.DataColumns.CONTENT + " ASC");

        if (cursor != null) {
            while (cursor.moveToNext()) {
                String tagName = cursor.getString(0);
                if (!TextUtils.isEmpty(tagName)) {
                    // 创建标签按钮
                    Button tagButton = new Button(this);
                    tagButton.setText(tagName);
                    tagButton.setBackgroundResource(R.drawable.bg_btn_set_color);
                    tagButton.setTextColor(Color.WHITE);
                    tagButton.setTextSize(14);
                    tagButton.setSingleLine(true);
                    tagButton.setTag(tagName);
                    // tagButton.setOnClickListener(new OnClickListener() {
                    //     @Override
                    //     public void onClick(View v) {
                    //         onTagClick(v);
                    //     }
                    // });

                    // 设置标准化布局参数
                    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT, 36);
                    params.setMargins(0, 0, 8, 0);
                    params.gravity = Gravity.CENTER_VERTICAL;
                    tagButton.setLayoutParams(params);

                    // 设置标准化内边距
                    tagButton.setPadding(12, 0, 12, 0);

                    // 添加到标签云容器
                    mTagCloudContainer.addView(tagButton);
                }
            }
            cursor.close();
        }
    }


    // 标签云功能已移除，onTagClick方法已删除
    // public void onTagClick(View v) {
    //     if (v.getId() == R.id.tag_all_notes) {
    //         // 显示全部笔记
    //         mCurrentFilterTag = null;
    //         mAllNotesTag.setTextColor(Color.WHITE);
    //         mAllNotesTag.setBackgroundResource(R.drawable.bg_btn_set_color);
    //     } else {
    //         // 显示特定标签的笔记
    //         mCurrentFilterTag = (String) v.getTag();
    //         mAllNotesTag.setTextColor(Color.BLACK);
    //         mAllNotesTag.setBackgroundResource(android.R.drawable.btn_default);
    //     }
    //
    //     // 更新其他标签的样式
    //     for (int i = 1; i < mTagCloudContainer.getChildCount(); i++) {
    //         Button tagButton = (Button) mTagCloudContainer.getChildAt(i);
    //         if (tagButton.getTag().equals(mCurrentFilterTag)) {
    //             tagButton.setTextColor(Color.WHITE);
    //             tagButton.setBackgroundResource(R.drawable.bg_btn_set_color);
    //         } else {
    //             tagButton.setTextColor(Color.BLACK);
    //             tagButton.setBackgroundResource(android.R.drawable.btn_default);
    //         }
    //     }
    //
    //     // 重新查询笔记列表
    //     startAsyncNotesListQuery();
    // }

    /**
     * 后台查询处理器 - 处理异步数据库查询
     */
    private final class BackgroundQueryHandler extends AsyncQueryHandler {
        public BackgroundQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        /**
         * 查询完成时调用
         * 根据不同的查询标记处理查询结果
         */
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            Log.d(TAG, "onQueryComplete called with token: " + token + ", cursor: " + cursor + ", count: " + (cursor != null ? cursor.getCount() : -1));

            switch (token) {
                case FOLDER_NOTE_LIST_QUERY_TOKEN:
                    // 查询笔记列表完成，更新适配器
                    Log.d(TAG, "Updating notes list adapter with cursor, count: " + (cursor != null ? cursor.getCount() : -1));
                    mNotesListAdapter.changeCursor(cursor);
                    break;
                case FOLDER_LIST_QUERY_TOKEN:
                    // 查询文件夹列表完成，显示文件夹菜单
                    if (cursor != null && cursor.getCount() > 0) {
                        showFolderListMenu(cursor);
                    } else {
                        Log.e(TAG, "Query folder failed");
                    }
                    break;
                default:
                    return;
            }
        }
    }

    /**
     * 显示文件夹列表菜单
     * 用于选择移动笔记的目标文件夹
     */
    private void showFolderListMenu(Cursor cursor) {
        AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
        builder.setTitle(R.string.menu_title_select_folder);
        final FoldersListAdapter adapter = new FoldersListAdapter(this, cursor);
        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                DataUtils.batchMoveToFolder(mContentResolver,
                        mNotesListAdapter.getSelectedItemIds(), adapter.getItemId(which));
                Toast.makeText(
                        NotesListActivity.this,
                        getString(R.string.format_move_notes_to_folder,
                                mNotesListAdapter.getSelectedCount(),
                                adapter.getFolderName(NotesListActivity.this, which)),
                        Toast.LENGTH_SHORT).show();
                mModeCallBack.finishActionMode();
            }
        });
        builder.show();
    }

    /**
     * 创建新笔记
     * 跳转到笔记编辑界面
     */
    private void createNewNote() {
        // 弹出对话框询问是否加密
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.encrypt_note_dialog_title);
        builder.setMessage(R.string.encrypt_note_dialog_message);
        builder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户选择加密，弹出密码输入对话框
                showPasswordInputDialog();
            }
        });
        builder.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 用户选择不加密，直接创建便签
                createNoteWithoutEncryption();
            }
        });
        builder.show();
    }

    private void showPasswordInputDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
        final EditText etPassword = (EditText) view.findViewById(R.id.et_foler_name);
        etPassword.setHint(R.string.password_hint);
        etPassword.setInputType(android.text.InputType.TYPE_CLASS_TEXT |
                android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD);
        builder.setTitle(R.string.password_set_dialog_title);
        builder.setView(view);
        builder.setPositiveButton(android.R.string.ok, null);
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 取消，直接创建不加密的便签
                createNoteWithoutEncryption();
            }
        });

        final Dialog dialog = builder.create();
        dialog.show();

        final Button positive = (Button) dialog.findViewById(android.R.id.button1);
        positive.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String password = etPassword.getText().toString();
                if (TextUtils.isEmpty(password)) {
                    Toast.makeText(NotesListActivity.this,
                            R.string.password_empty, Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog.dismiss();
                // 创建加密便签
                createNoteWithEncryption(password);
            }
        });
    }

    private void createNoteWithoutEncryption() {
        Intent intent = new Intent(this, NoteEditActivity.class);
        intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
        intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);

        // 设置笔记类型
        if (mIsChecklistMode) {
            // 清单模式：创建清单类型的笔记
            intent.putExtra(Notes.INTENT_EXTRA_NOTE_TYPE, Notes.TYPE_CHECKLIST);
        } else {
            // 笔记模式：创建普通笔记类型
            intent.putExtra(Notes.INTENT_EXTRA_NOTE_TYPE, Notes.TYPE_NOTE);
        }

        // 如果是清单模式，使用ChecklistManager添加清单模式标记
        if (mIsChecklistMode && mChecklistManager != null) {
            mChecklistManager.addChecklistModeToIntent(intent, true);
        }

        this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
    }

    /**
     * 批量删除笔记
     * 在同步模式下将笔记移动到回收站，非同步模式下直接删除
     */
    private void createNoteWithEncryption(String password) {
        Intent intent = new Intent(this, NoteEditActivity.class);
        intent.setAction(Intent.ACTION_INSERT_OR_EDIT);
        intent.putExtra(Notes.INTENT_EXTRA_FOLDER_ID, mCurrentFolderId);
        intent.putExtra("is_encrypted", true);
        intent.putExtra("password", password);
        this.startActivityForResult(intent, REQUEST_CODE_NEW_NODE);
    }

    private void batchDelete() {
        final NotesListActivity activity = this;
        new AsyncTask<Void, Void, HashSet<AppWidgetAttribute>>() {
            protected HashSet<AppWidgetAttribute> doInBackground(Void... unused) {
                HashSet<AppWidgetAttribute> widgets = mNotesListAdapter.getSelectedWidget();
                if (!isSyncMode()) {
                    // if not synced, delete notes directly
                    if (DataUtils.batchDeleteNotes(mContentResolver, mNotesListAdapter
                            .getSelectedItemIds(), activity)) {
                    } else {
                        Log.e(TAG, "Delete notes error, should not happens");
                    }
                } else {
                    // in sync mode, we'll move the deleted note into the trash
                    // folder
                    if (!DataUtils.batchMoveToFolder(mContentResolver, mNotesListAdapter
                            .getSelectedItemIds(), Notes.ID_TRASH_FOLER)) {
                        Log.e(TAG, "Move notes to trash folder error, should not happens");
                    }
                }
                return widgets;
            }

            @Override
            protected void onPostExecute(HashSet<AppWidgetAttribute> widgets) {
                if (widgets != null) {
                    for (AppWidgetAttribute widget : widgets) {
                        if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                                && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
                            updateWidget(widget.widgetId, widget.widgetType);
                        }
                    }
                }
                mModeCallBack.finishActionMode();
            }
        }.execute();
    }

    /**
     * 删除文件夹
     * 在同步模式下将文件夹移动到回收站，非同步模式下直接删除
     */
    private void deleteFolder(long folderId) {
        if (folderId == Notes.ID_ROOT_FOLDER) {
            Log.e(TAG, "Wrong folder id, should not happen " + folderId);
            return;
        }

        HashSet<Long> ids = new HashSet<Long>();
        ids.add(folderId);
        HashSet<AppWidgetAttribute> widgets = DataUtils.getFolderNoteWidget(mContentResolver,
                folderId);
        if (!isSyncMode()) {
            // if not synced, delete folder directly
            DataUtils.batchDeleteNotes(mContentResolver, ids, this);
        } else {
            // in sync mode, we'll move the deleted folder into the trash folder
            DataUtils.batchMoveToFolder(mContentResolver, ids, Notes.ID_TRASH_FOLER);
        }
        if (widgets != null) {
            for (AppWidgetAttribute widget : widgets) {
                if (widget.widgetId != AppWidgetManager.INVALID_APPWIDGET_ID
                        && widget.widgetType != Notes.TYPE_WIDGET_INVALIDE) {
                    updateWidget(widget.widgetId, widget.widgetType);
                }
            }
        }
    }

    /**
     * 打开笔记
     * 跳转到笔记编辑界面查看/编辑笔记
     */
    private void openNode(NoteItemData data) {
        // 检查是否为加密便签
        // 使用PasswordUtils检查，因为数据库中的值可能更准确
        boolean isEncrypted = net.micode.notes.tool.PasswordUtils.isNoteEncrypted(this, data.getId());
        if (isEncrypted) {
            // 跳转到密码输入界面
            Intent intent = new Intent(this, PasswordInputActivity.class);
            intent.putExtra(PasswordInputActivity.EXTRA_NOTE_ID, data.getId());
            startActivity(intent);
        } else {
            // 普通便签，直接打开
            Intent intent = new Intent(this, NoteEditActivity.class);
            intent.setAction(Intent.ACTION_VIEW);
            intent.putExtra(Intent.EXTRA_UID, data.getId());
            this.startActivityForResult(intent, REQUEST_CODE_OPEN_NODE);
        }
    }

    /**
     * 打开文件夹
     * 更新当前文件夹ID并重新查询笔记列表
     */
    private void openFolder(NoteItemData data) {
        mCurrentFolderId = data.getId();
        startAsyncNotesListQuery();
        if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
            mState = ListEditState.CALL_RECORD_FOLDER;
            mAddNewNote.setVisibility(View.GONE);
        } else {
            mState = ListEditState.SUB_FOLDER;
        }
        if (data.getId() == Notes.ID_CALL_RECORD_FOLDER) {
            mTitleBar.setText(R.string.call_record_folder_name);
        } else {
            mTitleBar.setText(data.getSnippet());
        }
        mTitleBar.setVisibility(View.VISIBLE);
    }

    /**
     * 处理点击事件
     * 当前只处理新建笔记按钮的点击
     */
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_new_note:
                createNewNote();
                break;

            default:
                break;
        }
    }
    /**
     * 显示自定义菜单
     * OMO
     */
    public void showCustomMenu(View view) {
        PopupMenu popupMenu = new PopupMenu(this, view);
        popupMenu.inflate(R.menu.note_list);  // 加载原有菜单资源

        // 设置菜单点击事件
        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // 调用原有的菜单处理逻辑
                return onOptionsItemSelected(item);
            }
        });

        popupMenu.show();
    }

    /**
     * 更新模式按钮样式
     * 根据当前模式更新按钮的背景色和文字颜色
     * OMO
     */
    private void updateModeButtons() {
        if (mIsChecklistMode) {
            // 清单模式下，清单按钮高亮
            mChecklistModeButton.setBackgroundColor(0xFF007AFF);
            mChecklistModeButton.setTextColor(0xFFFFFFFF);
            mNoteModeButton.setBackgroundColor(0xFFFFFFFF);
            mNoteModeButton.setTextColor(0xFF000000);
        } else {
            // 笔记模式下，笔记按钮高亮
            mNoteModeButton.setBackgroundColor(0xFF007AFF);
            mNoteModeButton.setTextColor(0xFFFFFFFF);
            mChecklistModeButton.setBackgroundColor(0xFFFFFFFF);
            mChecklistModeButton.setTextColor(0xFF000000);
        }
    }

    /**
     * 切换到笔记模式
     * @param view 点击的视图
     * OMO
     */
    public void switchToNoteMode(View view) {
        mIsChecklistMode = false;
        updateModeButtons();

        // 更新适配器模式
        if (mNotesListAdapter != null) {
            mNotesListAdapter.setChecklistMode(false);
        }

        // 查询笔记列表
        startAsyncNotesListQuery();
    }

    /**
     * 切换到清单模式
     * 点击时切换到清单模式并显示清单列表
     * @param view 点击的视图
     * OMO
     */
    public void switchToChecklistMode(View view) {
        mIsChecklistMode = true;
        updateModeButtons();

        // 更新适配器模式
        if (mNotesListAdapter != null) {
            mNotesListAdapter.setChecklistMode(true);
        }

        // 查询清单列表
        startAsyncNotesListQuery();
    }

    /**
     * 显示软键盘
     */
    private void showSoftInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
    }

    /**
     * 隐藏软键盘
     */
    private void hideSoftInput(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 显示创建或修改文件夹的对话框
     * @param create 是否为创建文件夹模式
     */
    private void showCreateOrModifyFolderDialog(final boolean create) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
        final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
        showSoftInput();
        if (!create) {
            if (mFocusNoteDataItem != null) {
                etName.setText(mFocusNoteDataItem.getSnippet());
                builder.setTitle(getString(R.string.menu_folder_change_name));
            } else {
                Log.e(TAG, "The long click data item is null");
                return;
            }
        } else {
            etName.setText("");
            builder.setTitle(this.getString(R.string.menu_create_folder));
        }

        builder.setPositiveButton(android.R.string.ok, null);
        builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                hideSoftInput(etName);
            }
        });

        final Dialog dialog = builder.setView(view).show();
        final Button positive = (Button)dialog.findViewById(android.R.id.button1);
        positive.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                hideSoftInput(etName);
                String name = etName.getText().toString();
                if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
                    Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
                            Toast.LENGTH_LONG).show();
                    etName.setSelection(0, etName.length());
                    return;
                }
                if (!create) {
                    if (!TextUtils.isEmpty(name)) {
                        ContentValues values = new ContentValues();
                        values.put(NoteColumns.SNIPPET, name);
                        values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                        values.put(NoteColumns.LOCAL_MODIFIED, 1);
                        mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID
                                + "=?", new String[] {
                                String.valueOf(mFocusNoteDataItem.getId())
                        });
                    }
                } else if (!TextUtils.isEmpty(name)) {
                    ContentValues values = new ContentValues();
                    values.put(NoteColumns.SNIPPET, name);
                    values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                    mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
                }
                dialog.dismiss();
            }
        });

        if (TextUtils.isEmpty(etName.getText())) {
            positive.setEnabled(false);
        }
        /**
         * When the name edit text is null, disable the positive button
         */
        etName.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // TODO Auto-generated method stub

            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (TextUtils.isEmpty(etName.getText())) {
                    positive.setEnabled(false);
                } else {
                    positive.setEnabled(true);
                }
            }

            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });
    }

    /**
     * 处理返回键按下事件
     * 根据当前状态返回到上一级菜单或退出应用
     */
    @Override
    public void onBackPressed() {
        switch (mState) {
            case SUB_FOLDER:
                mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                mState = ListEditState.NOTE_LIST;
                startAsyncNotesListQuery();
                mTitleBar.setVisibility(View.GONE);
                break;
            case CALL_RECORD_FOLDER:
                mCurrentFolderId = Notes.ID_ROOT_FOLDER;
                mState = ListEditState.NOTE_LIST;
                mAddNewNote.setVisibility(View.VISIBLE);
                mTitleBar.setVisibility(View.GONE);
                startAsyncNotesListQuery();
                break;
            case NOTE_LIST:
                super.onBackPressed();
                break;
            default:
                break;
        }
    }

    /**
     * 更新小部件
     * 根据小部件类型发送相应的广播更新
     */
    private void updateWidget(int appWidgetId, int appWidgetType) {
        Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
        if (appWidgetType == Notes.TYPE_WIDGET_2X) {
            intent.setClass(this,NoteWidgetProvider_2x.class);
        } else if (appWidgetType == Notes.TYPE_WIDGET_4X) {
            intent.setClass(this, NoteWidgetProvider_4x.class);
        } else {
            Log.e(TAG, "Unspported widget type");
            return;
        }

        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, new int[] {
                appWidgetId
        });

        sendBroadcast(intent);
        setResult(RESULT_OK, intent);
    }

    /**
     * 文件夹上下文菜单监听器
     * 创建文件夹的上下文菜单
     */
    private final OnCreateContextMenuListener mFolderOnCreateContextMenuListener = new OnCreateContextMenuListener() {
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            if (mFocusNoteDataItem != null) {
                menu.setHeaderTitle(mFocusNoteDataItem.getSnippet());
                menu.add(0, MENU_FOLDER_VIEW, 0, R.string.menu_folder_view);
                menu.add(0, MENU_FOLDER_DELETE, 0, R.string.menu_folder_delete);
                menu.add(0, MENU_FOLDER_CHANGE_NAME, 0, R.string.menu_folder_change_name);
            }
        }
    };

    /**
     * 上下文菜单关闭时调用
     * 清除列表视图的上下文菜单监听器
     */
    @Override
    public void onContextMenuClosed(Menu menu) {
        if (mNotesListView != null) {
            mNotesListView.setOnCreateContextMenuListener(null);
        }
        super.onContextMenuClosed(menu);
    }

    /**
     * 处理上下文菜单项的选择
     * 支持查看、删除、重命名文件夹操作
     */
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (mFocusNoteDataItem == null) {
            Log.e(TAG, "The long click data item is null");
            return false;
        }
        switch (item.getItemId()) {
            case MENU_FOLDER_VIEW:
                openFolder(mFocusNoteDataItem);
                break;
            case MENU_FOLDER_DELETE:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle(getString(R.string.alert_title_delete));
                builder.setIcon(android.R.drawable.ic_dialog_alert);
                builder.setMessage(getString(R.string.alert_message_delete_folder));
                builder.setPositiveButton(android.R.string.ok,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                deleteFolder(mFocusNoteDataItem.getId());
                            }
                        });
                builder.setNegativeButton(android.R.string.cancel, null);
                builder.show();
                break;
            case MENU_FOLDER_CHANGE_NAME:
                showCreateOrModifyFolderDialog(false);
                break;
            default:
                break;
        }

        return true;
    }

    /**
     * 准备选项菜单
     * 根据当前状态加载不同的菜单布局
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.clear();
        if (mState == ListEditState.NOTE_LIST) {
            getMenuInflater().inflate(R.menu.note_list, menu);
            // set sync or sync_cancel
            menu.findItem(R.id.menu_sync).setTitle(
                    GTaskSyncService.isSyncing() ? R.string.menu_sync_cancel : R.string.menu_sync);
        } else if (mState == ListEditState.SUB_FOLDER) {
            getMenuInflater().inflate(R.menu.sub_folder, menu);
        } else if (mState == ListEditState.CALL_RECORD_FOLDER) {
            getMenuInflater().inflate(R.menu.call_record_folder, menu);
        } else {
            Log.e(TAG, "Wrong state:" + mState);
        }
        return true;
    }

    /**
     * 处理选项菜单项的选择
     * 支持新建文件夹、导出文本、同步等操作
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_new_folder: {
                showCreateOrModifyFolderDialog(true);
                break;
            }
            case R.id.menu_export_text: {
                exportNoteToText();
                break;
            }
            case R.id.menu_sync: {
                if (isSyncMode()) {
                    if (TextUtils.equals(item.getTitle(), getString(R.string.menu_sync))) {
                        GTaskSyncService.startSync(this);
                    } else {
                        GTaskSyncService.cancelSync(this);
                    }
                } else {
                    startPreferenceActivity();
                }
                break;
            }
            case R.id.menu_setting: {
                startPreferenceActivity();
                break;
            }
            case R.id.menu_new_note: {
                createNewNote();
                break;
            }
            case R.id.menu_search:
                onSearchRequested();
                break;
            case R.id.menu_trash: {
                Intent intent = new Intent(this, TrashActivity.class);
                startActivity(intent);
                break;
            }
            case R.id.menu_exit_search:
                // 退出搜索模式
                exitSearchMode();
                return true;
            default:
                break;
        }
        return true;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // 处理搜索意图
        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            if (!TextUtils.isEmpty(query)) {
                setSearchMode(true, query);
                // 添加到搜索历史
                saveSearchHistory(query);
                // 显示软键盘
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
                }
            }
        }
    }

    /**
     * 设置搜索模式
     * @param isSearchMode 是否处于搜索模式
     * @param searchQuery 搜索查询字符串
     */
    private void setSearchMode(boolean isSearchMode, String searchQuery) {
        mIsSearchMode = isSearchMode;
        mSearchQuery = searchQuery;

        // 移除任何待执行的搜索任务，避免状态冲突
        mSearchEditText.removeCallbacks(mSearchRunnable);

        startAsyncNotesListQuery();

        // 更新UI，显示或隐藏搜索相关控件
        if (isSearchMode) {
            // 搜索模式下显示搜索栏
            mSearchBar.setVisibility(View.VISIBLE);
            // 设置搜索查询文本
            mSearchEditText.setText(searchQuery);
            // 将光标定位到文本末尾
            mSearchEditText.setSelection(searchQuery.length());
        } else {
            // 退出搜索模式，隐藏搜索栏
            mSearchBar.setVisibility(View.GONE);
        }
    }

    /**
     * 退出搜索模式
     */
    public void exitSearchMode() {
        setSearchMode(false, null);
    }

    @Override
    public boolean onSearchRequested() {
        startSearch(null, false, null /* appData */, false);
        return true;
    }
    /**
     * 处理搜索按钮的点击事件
     * @param view 点击的视图
     * OMO
     */
    public void handleSearchClick(View view) {
        Log.d(TAG, "Search button clicked, showing search bar");
        // 显示搜索栏并聚焦到搜索输入框
        setSearchMode(true, mSearchQuery != null ? mSearchQuery : "");
        mSearchEditText.requestFocus();
        // 显示软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(mSearchEditText, InputMethodManager.SHOW_IMPLICIT);
        }
        Log.d(TAG, "Search bar displayed, search mode: " + mIsSearchMode);
    }

    /**
     * 保存搜索历史
     * @param query 搜索查询字符串
     */
    private void saveSearchHistory(String query) {
        if (TextUtils.isEmpty(query)) {
            return;
        }

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        Set<String> historySet = prefs.getStringSet(PREFERENCE_SEARCH_HISTORY, new HashSet<String>());

        // 创建新的集合以支持修改
        Set<String> newHistorySet = new LinkedHashSet<String>(historySet);

        // 如果已存在，先移除，然后添加到开头
        newHistorySet.remove(query);
        // 创建有序集合以保持插入顺序
        LinkedHashSet<String> orderedHistorySet = new LinkedHashSet<String>();
        orderedHistorySet.add(query);
        orderedHistorySet.addAll(newHistorySet);

        // 限制历史记录数量
        if (orderedHistorySet.size() > MAX_SEARCH_HISTORY) {
            // 移除最旧的记录
            String[] historyArray = orderedHistorySet.toArray(new String[0]);
            for (int i = MAX_SEARCH_HISTORY; i < historyArray.length; i++) {
                orderedHistorySet.remove(historyArray[i]);
            }
        }

        // 保存到偏好设置
        prefs.edit().putStringSet(PREFERENCE_SEARCH_HISTORY, orderedHistorySet).apply();
    }

    /**
     * 获取搜索历史
     * @return 搜索历史集合
     */
    private Set<String> getSearchHistory() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        return prefs.getStringSet(PREFERENCE_SEARCH_HISTORY, new HashSet<String>());
    }

    /**
     * 清除搜索历史
     */
    private void clearSearchHistory() {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.edit().remove(PREFERENCE_SEARCH_HISTORY).apply();
    }

    /**
     * 添加退出搜索模式的菜单项
     * @param menu 菜单对象
     * @return 是否成功创建菜单
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.note_list_options, menu);

        // 在搜索模式下添加退出搜索菜单项
        if (mIsSearchMode) {
            MenuItem exitSearchItem = menu.add(Menu.NONE, R.id.menu_exit_search, Menu.NONE, "退出搜索");
            exitSearchItem.setIcon(android.R.drawable.ic_menu_close_clear_cancel);
            exitSearchItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }

        return true;
    }
    private void exportNoteToText() {
        final BackupUtils backup = BackupUtils.getInstance(NotesListActivity.this);
        new AsyncTask<Void, Void, Integer>() {

            @Override
            protected Integer doInBackground(Void... unused) {
                return backup.exportToText();
            }

            @Override
            protected void onPostExecute(Integer result) {
                if (result == BackupUtils.STATE_SD_CARD_UNMOUONTED) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(NotesListActivity.this
                            .getString(R.string.failed_sdcard_export));
                    builder.setMessage(NotesListActivity.this
                            .getString(R.string.error_sdcard_unmounted));
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                } else if (result == BackupUtils.STATE_SUCCESS) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(NotesListActivity.this
                            .getString(R.string.success_sdcard_export));
                    builder.setMessage(NotesListActivity.this.getString(
                            R.string.format_exported_file_location, backup
                                    .getExportedTextFileName(), backup.getExportedTextFileDir()));
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                } else if (result == BackupUtils.STATE_SYSTEM_ERROR) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(NotesListActivity.this);
                    builder.setTitle(NotesListActivity.this
                            .getString(R.string.failed_sdcard_export));
                    builder.setMessage(NotesListActivity.this
                            .getString(R.string.error_sdcard_export));
                    builder.setPositiveButton(android.R.string.ok, null);
                    builder.show();
                }
            }

        }.execute();
    }

    private boolean isSyncMode() {
        return NotesPreferenceActivity.getSyncAccountName(this).trim().length() > 0;
    }

    private void startPreferenceActivity() {
        Activity from = getParent() != null ? getParent() : this;
        Intent intent = new Intent(from, NotesPreferenceActivity.class);
        from.startActivityIfNeeded(intent, -1);
    }

    private class OnListItemClickListener implements OnItemClickListener {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (view instanceof NotesListItem) {
                NoteItemData item = ((NotesListItem) view).getItemData();
                if (mNotesListAdapter.isInChoiceMode()) {
                    if (item.getType() == Notes.TYPE_NOTE || item.getType() == Notes.TYPE_CHECKLIST) {
                        position = position - mNotesListView.getHeaderViewsCount();
                        mModeCallBack.onItemCheckedStateChanged(null, position, id,
                                !mNotesListAdapter.isSelectedItem(position));
                    }
                    return;
                }

                switch (mState) {
                    case NOTE_LIST:
                        if (item.getType() == Notes.TYPE_FOLDER
                                || item.getType() == Notes.TYPE_SYSTEM) {
                            openFolder(item);
                        } else if (item.getType() == Notes.TYPE_NOTE || item.getType() == Notes.TYPE_CHECKLIST) {
                            openNode(item);
                        } else {
                            Log.e(TAG, "Wrong note type in NOTE_LIST: " + item.getType());
                        }
                        break;
                    case SUB_FOLDER:
                    case CALL_RECORD_FOLDER:
                        if (item.getType() == Notes.TYPE_NOTE || item.getType() == Notes.TYPE_CHECKLIST) {
                            openNode(item);
                        } else {
                            Log.e(TAG, "Wrong note type in SUB_FOLDER: " + item.getType());
                        }
                        break;
                    default:
                        break;
                }
            }
        }

    }

    private void startQueryDestinationFolders() {
        String selection = NoteColumns.TYPE + "=? AND " + NoteColumns.PARENT_ID + "<>? AND " + NoteColumns.ID + "<>?";
        selection = (mState == ListEditState.NOTE_LIST) ? selection:
                "(" + selection + ") OR (" + NoteColumns.ID + "=" + Notes.ID_ROOT_FOLDER + ")";

        mBackgroundQueryHandler.startQuery(FOLDER_LIST_QUERY_TOKEN,
                null,
                Notes.CONTENT_NOTE_URI,
                FoldersListAdapter.PROJECTION,
                selection,
                new String[] {
                        String.valueOf(Notes.TYPE_FOLDER),
                        String.valueOf(Notes.ID_TRASH_FOLER),
                        String.valueOf(mCurrentFolderId)
                },
                NoteColumns.MODIFIED_DATE + " DESC");
    }

    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        if (view instanceof NotesListItem) {
            mFocusNoteDataItem = ((NotesListItem) view).getItemData();
            if ((mFocusNoteDataItem.getType() == Notes.TYPE_NOTE || mFocusNoteDataItem.getType() == Notes.TYPE_CHECKLIST) && !mNotesListAdapter.isInChoiceMode()) {
                if (mNotesListView.startActionMode(mModeCallBack) != null) {
                    mModeCallBack.onItemCheckedStateChanged(null, position, id, true);
                    mNotesListView.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS);
                } else {
                    Log.e(TAG, "startActionMode fails");
                }
            } else if (mFocusNoteDataItem.getType() == Notes.TYPE_FOLDER) {
                mNotesListView.setOnCreateContextMenuListener(mFolderOnCreateContextMenuListener);
            }
        }
        return false;
    }
}
