package com.sheep.gamegroup.view.activity;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.AppCompatAutoCompleteTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.TextView;

import com.kfzs.appstore.utils.adapter.recyclerview.RecyclerViewAdapter;
import com.kfzs.appstore.utils.adapter.recyclerview.ViewHolder;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.absBase.BaseContainerActivity;
import com.sheep.gamegroup.absBase.IHomePageSearch;
import com.sheep.gamegroup.absBase.ISearch;
import com.sheep.gamegroup.absBase.ISearchRecord;
import com.sheep.gamegroup.greendao.DDProviderHelper;
import com.sheep.gamegroup.greendao.download.SearchRecord;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.TitleInfoList;
import com.sheep.gamegroup.model.entity.TopSearchStatistics;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.ApiUtil;
import com.sheep.gamegroup.util.DataUtil;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdpTitleInfoList;
import com.sheep.gamegroup.view.fragment.FgtSearchApp;
import com.sheep.gamegroup.view.fragment.FgtSearchAppOrTask;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;
import com.umeng.socialize.utils.Log;

import org.afinal.simplecache.ApiKey;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by realicing on 2018/9/13.
 * realicing@sina.com
 */
public class ActSearchAppOrTask extends BaseActivity {
    @BindView(R.id.search_app_list)
    RecyclerView recyclerView;
    @BindView(R.id.frame_container)
    View frame_container;

    FgtSearchAppOrTask fgtSearchAppOrTask;

    @Override
    protected int getLayoutId() {
        return R.layout.act_search_app_or_task;
    }

