wjc
2025-04-28 1a5dbd95a4b61c3c94555bc799a1821aa07930e7
app/src/main/java/com/hdl/photovoltaic/ui/powerstation/HouseSearchActivity.java
@@ -1,20 +1,512 @@
package com.hdl.photovoltaic.ui.powerstation;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hdl.linkpm.sdk.core.exception.HDLException;
import com.hdl.photovoltaic.R;
import com.hdl.photovoltaic.base.CustomBaseActivity;
import com.hdl.photovoltaic.databinding.ActivityHouseSearchBinding;
import com.hdl.photovoltaic.enums.ShowErrorMode;
import com.hdl.photovoltaic.enums.SortType;
import com.hdl.photovoltaic.listener.CloudCallBeak;
import com.hdl.photovoltaic.other.HdlCommonLogic;
import com.hdl.photovoltaic.other.HdlFileLogic;
import com.hdl.photovoltaic.other.HdlLogLogic;
import com.hdl.photovoltaic.other.HdlResidenceLogic;
import com.hdl.photovoltaic.other.HdlThreadLogic;
import com.hdl.photovoltaic.other.HdlUniLogic;
import com.hdl.photovoltaic.ui.adapter.SearchHistoryAdapter;
import com.hdl.photovoltaic.ui.adapter.SearchHouseAdapter;
import com.hdl.photovoltaic.ui.bean.HouseIdBean;
import com.hdl.photovoltaic.uni.HDLUniMP;
import com.hdl.photovoltaic.utils.KeyboardStateObserverUtils;
import com.hdl.photovoltaic.widget.refreshlayout.BGARefreshLayout;
import com.hdl.photovoltaic.widget.refreshlayout.HDLRefreshViewHolder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
 * 电站搜索界面
 */
