package com.taikor.investment.modules.group;

import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
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.GroupProductAdapter;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.bean.Product;
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/13.
 */

public class ProductsActivity extends BaseActivity implements SimpleListView.OnLoadListener {
    
    @BindView(R.id.tv_bar_back)
    TextView tvBack;//上一步
    @BindView(R.id.tv_bar_title)
    TextView tvMiddleTitle;//标题
    @BindView(R.id.tv_bar_right)
    public TextView tvRight;//完成
    @BindView(R.id.et_find)
    EditText etFind;//搜索
    @BindView(R.id.ib_clear)
    ImageButton ibClear;//清除
    @BindView(R.id.ll_product)
    LinearLayout llProduct;//产品布局
    @BindView(R.id.slv_products)
    SimpleListView simpleListView;
    @BindView(R.id.tv_empty_results)
    TextView textView;

    private int mPage = 1;
    private String keyword = "";
    private GroupProductAdapter mAdapter = null;
    private List<Product> mList = new ArrayList<>();//装载所有请求的数据

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

    @Override
    public void initView() {
        //初始化界面
        tvBack.setText("上一步");
        tvBack.setTextColor(Color.parseColor("#FFFFFF"));
        tvBack.setBackground(null);
        tvMiddleTitle.setText("添加产品");
        tvRight.setText("完成");
        tvRight.setVisibility(View.VISIBLE);
        mAdapter = new GroupProductAdapter(this);
        simpleListView.setAdapter(mAdapter);
        simpleListView.setOnLoadListener(this);

        //设置文字的监听
        etFind.setHint(R.string.keyword);
        etFind.addTextChangedListener(watcher);
        etFind.setOnKeyListener(onKeyListener);
    }

    @Override
    public void initData() {
        getProductsList(Constant_URL.PRODUCT, mPage);
    }

    //请求网络数据
    public void getProductsList(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(10 * (page - 1)))
                .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.setList(mList);
                mAdapter.setData(response, page == 1);
            }

        });
    }

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

    @OnClick({R.id.tv_bar_back, R.id.tv_bar_right, R.id.ib_clear})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bar_back:
                finish();
                break;
            case R.id.tv_bar_right://返回到添加产品，设置仓位
                //获取选中的产品集合
                ArrayList<Product> selectedItem = mAdapter.getSelectedItem();
                if (selectedItem.size()!=0) {
                    tvRight.setText("完成(" + selectedItem.size() + ")");
                    Intent intent = this.getIntent();
                    intent.putExtra("products_list", selectedItem);
                    setResult(RESULT_OK, intent);
                    this.finish();//此处一定要调用finish()方法
                }
                break;
            case R.id.ib_clear:
                etFind.setText("");
                ibClear.setVisibility(View.GONE);
                break;
        }
    }

    /**
     * 文字监听
     */
    private TextWatcher watcher = 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;
                    getProductsList(Constant_URL.PRODUCT, mPage);
                    llProduct.setVisibility(View.VISIBLE);
                }
                return true;
            }
            return false;
        }
    };
}