    @Override
    public void initView() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        Fragment fragment = getSupportFragmentManager().findFragmentByTag("tag");
        if (fragment == null) {
            fragment = new FgtSearchAppOrTask();
            transaction.add(R.id.frame_container, fragment, "tag");
            transaction.commitAllowingStateLoss();
        } else {
            transaction.replace(R.id.frame_container, fragment);
            transaction.commitAllowingStateLoss();
        }
        if (fgtSearchAppOrTask == null && fragment instanceof FgtSearchAppOrTask)
            fgtSearchAppOrTask = (FgtSearchAppOrTask) fragment;
    }

    private List<TitleInfoList> titleInfoListList = new ArrayList<>();

    @Override
    public void initListener() {
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitleFinish(this)
                .setSearchBox(this, "搜索任务名称/游戏名称",
                        (v, actionId, event) -> {
                            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                                toSearchApp();
                            }
                            return false;
                        },
                        (text) -> {
                            frame_container.removeCallbacks(autoSearchRunnable);
                            if (text.isEmpty() && !isTitleInfoListEmpty()) {//输入框内容为空且有搜索记录时显示搜索记录
                                recyclerView.setVisibility(View.VISIBLE);
                                frame_container.setVisibility(View.INVISIBLE);
                            } else {
                                frame_container.postDelayed(autoSearchRunnable, 1000L);//1秒后自动搜索
                            }
                        })
                .setRightBtn(this, "搜索", 0,
                        v -> toSearchApp());

        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        AdpTitleInfoList adpTitleInfoList = new AdpTitleInfoList(titleInfoListList);
        adpTitleInfoList.bindToRecyclerView(recyclerView);
    }

    private Runnable autoSearchRunnable = new Runnable() {
        @Override
        public void run() {
            toSearchApp();
        }
    };

    public static final int MAX_SHOW_SEARCH_RECORD_COUNT = 10;//最多展示的搜索历史的个数
    public static final int SORT_TOP_SEARCH = 1;//热门推荐 的排序
    public static final int SORT_SEARCH_RECORD = 2;//搜索历史 的排序
    List<ISearchRecord> topSearchStatisticsList = new ArrayList<>();

    @Override
    public void initData() {
        //尝试获取缓存数据
        List<TopSearchStatistics> newList = DataUtil.getInstance().getCacheList(ApiKey.top_search_statistics, TopSearchStatistics.class);
        if (!ListUtil.isEmpty(newList)) {
            topSearchStatisticsList.addAll(newList);
            addListData("热门推荐", topSearchStatisticsList, SORT_TOP_SEARCH);
        }

        //初始化搜索历史
        List<SearchRecord> newSgrList = DDProviderHelper.getInstance().getSearchRecordList(MAX_SHOW_SEARCH_RECORD_COUNT);
        if (!ListUtil.isEmpty(newSgrList)) {
            searchRecordList.addAll(newSgrList);
            addListData("搜索历史", searchRecordList, SORT_SEARCH_RECORD);
        }
        notifyDataSetChangedTitleInfoList();
        SheepApp.getInstance().getNetComponent().getApiService().getTopSearchStatistics()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                    @Override
                    public void onNext(BaseMessage baseMessage) {
                        boolean isNewData = DataUtil.getInstance().isNewData(ApiKey.top_search_statistics);
                        if (isNewData) {
                            List<TopSearchStatistics> newList = baseMessage.getDatas(TopSearchStatistics.class);
                            topSearchStatisticsList.clear();
                            topSearchStatisticsList.addAll(newList);
                            if (ListUtil.getItem(titleInfoListList, new ListUtil.CallBack<TitleInfoList, Boolean>() {
                                @Override
                                public Boolean call(TitleInfoList titleInfoList) {
                                    return titleInfoList.getSort() == SORT_TOP_SEARCH;
                                }
                            }) == null) {
                                addListData("热门推荐", topSearchStatisticsList, SORT_TOP_SEARCH);
                            }
                            notifyDataSetChangedTitleInfoList();
                        }
                    }

                    @Override
                    public void onError(BaseMessage baseMessage) {
                    }
                });

    }

    //排序与刷新
    private void notifyDataSetChangedTitleInfoList() {
        //排序
        Collections.sort(titleInfoListList);
        //刷新
        recyclerView.getAdapter().notifyDataSetChanged();
        if (isTitleInfoListEmpty()) {
            frame_container.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.INVISIBLE);
        } else {
            frame_container.setVisibility(View.INVISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        }
    }

    //添加列表数据到总的列表中
    private void addListData(String title, final List<ISearchRecord> list, int sort) {
        titleInfoListList.add(new TitleInfoList(title, new RecyclerViewAdapter<ISearchRecord>(SheepApp.getInstance(), R.layout.item_i_serach_record, list) {
            @Override
            public void convert(ViewHolder viewHolder, final ISearchRecord item, int position) {
                View view = viewHolder.itemView;
                TextView item_search_record_name = view.findViewById(R.id.item_search_record_name);
                ImageView item_search_record_x = view.findViewById(R.id.item_search_record_x);
                ViewUtil.setText(item_search_record_name, item.getInput());
                if (item instanceof SearchRecord) {
                    //点击一条搜索历史后面的xx
                    item_search_record_x.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            list.remove(item);
                            recyclerView.getAdapter().notifyDataSetChanged();
                            DDProviderHelper.getInstance().deleteSearchRecord((SearchRecord) item);
                            if (isTitleInfoListEmpty()) {
                                frame_container.setVisibility(View.VISIBLE);
                                recyclerView.setVisibility(View.INVISIBLE);
                            }
                        }
                    });
                } else {
                    ViewUtil.setVisibility(item_search_record_x, false);
                }
                //点击一条搜索历史
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        TitleBarUtils.getInstance().setSearchText(ActSearchAppOrTask.this, item.getInput());
                        if (item instanceof IHomePageSearch)
                            ApiUtil.postTopSearchStatisticsClickTopSearch((IHomePageSearch) item);
                    }
                });
            }
        }).setSort(sort));
    }

    //搜索历史中没有数据且没有获取到服务器的热门搜索列表
    private boolean isTitleInfoListEmpty() {
        return searchRecordList.isEmpty() && topSearchStatisticsList.isEmpty();
    }

    List<ISearchRecord> searchRecordList = new ArrayList<>();

    //尝试搜索游戏
    private void toSearchApp() {
        recyclerView.setVisibility(View.INVISIBLE);
        frame_container.setVisibility(View.VISIBLE);
        String inputText = TitleBarUtils.getInstance().getSearchText(this);
        if (!TextUtils.isEmpty(inputText)) {
            //保存搜索到数据库
            SearchRecord searchRecord = new SearchRecord();
            searchRecord.setInput(inputText);
            searchRecord.setLast_time(System.currentTimeMillis());
            searchRecord.setCount(1);
            searchRecordList.add(searchRecord);
            DDProviderHelper.getInstance().addOrUpdateSearchRecord(searchRecord, null);
            recyclerView.getAdapter().notifyDataSetChanged();
        }
        fgtSearchAppOrTask.toSearch(inputText);
    }
}
