package com.beanpodtech.allinone.activity;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.aliyun.svideo.common.utils.ToastUtils;
import com.beanpodtech.allinone.R;
import com.beanpodtech.allinone.adapter.RecommendVideoAdapter;
import com.beanpodtech.allinone.adapter.SearchHistoryAdapter;
import com.beanpodtech.allinone.bean.RecommendVideoBean;
import com.beanpodtech.allinone.http.UrlConfig;
import com.beanpodtech.allinone.utils.Contants;
import com.beanpodtech.allinone.utils.HttpUtils;
import com.beanpodtech.allinone.utils.OkGoBuilder;
import com.beanpodtech.allinone.utils.OkGoUtil;
import com.beanpodtech.allinone.utils.SpUtil;
import com.beanpodtech.allinone.widget.flowlayout.TagFlowLayout;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class SearchActivity extends BaseActivity {

    private EditText etSearch;
    private ImageView ivSearch;
    private TagFlowLayout tflHistory;
    private TextView tvChange;
    private RecyclerView idRecyclerview;
    //搜索框的关键字
    private String keyWordsInput;
    //搜索历史
    private String keyWordsHistory;
    private SearchHistoryAdapter searchHistoryAdapter;
    private List<String> listHistory = new ArrayList<>();
    private List<RecommendVideoBean.ListBean> listRecommend = new ArrayList<>();
    private RecommendVideoAdapter recommendVideoAdapter;
    private String userId;
    private ImageView ivBack;

    public static void startActivity(Context context, Bundle bundle) {
        Intent intent = new Intent(context, SearchActivity.class);
        context.startActivity(intent);
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_search:
                String keyWord = etSearch.getText().toString();
                if (keyWord != null && !TextUtils.isEmpty(keyWord)) {
                    setHistory(keyWord);
                    SearchResultActivity.startActivity(mContext, keyWord);
                    getHistory();
                } else {
                    ToastUtils.show(mContext, getResources().getString(R.string.please_input_keyword));
                }
                break;
            case R.id.tv_change:
                getRecommendVideo();
                break;
            case R.id.iv_back:
                finish();
                break;
        }
    }

    /**
     * 保存搜索记录到本地
     *
     * @param keyWord 关键字
     */
    private void setHistory(String keyWord) {
        String keyWordHistory = SpUtil.getInstace().getString(Contants.SEARCH_KEY_WORD, null);
        StringBuilder sb = null;
        if (keyWordHistory != null && !TextUtils.isEmpty(keyWordHistory)) {
            sb = new StringBuilder(keyWordHistory);
            String[] strings = sb.toString().split(",");
            boolean tag = false;
            for (int i = 0; i < strings.length; i++) {
                if (keyWord.equals(strings[i])) {
                    tag = true;
                }
            }
            if (!tag) {
                sb.append(",").append(keyWord);
            }
        } else {
            sb = new StringBuilder();
            sb.append(keyWord);
        }
        SpUtil.getInstace().save(Contants.SEARCH_KEY_WORD, sb.toString());
    }


    @Override
    public int bindLayout() {
        return R.layout.activity_search;
    }

    @Override
    public void initView(View view) {
        findViewById(R.id.tv_title).setVisibility(View.INVISIBLE);
        ivBack = findViewById(R.id.iv_back);
        etSearch = findViewById(R.id.et_search);
        ivSearch = findViewById(R.id.iv_search);
        tflHistory = findViewById(R.id.tfl_history);
        tvChange = findViewById(R.id.tv_change);
        idRecyclerview = findViewById(R.id.id_recyclerview);
        searchHistoryAdapter = new SearchHistoryAdapter(mContext, listHistory, getLayoutInflater(), tflHistory);
        tflHistory.setAdapter(searchHistoryAdapter);
        idRecyclerview.setLayoutManager(new GridLayoutManager(this, 5));
        idRecyclerview.setItemAnimator(new DefaultItemAnimator());
        recommendVideoAdapter = new RecommendVideoAdapter(listRecommend, mContext);
        idRecyclerview.setAdapter(recommendVideoAdapter);
    }

    @Override
    public void initListener() {
        ivSearch.setOnClickListener(this);
        ivBack.setOnClickListener(this);
        tvChange.setOnClickListener(this);
    }

    @Override
    public void initData(Context mContext) {
        userId = SpUtil.getInstace().getString(Contants.USER_ID, null);
        getHistory();
        getRecommendVideo();
    }

    /**
     * 获取推荐课程
     */
    private void getRecommendVideo() {
        OkGoBuilder.getInstance().url(UrlConfig.RECOMMENDVIDEO).Builder(this).requestBody(HttpUtils.getRequestJson(initRequestJson(userId))).cls(RecommendVideoBean.class).method(OkGoBuilder.PSOT).callback(new OkGoUtil<RecommendVideoBean>(RecommendVideoBean.class) {
            @Override
            public void onSuccess(Response<RecommendVideoBean> response) {
                if (response.body() != null && response.body().getList() != null) {
                    if (response.body() instanceof RecommendVideoBean) {
                        RecommendVideoBean body = response.body();
                        List<RecommendVideoBean.ListBean> list = body.getList();
                        listRecommend.clear();
                        listRecommend.addAll(list);
                        recommendVideoAdapter.notifyDataSetChanged();
                    }
                }/* else {
                    ToastUtils.show(mContext, "网络请求异常");
                }*/

//                progressDialog.dismiss();

            }

            @Override
            public void onError(Response<RecommendVideoBean> response) {
                super.onError(response);
            }

            @Override
            public void onFinish() {
                super.onFinish();

            }
        }).build();
    }

    /**
     * @param userId 用户Id
     * @return 返回处理好的请求requestBody
     */
    private HashMap<String, String> initRequestJson(String userId) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", userId);
        return map;
    }

    /**
     * 获取本地保存的搜索记录
     */
    private void getHistory() {
        listHistory.clear();
        keyWordsHistory = SpUtil.getInstace().getString(Contants.SEARCH_KEY_WORD, null);
        if (keyWordsHistory != null && !TextUtils.isEmpty(keyWordsHistory)) {
            String[] split = keyWordsHistory.split(",");
            List<String> strings = Arrays.asList(split);
            if (strings != null) {
                listHistory.addAll(strings);
                searchHistoryAdapter.notifyDataChanged();
            }
        }
    }
}
