package com.sheep.gamegroup.view.activity;

import android.app.Activity;
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.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.sheep.gamegroup.event.BigEvent;
import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.BaseMessage;
import com.sheep.gamegroup.model.entity.SearchGameRecord;
import com.sheep.gamegroup.model.entity.TaskEty;
import com.sheep.gamegroup.model.entity.Release_task;
import com.sheep.gamegroup.model.entity.XiaomiGameEntity;
import com.sheep.gamegroup.model.util.SheepSubscriber;
import com.sheep.gamegroup.util.CommonUtil;
import com.sheep.gamegroup.util.Jump2View;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.LogUtil;
import com.sheep.gamegroup.util.MyDbManager;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.TestUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.gamegroup.view.adapter.ArrayAdapter;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

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

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

import static com.sheep.gamegroup.util.UMConfigUtils.Event.SEARCH_GAME_COMMIT;
import static com.sheep.gamegroup.view.adapter.TryMakeMoneyAdp.PUBLIC_TAG_PREFIX_TEXTVIEW_LIST;

/**
 * Created by realicing on 2018/04/.
 * realicing@sina.com
 */
public class ActSearchGame extends BaseActivity {

    @BindView(R.id.search_game_input)
    AppCompatAutoCompleteTextView search_game_input;
    @BindView(R.id.search_game_bt)
    TextView search_game_bt;
    @BindView(R.id.search_game_hot_list)
    GridView search_game_hot_list;
    @BindView(R.id.search_game_list)
    RecyclerView search_game_list;
    @BindView(R.id.search_game_hot)
    View search_game_hot;
    @BindView(R.id.empty_view)
    View empty_view;

    private int type;//1:小米游戏过来

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

    private ActSearchGame activity;

    @Override
    public void initView() {
        type = getIntent().getIntExtra("where_come", 0);
        EventBus.getDefault().register(this);
        activity = this;
        TitleBarUtils.getInstance()
                .setShowOrHide(this, true)
                .setTitle(this, "搜索游戏")
                .setTitleFinish(this);
        empty_view.setVisibility(View.GONE);
        initHotList();
        initList();
        initInput();

    }
    private ArrayAdapter<SearchGameRecord> inputAdapter;
    private void initInput() {
        inputAdapter = new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1, searchGameRecordList);
        search_game_input.setAdapter(inputAdapter);
        search_game_input.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Object obj = parent.getItemAtPosition(position);
                if(obj instanceof SearchGameRecord){
                    search_game_input.setText(((SearchGameRecord) obj).getInput());
                }
            }

        });
