package cc.winboll.studio.contacts.fragments;


/**
 * @Author ZhanGSKen&豆包大模型<zhangsken@qq.com>
 * @Date 2025/08/30 14:32
 * @Describe 联系人视图
 */
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import cc.winboll.studio.contacts.R;
import cc.winboll.studio.contacts.adapters.ContactAdapter;
import cc.winboll.studio.contacts.beans.ContactModel;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.utils.ToastUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ContactsFragment extends Fragment {

    public static final String TAG = "ContactsFragment";
    private static final String ARG_PAGE = "ARG_PAGE";
    private static final int REQUEST_READ_CONTACTS = 1;

    private int mPage;
    private RecyclerView recyclerView;
    private ContactAdapter contactAdapter;
    private EditText searchEditText;
    private Button btnDial;
    private boolean isViewInitialized = false; // 标记视图是否已初始化

    // 静态缓存：全局复用联系人数据
    private static List<ContactModel> sCachedOriginalList = new ArrayList<ContactModel>();
    private static List<ContactModel> sCachedFilteredList = new ArrayList<ContactModel>();

    // 当前页面数据容器
    private List<ContactModel> contactList = new ArrayList<ContactModel>();
    private List<ContactModel> originalContactList = new ArrayList<ContactModel>();

    // 异步工具
    private final ExecutorService executor = Executors.newSingleThreadExecutor();
    private final Handler mainHandler = new Handler(Looper.getMainLooper());
    private boolean isDataLoaded = false;


    public static ContactsFragment newInstance(int page) {
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, page);
        ContactsFragment fragment = new ContactsFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mPage = getArguments().getInt(ARG_PAGE);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局（已移除进度条相关代码）
        View view = inflater.inflate(R.layout.fragment_contacts, container, false);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 初始化RecyclerView
        recyclerView = (RecyclerView) view.findViewById(R.id.contacts_recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        contactList = new ArrayList<ContactModel>();
        contactAdapter = new ContactAdapter(getActivity(), contactList);
        recyclerView.setAdapter(contactAdapter);
        // 初始隐藏列表，数据加载后显示
        recyclerView.setVisibility(View.GONE);

        // 绑定搜索框和拨号按钮
        searchEditText = (EditText) view.findViewById(R.id.search_edit_text);
        btnDial = (Button) view.findViewById(R.id.btn_dial);
        // 初始隐藏搜索相关控件，延迟到首次可见时显示
        searchEditText.setVisibility(View.GONE);
        btnDial.setVisibility(View.GONE);
    }

    // 首次可见时初始化资源
    @Override
    public void onResume() {
        super.onResume();
        if (!isViewInitialized) {
            initSearchAndDial(); // 初始化搜索和拨号功能
            checkContactPermission(); // 检查权限并加载数据
            isViewInitialized = true;
        }
    }

    // 初始化搜索框和拨号按钮
    private void initSearchAndDial() {
        // 显示搜索相关控件
        searchEditText.setVisibility(View.VISIBLE);
        btnDial.setVisibility(View.VISIBLE);

        // 搜索框防抖监听
        searchEditText.addTextChangedListener(new DebounceTextWatcher(300) {
				@Override
				public void onDebounceTextChanged(String query) {
					filterContacts(query);
				}
			});

        // 拨号按钮点击事件
        btnDial.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					String phoneNumber = searchEditText.getText().toString().replaceAll("\\s", "");
					if (phoneNumber.isEmpty()) {
						ToastUtils.show("请输入号码");
						return;
					}
					Intent intent = new Intent(Intent.ACTION_CALL);
					intent.setData(android.net.Uri.parse("tel:" + phoneNumber));
					intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					startActivity(intent);
				}
			});
    }

    // 权限检查
    private void checkContactPermission() {
        if (ActivityCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(requireActivity(), new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_READ_CONTACTS);
        } else {
            loadContacts();
        }
    }

    // 加载联系人（延迟到首次可见时）
    private void loadContacts() {
        // 若有缓存，直接复用
        if (!sCachedOriginalList.isEmpty() && !sCachedFilteredList.isEmpty()) {
            originalContactList.clear();
            originalContactList.addAll(sCachedOriginalList);
            contactList.clear();
            contactList.addAll(sCachedFilteredList);
            contactAdapter.notifyDataSetChanged();
            recyclerView.setVisibility(View.VISIBLE); // 显示列表
            isDataLoaded = true;
            return;
        }

        // 无缓存时异步加载
        if (!isDataLoaded) {
            recyclerView.setVisibility(View.GONE); // 加载中隐藏列表

            executor.execute(new Runnable() {
					@Override
					public void run() {
						// 子线程读取联系人
						final List<ContactModel> tempList = readContactsInBackground();

						// 主线程更新UI
						mainHandler.post(new Runnable() {
								@Override
								public void run() {
									// 更新缓存
									sCachedOriginalList.clear();
									sCachedOriginalList.addAll(tempList);
									sCachedFilteredList.clear();
									sCachedFilteredList.addAll(tempList);

									// 更新当前列表
									originalContactList.clear();
									originalContactList.addAll(sCachedOriginalList);
									contactList.clear();
									contactList.addAll(sCachedFilteredList);
									contactAdapter.notifyDataSetChanged();
									LogUtils.d(TAG, String.format("联系人加载完成，共%d条数据", contactList.size()));

									// 数据加载后显示列表
									recyclerView.setVisibility(View.VISIBLE);
									isDataLoaded = true;
								}
							});
					}
				});
        }
    }

    // 子线程读取联系人
    private List<ContactModel> readContactsInBackground() {
        List<ContactModel> tempList = new ArrayList<ContactModel>();
        Cursor cursor = null;
        try {
            // 查询联系人姓名和号码
            cursor = requireContext().getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                new String[]{
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Phone.NUMBER
                },
                null,
                null,
                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"
            );

            if (cursor != null && cursor.moveToFirst()) {
                int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
                int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);

                do {
                    String name = cursor.getString(nameIndex);
                    String number = cursor.getString(numberIndex).replaceAll("\\s", ""); // 去除空格
                    tempList.add(new ContactModel(name, number));
                } while (cursor.moveToNext());
            }
        } catch (Exception e) {
            LogUtils.d(TAG, "读取联系人失败：" + e);
        } finally {
            if (cursor != null) {
                cursor.close(); // 关闭游标，避免内存泄漏
            }
        }
        return tempList;
    }

    // 过滤联系人
    private void filterContacts(String query) {
        contactList.clear();
        if (query.isEmpty()) {
            contactList.addAll(originalContactList);
            sCachedFilteredList.clear();
            sCachedFilteredList.addAll(originalContactList);
        } else {
            String lowerQuery = query.toLowerCase();
            for (ContactModel contact : originalContactList) {
                // 匹配姓名、全拼、简拼、号码
                boolean matchName = contact.getName().toLowerCase().contains(lowerQuery);
                boolean matchPinyin = contact.getPinyin().toLowerCase().contains(lowerQuery);
                boolean matchFirstLetter = contact.getPinyinFirstLetter().toLowerCase().contains(lowerQuery);
                boolean matchNumber = contact.getNumber().contains(lowerQuery);

                if (matchName || matchPinyin || matchFirstLetter || matchNumber) {
                    contactList.add(contact);
                }
            }
            sCachedFilteredList.clear();
            sCachedFilteredList.addAll(contactList);
        }
        contactAdapter.notifyDataSetChanged();
        // 过滤后确保列表可见
        recyclerView.setVisibility(View.VISIBLE);
    }

    // 权限回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_READ_CONTACTS) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                loadContacts(); // 授权后加载联系人
            } else {
                ToastUtils.show("请授予联系人权限以查看联系人列表");
                recyclerView.setVisibility(View.VISIBLE); // 显示空列表
            }
        }
    }

    // 防抖TextWatcher（Java 7实现）
    public abstract static class DebounceTextWatcher implements TextWatcher {
        private final long debounceDelay;
        private Handler handler = new Handler(Looper.getMainLooper());
        private Runnable pendingRunnable;

        public DebounceTextWatcher(long debounceDelay) {
            this.debounceDelay = debounceDelay;
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // 无需处理
        }

        @Override
        public void onTextChanged(final CharSequence s, int start, int before, int count) {
            // 移除之前的延迟任务
            if (pendingRunnable != null) {
                handler.removeCallbacks(pendingRunnable);
            }
            // 延迟执行过滤
            pendingRunnable = new Runnable() {
                @Override
                public void run() {
                    onDebounceTextChanged(s.toString());
                }
            };
            handler.postDelayed(pendingRunnable, debounceDelay);
        }

        @Override
        public void afterTextChanged(Editable s) {
            // 无需处理
        }

        // 抽象方法：防抖后的回调
        public abstract void onDebounceTextChanged(String query);
    }

    // 资源释放
    @Override
    public void onDestroy() {
        super.onDestroy();
        executor.shutdown(); // 关闭线程池
        mainHandler.removeCallbacksAndMessages(null); // 清除未执行任务
    }

    // Fragment隐藏/显示时的处理
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && isDataLoaded) {
            // 复用缓存数据并显示列表
            contactList.clear();
            contactList.addAll(sCachedFilteredList);
            contactAdapter.notifyDataSetChanged();
            recyclerView.setVisibility(View.VISIBLE);
        }
    }
}

