package com.taikor.investment.modules.customer;

import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
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.bean.Products;
import com.taikor.investment.mylibrary.TAnalytics;
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 java.util.ArrayList;
import java.util.List;

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

/**
 * 基金列表
 * Created by Any on 2017/4/12.
 */

public class FundsActivity extends BaseActivity implements
        AdapterView.OnItemClickListener,
        SimpleListView.OnLoadListener {

    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle;
    @BindView(R.id.et_find)
    EditText etFind;
    @BindView(R.id.ib_clear)
    ImageButton ibDeleteText;//删除
    @BindView(R.id.ll_fund)
    LinearLayout llFund;//基金列表布局
    @BindView(R.id.slv_fund)
    SimpleListView simpleListView;
    @BindView(R.id.tv_empty_result)
    TextView textView;

    private int mPage = 1;
    private String keyword = "";
    private FundAdapter mAdapter = null;
    private List<Product> mList = new ArrayList<>();
    private ArrayList<Products> repo;

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

    @Override
    public void initView() {
        tvBarTitle.setText("基金购买");
        etFind.setHint("请输入代码/拼音");
        etFind.addTextChangedListener(myWatcher);
        etFind.setOnKeyListener(onKeyListener);
        mAdapter = new FundAdapter(this);
        simpleListView.setAdapter(mAdapter);
        simpleListView.setOnItemClickListener(this);
        simpleListView.setOnLoadListener(this);

        Intent intent = this.getIntent();
        repo = (ArrayList<Products>) intent.getSerializableExtra("repo");
    }

    //请求网络数据
    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) {
                    simpleListView.finishLoad(true);
                    if (page == 1) {
                        textView.setVisibility(View.VISIBLE);
                    } else
                        textView.setVisibility(View.GONE);
                } else {
                    textView.setVisibility(View.GONE);
                    if (page == 1) {//更新数据
                        mList.clear();
                    }
                    mList.addAll(response);
                    if (response.size() < 10)
                        simpleListView.finishLoad(true);
                    else
                        simpleListView.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());
        //传递参数
        Intent intent = new Intent(FundsActivity.this, FundDescActivity.class);
        intent.putExtra("product_id", product.getProductID());
        intent.putExtra("product_name", product.getProductName());
        intent.putExtra("product_net_worth", product.getUnitNet());
        intent.putExtra("repo", repo);
        startActivity(intent);
        finish();
    }

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

    /**
     * 监听文本的变化
     */
    private 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) {
            //显示清除图标
            ibDeleteText.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);
                    llFund.setVisibility(View.VISIBLE);
                }
                return true;
            }
            return false;
        }
    };

}