//        search_game_input.setThreshold(1);
    }

    private AdbCommonRecycler<Object> adapter;
    private void initList() {
        search_game_list.setLayoutManager(new LinearLayoutManager(activity));
        adapter = new AdbCommonRecycler<Object>(activity, list) {

            @Override
            public int getViewIdByType(int type) {
                return R.layout.item_search_game;
            }

            @Override
            public void convert(ViewHolder holder, final Object item) {
                View itemView = holder.itemView;
                if(item == null)
                    return;
                ImageView find_information_game_icon = (ImageView) itemView.findViewById(R.id.find_information_game_icon);
                TextView find_information_game_name = (TextView) itemView.findViewById(R.id.find_information_game_name);
                TextView find_information_game_surplus = (TextView) itemView.findViewById(R.id.find_information_game_surplus);
                TextView find_information_game_time = (TextView) itemView.findViewById(R.id.find_information_game_time);
                TextView find_information_game_yuan = (TextView) itemView.findViewById(R.id.find_information_game_yuan);
                TextView find_information_game_task_bottom = (TextView) itemView.findViewById(R.id.find_information_game_task_bottom);
                TextView find_information_game_task_top = (TextView) itemView.findViewById(R.id.find_information_game_task_top);
                TextView find_information_game_task_center = (TextView) itemView.findViewById(R.id.find_information_game_task_center);

                if(item instanceof Release_task){
                    final Release_task items = (Release_task) item;
                    final TaskEty taskEty;
                    if ((taskEty = items.getTask()) == null) {
                        return;
                    }
                    ViewUtil.centerImage(find_information_game_icon, taskEty.getIcon());
                    ViewUtil.setText(find_information_game_name, items.getName());
                    ViewUtil.setText(find_information_game_surplus);
                    ViewUtil.setText(find_information_game_time, taskEty.getDetailShow());
                    find_information_game_yuan.setVisibility(View.INVISIBLE);//这里必须为INVISIBLE,因为要显示两个按钮，下面的按钮位置不动
                    find_information_game_task_top.setVisibility(View.VISIBLE);
                    find_information_game_task_top.setText("立即充值");
                    find_information_game_task_top.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ViewUtil.showGamePayAccount(activity, taskEty.getThird_task_id(), items.getName());
                        }
                    });
                    items.getDownloadHelper().updateDownloadTaskView(activity, taskEty, find_information_game_task_bottom);
                    find_information_game_task_bottom.setTag("PUBLIC_TAG_PREFIX_TEXTVIEW_LIST" + taskEty.getDownload_link());
                }else if(item instanceof XiaomiGameEntity){
                    final XiaomiGameEntity  items = (XiaomiGameEntity) item;
                    ViewUtil.centerImage(find_information_game_icon, items.getIcon());
                    ViewUtil.setText(find_information_game_name, items.getName());
                    ViewUtil.setText(find_information_game_surplus);
                    ViewUtil.setText(find_information_game_time, "");
                    find_information_game_yuan.setVisibility(View.GONE);//这里必须为INVISIBLE,因为要显示两个按钮，下面的按钮位置不动
                    find_information_game_task_top.setVisibility(View.GONE);
                    find_information_game_task_bottom.setVisibility(View.GONE);
                    find_information_game_task_center.setVisibility(View.VISIBLE);
                    if(items.getAvailable_receive() == 0 && items.getReceive_account() == 0){//未领取账号
                        CommonUtil.getInstance()
                                .xiaomiRevieceAcctoun(find_information_game_task_center, items, activity);
                    }else {
                        items.getDownloadHelper().updateDownloadTaskView((Activity) activity, items, find_information_game_task_center);
                        find_information_game_task_center.setTag(PUBLIC_TAG_PREFIX_TEXTVIEW_LIST + items.getDownload_url());
                    }
                }


            }
        };
        search_game_list.setAdapter(adapter);
    }

    private ArrayAdapter<Release_task> hotAdapter;
    private void initHotList() {
        hotAdapter = new ArrayAdapter<Release_task>(activity, R.layout.item_search_game_hot, hotList) {
            @Override
            public boolean convert(int position, View convertView, ViewGroup parent, final Release_task item) {
                if (convertView instanceof TextView) {
                    ((TextView) convertView).setText(item.getName());
                }
                convertView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        search_game_input.setText(item.getName());
                        search_game_input.setSelection(search_game_input.getText().toString().length());
                    }
                });
                return true;
            }
        };
        search_game_hot_list.setAdapter(hotAdapter);
    }

    private Runnable autoSearchRunnable = new Runnable() {
        @Override
        public void run() {
            search_game_bt.performClick();
        }
    };
    @Override
    public void initListener() {
        if(TestUtil.isTest()){
            search_game_input.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)});
        }
        search_game_input.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search_game_bt.performClick();
                }
                return false;
            }
        });
        search_game_input.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editable.toString();
                if(text.startsWith("h") && TestUtil.isTest()){//测试用 http中的h开头
                    return;
                }
                if(text.startsWith("t") && TestUtil.isTest()){//测试用 task中的t开头
                    return;
                }
                search_game_input.removeCallbacks(autoSearchRunnable);
                search_game_input.postDelayed(autoSearchRunnable, 1000L);//1秒后自动搜索
            }
        });
    }

    List<SearchGameRecord> searchGameRecordList = new ArrayList<>();
    List<Release_task> hotList = new ArrayList<>();
    List<Object> list = new ArrayList<>();

    @Override
    public void initData() {
        //初始化搜索历史
        List<SearchGameRecord> newSgrList = MyDbManager.getInstance().getAllSearchGameRecord(type);
        ListUtil.addAll(searchGameRecordList, newSgrList);
        inputAdapter.notifyDataSetChanged();
        if(type == 1){
            search_game_hot.setVisibility(View.GONE);
        }else {
            //初始化热门列表
            SheepApp.getInstance().getNetComponent().getApiService()
                    .releaseTask(1, 9,
                            SheepApp.getInstance().getConnectAddress().getPlatForm(), 1,
                            0, 0,
                            "1002,1003,1004", 3)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new SheepSubscriber<BaseMessage>(SheepApp.getInstance()) {
                        @Override
                        public void onError(BaseMessage baseMessage) {
                            CommonUtil.getInstance().updateEmptyView(empty_view, true);
                            search_game_hot.setVisibility(View.GONE);
                            search_game_list.setVisibility(View.GONE);
                        }

                        @Override
                        public void onNext(BaseMessage baseMessage) {
                            List<Release_task> newList = baseMessage.getDatas(Release_task.class);
                            ListUtil.addAll(hotList, newList);
                            hotAdapter.notifyDataSetChanged();
                        }
                    });
        }


    }

    @OnClick({R.id.search_game_bt})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.search_game_bt:
                SEARCH_GAME_COMMIT.onEvent();
                toSearchGame();
                break;
        }
    }

    private void toSearchGame() {
        String inputText = search_game_input.getText().toString();
        if (TextUtils.isEmpty(inputText)) {
            list.clear();
            notifyDataSetChanged();
            return;
        }
        //保存搜索到数据库
        SearchGameRecord searchGameRecord = new SearchGameRecord();
        searchGameRecord.setInput(inputText);
        searchGameRecord.setTime(System.currentTimeMillis());
        searchGameRecord.setType(type);
        MyDbManager.getInstance().saveOrUpdate(searchGameRecord);
        searchGameRecordList.add(searchGameRecord);
//        initInput();

        if(inputText.startsWith("http") && inputText.length() > 6 && TestUtil.isTest()){//测试用
            Jump2View.getInstance().goWeb(activity, inputText, "测试内部H5");
            return;
        }
        if(inputText.startsWith("task") && inputText.length() > 6 && TestUtil.isTest()){//测试用
            ArrayList<String> arrayList = StringUtils.getAllSatisfyStr(inputText, "\\d+");
            ListUtil.forEach(arrayList, new Action1<String>() {
                @Override
                public void call(String s) {
                    Jump2View.getInstance().goTaskDetailView(activity, Integer.parseInt(s));
                }
            });
            return;
        }

        if(type == 1){
            CommonUtil.getInstance()
                    .xiaomiGame(activity,1, 100, inputText, new Action1<BaseMessage>() {
                        @Override
                        public void call(BaseMessage baseMessage) {
                            try {
                                if(baseMessage == null){

                                    G.showToast("暂无游戏");
                                    list.clear();
                                    notifyDataSetChanged();
                                }else {
                                    List<XiaomiGameEntity> newList = baseMessage.getDatas(XiaomiGameEntity.class);
                                    list.clear();
                                    ListUtil.addAll(list, newList);
                                    notifyDataSetChanged();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }else {
            CommonUtil.getInstance()
                    .gameTask(activity, "1002,1003,1004", inputText, new Action1<BaseMessage>() {
                        @Override
                        public void call(BaseMessage baseMessage) {
                            try {
                                if(baseMessage == null){

                                    G.showToast("暂无游戏");
                                    list.clear();
                                    notifyDataSetChanged();
                                }else {
                                    List<Release_task> newList = baseMessage.getDatas(Release_task.class);
                                    list.clear();
                                    ListUtil.addAll(list, newList);
                                    notifyDataSetChanged();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        }
    }

    private void notifyDataSetChanged() {
        adapter.notifyDataSetChanged();
        if (list.isEmpty()) {
            if(hotList.isEmpty()) {
                CommonUtil.getInstance().updateEmptyView(empty_view, true);
            } else {
                search_game_hot.setVisibility(View.VISIBLE);
            }
            search_game_list.setVisibility(View.GONE);
        } else {
            search_game_list.setVisibility(View.VISIBLE);
            if(hotList.isEmpty()) {
                empty_view.setVisibility(View.GONE);
            } else {
                search_game_hot.setVisibility(View.GONE);
            }
        }
    }

    @Subscribe
    public void onEventMainThread(BigEvent event){
        CommonUtil.getInstance().setEventResultViewStatus(event, search_game_list);
    }

    @Override
    public void onBackPressed() {
        if(search_game_input.getText().toString().isEmpty()) {
            super.onBackPressed();
        } else {
            search_game_input.setText("");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }
}