public class HouseSearchActivity extends CustomBaseActivity {
    private Handler handler;
    private Runnable delayedRunnable;
    private ActivityHouseSearchBinding viewBinding;
    SearchHistoryAdapter searchHistoryAdapter;
    SearchHouseAdapter searchHouseAdapter;
    private List<HouseIdBean> houseListBeanIDList = new ArrayList<>();
    private int currentHouseListPage = 0; // 当前电站列表页码
    private int currentHouseListTotal = 0; // 电站列表总页码
    private boolean isHouseLoadingMore = false; // 标记电站列表正在加载更多数据
    private String currSearchText;
    List<String> searchHistoryTitleList = new ArrayList<>();
    @Override
    public Object getContentView() {
        return null;
        viewBinding = ActivityHouseSearchBinding.inflate(getLayoutInflater());
        return viewBinding.getRoot();
    }
    @Override
    public void onBindView(Bundle savedInstanceState) {
        setStatusBarTranslucent();
        getWindow().setNavigationBarColor(getColor(R.color.text_FF000000));
        //历史记录文件夹创建
        HdlFileLogic.getInstance().createFileDir(HdlFileLogic.getInstance().getCurrentUserRootPath());
        //初始化数据
        initData();
        //初始化
        initView();
        //初始化界面监听器
        initEvent();
    }
    private void initData() {
        try {
            String json = HdlFileLogic.getInstance().readFile(getHistoryFileNamePath());
            if (TextUtils.isEmpty(json)) {
                return;
            }
            searchHistoryTitleList = new Gson().fromJson(json, new TypeToken<List<String>>() {
            }.getType());
        } catch (Exception ignored) {
        }
    }
    /**
     * 下拉刷新的逻辑
     */
    protected void pullToRefresh() {
        viewBinding.listSrl.setDelegate(new BGARefreshLayout.BGARefreshLayoutDelegate() {
            @Override
            public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
                handler = new Handler(Looper.getMainLooper());
                delayedRunnable = new Runnable() {
                    @Override
                    public void run() {
                        viewBinding.listSrl.endRefreshing();
                        loadNextPageHouseList(false, 1, true);
                    }
                };
                // 延迟 5 秒执行
                handler.postDelayed(delayedRunnable, 1000);
            }
            @Override
            public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
                handler = new Handler(Looper.getMainLooper());
                delayedRunnable = new Runnable() {
                    @Override
                    public void run() {
                        viewBinding.listSrl.endLoadingMore();
                        //加载最新数据完成
                        if (!isHouseLoadingMore) {
                            // 滑动到了底部,执行相应的操作
                            loadNextPageHouseList(false, ++currentHouseListPage, false);
                        }
                    }
                };
                // 延迟 5 秒执行
                handler.postDelayed(delayedRunnable, 10);
                return true;
            }
        });
        HDLRefreshViewHolder hdlRefreshViewHolder = new HDLRefreshViewHolder(_mActivity, true);
        hdlRefreshViewHolder.setPullDownImageResource(R.mipmap.loading_44);
        hdlRefreshViewHolder.setChangeToReleaseRefreshAnimResId(R.drawable.loading_refresh);
        hdlRefreshViewHolder.setRefreshingAnimResId(R.drawable.loading_refresh_end);
        viewBinding.listSrl.setRefreshViewHolder(hdlRefreshViewHolder);
    }
    private void initEvent() {
        //后退
        viewBinding.backRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewBinding.powerStationSearchEt.addTextChangedListener(textWatcher);
        //搜索
        viewBinding.powerStationSearchTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //搜索关键字
                currSearchText = viewBinding.powerStationSearchEt.getText().toString().replace(" ", "");
                if (TextUtils.isEmpty(currSearchText)) {
                    HdlThreadLogic.toast(_mActivity, R.string.search_content_null);
                    return;
                }
                viewBinding.historyListParent.setVisibility(View.GONE);
                viewBinding.listParent.setVisibility(View.VISIBLE);
                viewBinding.powerStationSearchEt.clearFocus();
                hideSoftInputFromWindow();
                addSearchTextToList();
                loadNextPageHouseList(true, 1, true);
            }
        });
        //清除
        viewBinding.powerStationClearIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                currSearchText = "";
                viewBinding.powerStationSearchEt.setText("");
                viewBinding.historyListParent.setVisibility(View.VISIBLE);
                viewBinding.listParent.setVisibility(View.GONE);
                viewBinding.deviceNullDataIc.getRoot().setVisibility(View.GONE);
                searchHistoryAdapter.setList(searchHistoryTitleList);
                viewBinding.powerStationSearchEt.requestFocus();
                showSoftInput();
                clearData();
            }
        });
        //删除
        viewBinding.powerStationDelIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewBinding.powerStationSearchEt.clearFocus();
                hideSoftInputFromWindow();
                searchHistoryTitleList = new ArrayList<>();
                searchHistoryAdapter.setList(searchHistoryTitleList);
                viewBinding.deviceNullDataIc.getRoot().setVisibility(View.GONE);
                HdlFileLogic.getInstance().deleteFile(getHistoryFileNamePath());
            }
        });
        //历史记录点击事件
        searchHistoryAdapter.setOnclickListener(new SearchHistoryAdapter.OnClickListener() {
            @Override
            public void onClick(int position, String title) {
                viewBinding.powerStationSearchEt.setText(title);
                //搜索关键字
                currSearchText = viewBinding.powerStationSearchEt.getText().toString().replace(" ", "");
                if (TextUtils.isEmpty(currSearchText)) {
                    HdlThreadLogic.toast(_mActivity, R.string.search_content_null);
                    return;
                }
                viewBinding.powerStationSearchEt.clearFocus();
                hideSoftInputFromWindow();
                viewBinding.historyListParent.setVisibility(View.GONE);
                viewBinding.listParent.setVisibility(View.VISIBLE);
                addSearchTextToList();
                loadNextPageHouseList(true, 1, true);
            }
        });
        //电站点击是事件
        searchHouseAdapter.setOnclickListener(new SearchHouseAdapter.OnClickListener() {
            @Override
            public void onClick(int position, HouseIdBean houseIdBean) {
                //点击住宅详情
                HdlLogLogic.print("点击住宅详情---" + new Gson().toJson(houseIdBean), false);
                HdlResidenceLogic.getInstance().switchHouse(houseIdBean,true);
                String path = HDLUniMP.UNI_EVENT_OPEN_HOME_DETAILS + "?homeId=" + houseIdBean.getHomeId() + "&homeName=" + houseIdBean.getHomeName() + "&powerStationStatus=" + houseIdBean.getPowerStationStatus();
                HdlUniLogic.getInstance().openUniMP(path, null);
            }
        });
    }
    /**
     * 显示软键盘
     */
    public void showSoftInput() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.showSoftInput(viewBinding.powerStationSearchEt, 0);
    }
    /**
     * 隐藏软键盘
     */
    public void hideSoftInputFromWindow() {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(viewBinding.getRoot().getWindowToken(), 0);
    }
    private void initView() {
        viewBinding.historyListParent.setVisibility(View.VISIBLE);
        viewBinding.listParent.setVisibility(View.GONE);
        viewBinding.powerStationClearIv.setVisibility(View.GONE);
        //初始化历史记录适配器
        searchHistoryAdapter = new SearchHistoryAdapter(_mActivity);
        viewBinding.historyListRcv.setLayoutManager(new LinearLayoutManager(_mActivity));
        viewBinding.historyListRcv.setAdapter(searchHistoryAdapter);
        searchHistoryAdapter.setList(searchHistoryTitleList);
        //初始化电站适配器
        searchHouseAdapter = new SearchHouseAdapter(_mActivity);
        viewBinding.listRcv.setLayoutManager(new LinearLayoutManager(_mActivity));
        viewBinding.listRcv.setAdapter(searchHouseAdapter);
        viewBinding.powerStationSearchEt.post(new Runnable() {
            @Override
            public void run() {
                viewBinding.powerStationSearchEt.requestFocus();
            }
        });
        pullToRefresh();
        //在界面中使用
        KeyboardStateObserverUtils.getKeyboardStateObserver(_mActivity).setKeyboardVisibilityListener(new KeyboardStateObserverUtils.OnKeyboardVisibilityListener() {
            @Override
            public void onKeyboardShow(int h) {
                //Toast.makeText(MainActivity.this,"键盘弹出",Toast.LENGTH_SHORT).show();
//                viewBinding.powerStationSearchEt.requestFocus();
            }
            @Override
            public void onKeyboardHide(int h) {
                viewBinding.powerStationSearchEt.clearFocus();
            }
        });
    }
    /**
     * 输入电站名称进行过滤
     */
    private final TextWatcher textWatcher = 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) {
        }
        @Override
        public void afterTextChanged(Editable s) {
            String et = viewBinding.powerStationSearchEt.getText().toString().replace(" ", "");
            if (TextUtils.isEmpty(et)) {
                viewBinding.powerStationClearIv.setVisibility(View.GONE);
            } else {
                viewBinding.powerStationClearIv.setVisibility(View.VISIBLE);
            }
            viewBinding.powerStationSearchEt.setSelection(viewBinding.powerStationSearchEt.length());
        }
    };
    /**
     * 物理按键返回事件
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }
    @Override
    protected void onDestroy() {
        viewBinding.powerStationSearchEt.removeTextChangedListener(textWatcher);
        if (searchHistoryTitleList.size() > 0) {
            HdlFileLogic.getInstance().deleteFile(getHistoryFileNamePath());
            HdlFileLogic.getInstance().appendFile(getHistoryFileNamePath(), new Gson().toJson(searchHistoryTitleList));
        }
        if (handler != null && delayedRunnable != null) {
            handler.removeCallbacks(delayedRunnable);
        }
        super.onDestroy();
    }
    /**
     * 刷新UI(电站)
     *
     * @param isRefreshing 表示是下拉刷新的
     */
    private void loadNextPageHouseList(boolean isRefreshing, long pageNo, boolean isClear) {
        //搜索关键字
        if (TextUtils.isEmpty(currSearchText)) {
            return;
        }
        if (isClear) {
            clearData();
        }
        //第一页读取数据强制读取
        if (pageNo > 1 && currentHouseListPage > currentHouseListTotal) {
            --currentHouseListPage;
            //当前页不能大于总页数
            return;
        }
        isHouseLoadingMore = true;//标记读取状态
        if (isRefreshing) {
            showLoading();
        }
        //获取住宅(电站)ID列表
        HdlResidenceLogic.getInstance().getResidenceIdList(SortType.homeName, currSearchText,
                "", "", "", "",
                pageNo, 20, new CloudCallBeak<HdlResidenceLogic.HouseBeanClass>() {
                    @Override
                    public void onSuccess(HdlResidenceLogic.HouseBeanClass houseBeanClass) {
                        HdlThreadLogic.runMainThread(new Runnable() {
                            @Override
                            public void run() {
                                if (isRefreshing) {
                                    hideLoading();
                                }
                                isHouseLoadingMore = false;
                                if (houseBeanClass != null) {
                                    currentHouseListTotal = (int) houseBeanClass.getTotalPage();
                                    currentHouseListPage = (int) houseBeanClass.getPageNo();
                                    //更新缓存
                                    setHouseIdList(houseBeanClass.getList());
                                    if (searchHouseAdapter != null) {
                                        //更新UI
                                        searchHouseAdapter.setList(houseListBeanIDList);
                                    }
                                    nullDataUpdateUi();
                                }
                            }
                        }, _mActivity, ShowErrorMode.YES);
                    }
                    @Override
                    public void onFailure(HDLException e) {
                        HdlThreadLogic.runMainThread(new Runnable() {
                            @Override
                            public void run() {
                                if (currentHouseListPage > 1) {
                                    --currentHouseListPage;
                                }
                                isHouseLoadingMore = false;
                                if (isRefreshing) {
                                    hideLoading();
                                }
                            }
                        }, _mActivity, ShowErrorMode.YES);
                    }
                });
    }
    private void clearData() {
        if (houseListBeanIDList != null && houseListBeanIDList.size() > 0) {
            houseListBeanIDList.clear();
        }
    }
    public void setHouseIdList(List<HouseIdBean> list) {
        if (list == null || list.size() == 0) {
            return;
        }
        if (this.houseListBeanIDList.size() == 0) {
            this.houseListBeanIDList.addAll(list);
            return;
        }
        for (int i = 0; i < list.size(); i++) {
            this.setSingleHouseId(list.get(i));
        }
    }
    /**
     * 添加电站Id到列表里面
     *
     * @param houseIdBean -电站Id对象
     */
    public void setSingleHouseId(HouseIdBean houseIdBean) {
        try {
            if (houseIdBean == null) {
                return;
            }
            boolean if_boolean = false;
            for (int i = 0; i < houseListBeanIDList.size(); i++) {
                if (houseListBeanIDList.get(i).getHomeId().equals(houseIdBean.getHomeId())) {
                    //存在替换
                    houseListBeanIDList.remove(i);
                    houseListBeanIDList.add(i, houseIdBean);
                    if_boolean = true;
                    break;
                }
            }
            if (!if_boolean) {
                //没有添加
                this.houseListBeanIDList.add(houseIdBean);
            }
        } catch (Exception e) {
            String mes = e.getMessage();
            HdlLogLogic.print("---" + mes);
        }
    }
    /**
     * 添加历史记录
     */
    private void addSearchTextToList() {
        for (int i = 0; i < searchHistoryTitleList.size(); i++) {
            if (searchHistoryTitleList.get(i).equals(currSearchText)) {
                searchHistoryTitleList.remove(searchHistoryTitleList.get(i));
            }
        }
        int maxValue = 10;
        searchHistoryTitleList.add(0, currSearchText);
        if (searchHistoryTitleList.size() > maxValue) {
            //历史记录不能超出10
            searchHistoryTitleList.remove(searchHistoryTitleList.get(maxValue));
        }
    }
    /**
     * 没有电站列表的样式
     */
    private void nullDataUpdateUi() {
        boolean is_data = houseListBeanIDList != null && houseListBeanIDList.size() > 0;
        HdlCommonLogic.getInstance().nullDataUpdateUi(_mActivity, viewBinding.deviceNullDataIc.getRoot(), viewBinding.deviceNullDataIc.nullDataGifAnimationIv, viewBinding.deviceNullDataIc.nullDataTv, getString(R.string.my_power_station_data_null), is_data);
    }
    /**
     * 获取【搜索历史记录文件】全路径
     */
    public String getHistoryFileNamePath() {
        return HdlFileLogic.getInstance().getCurrentUserRootPath() + "/house_history.txt";
    }
}