package com.taikor.investment.modules.product;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.taikor.investment.R;
import com.taikor.investment.adapter.FundAdapter;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.bean.Product;
import com.taikor.investment.event.FixedProductEvent;
import com.taikor.investment.event.MustProductEvent;
import com.taikor.investment.event.SettingProductEvent;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.CommonUtils;
import com.taikor.investment.utils.KeyBoardUtils;
import com.taikor.investment.utils.Constant_URL;
import com.taikor.investment.view.SimpleListView;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import org.greenrobot.eventbus.EventBus;

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

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 搜索页产品列表
 * Created by Any on 2017/6/8.
 */
public class ProductSearchActivity extends BaseActivity implements
        AdapterView.OnItemClickListener,
        SimpleListView.OnLoadListener {

    @BindView(R.id.et_find)
    EditText etFind;
    @BindView(R.id.ib_clear)
    ImageButton ibClear;
    @BindView(R.id.slv_product_list)
    SimpleListView slvProductList;
    @BindView(R.id.tv_product_empty)
    TextView tvEmpty;

    private int mPage = 1;
    private boolean jump_desc;
    private Intent productIntent;
    private FundAdapter mAdapter;
    private String keyword,flag,fromPage;
    private List<Product> mList = new ArrayList<>();

    @Override
    public int getContentViewId() {
        return R.layout.activity_product_list;
    }

    @Override
    public void initView() {
        etFind.setHint(R.string.find_by_product_manager);
        etFind.setFocusable(true);
        etFind.setFocusableInTouchMode(true);
        etFind.requestFocus();
        KeyBoardUtils.showKeyBoard(this, etFind);
        etFind.addTextChangedListener(myWatcher);
        etFind.setOnKeyListener(onKeyListener);

        mAdapter = new FundAdapter(this);
        slvProductList.setAdapter(mAdapter);
        slvProductList.setOnItemClickListener(this);
        slvProductList.setOnLoadListener(this);

        productIntent = getIntent();
        flag = productIntent.getStringExtra("type");
        jump_desc = productIntent.getBooleanExtra("jump_desc", false);
    }

    //获取数据
    public void getFundsData(String url, final int page) {
        OkHttpUtils.get().url(url)
                .addParams("keyword", keyword)
                .addParams("type", "-1")
                .addParams("target", "-1")
                .addParams("category", "-1")
                .addParams("term", "-1")
                .addParams("companyID", "")
                .addParams("managerID", "")
                .addParams("closedPeriod", "-1")
                .addParams("openFrequency", "-1")
                .addParams("style", "-1")
                .addParams("sortType", "3")
                .addParams("count", "10")
                .addParams("skip", String.valueOf((page - 1) * 10))
                .build().execute(new Callback<List<Product>>() {
            @Override
            public List<Product> parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().string(), new TypeToken<List<Product>>() {
                }.getType());
            }

            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(List<Product> response, int id) {
                if (response == null) {
                    return;
                }
                if (response.size() == 0) {
                    if (page == 1) {
                        tvEmpty.setVisibility(View.VISIBLE);
                    } else {
                        tvEmpty.setVisibility(View.GONE);
                        slvProductList.finishLoad(true);
                    }
                } else {
                    tvEmpty.setVisibility(View.GONE);
                    if (page == 1) {//更新数据
                        mList.clear();
                    }
                    mList.addAll(response);
                    if (response.size() < 10)
                        slvProductList.finishLoad(true);
                    else
                        slvProductList.finishLoad(page == 10);
                }
                mAdapter.setData(response, page == 1);
            }
        });
    }

    /**
     * 加载更多
     *
     * @param isRefresh true为下拉刷新 false为加载更多
     */
    @Override
    public void onLoad(boolean isRefresh) {
        if (isRefresh) {
            mPage = 1;
        } else {
            mPage++;
        }
        getFundsData(Constant_URL.PRODUCT, mPage);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Product product = (Product) parent.getItemAtPosition(position);
        //埋点
        TAnalytics.onClick("enterProduct",product.getProductID());
        if (jump_desc) { //跳转详情
            Intent detailIntent = new Intent(ProductSearchActivity.this, ProductDescActivity.class);
            detailIntent.putExtra("itemId", product.getProductID());
            detailIntent.putExtra("from","productSearchPage");
            startActivity(detailIntent);
        } else {//获取产品名称
            switch (flag) {
                case "fixed":
                    int fixed_position = productIntent.getIntExtra("fixed_position", 0);
                    EventBus.getDefault().post(new FixedProductEvent(product.getProductName(), product.getAnnualizedProfitRate(), fixed_position, product.getProductID()));
                    break;
                case "must":
                    int must_position = productIntent.getIntExtra("must_position", 0);
                    EventBus.getDefault().post(new MustProductEvent(product.getProductName(), product.getAnnualizedProfitRate(), must_position, product.getProductID()));
                    break;
                case "setting":
                    int setting_position = productIntent.getIntExtra("setting_position", 0);
                    EventBus.getDefault().post(new SettingProductEvent(product.getProductName(), setting_position, product.getProductID()));
                    break;
            }
            finish();
        }
    }

    @OnClick({R.id.iv_back, R.id.ib_clear})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_clear:
                etFind.setText("");
                break;
            case R.id.iv_back:
                finish();
                KeyBoardUtils.hideSoftKeyboard(etFind);
                break;
        }
    }

    //监听文本的变化
    TextWatcher myWatcher = 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) {
            //显示清除图标
            ibClear.setVisibility(View.VISIBLE);
        }
    };

    //文字输入之后，右下角按钮：完成
    private View.OnKeyListener onKeyListener = new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                //隐藏软键盘
                KeyBoardUtils.hideSoftKeyboard(v);
                //显示ListView列表
                String s = etFind.getText().toString();
                if (!TextUtils.isEmpty(s)) {
                    keyword = s;
                    getFundsData(Constant_URL.PRODUCT, mPage);
                }
                return true;
            }
            return false;
        }
    };

    //埋点
    @Override
    protected void onResume() {
        super.onResume();
        TAnalytics.onPageStart("bestGroupPage");
    }

    @Override
    protected void onPause() {
        super.onPause();
        switch (flag){
            case "find":
                fromPage="homePage";
                break;
            case "product":
                fromPage="productPage";
                break;
            case "fixed":
            case "must":
                fromPage="breakPage";
                break;
            case "setting":
                fromPage="flexiblePage";
                break;
        }
        TAnalytics.onPageLoad("productSearchPage",fromPage,"","");
    }

    @Override
    public void onBackPressed() {
        finish();
        KeyBoardUtils.hideSoftKeyboard(etFind);
    }
}
