package com.taikor.investment.modules;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.AdapterView;
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.GroupAdapter;
import com.taikor.investment.base.BaseFragment;
import com.taikor.investment.bean.Group;
import com.taikor.investment.event.BooleanEvent;
import com.taikor.investment.modules.group.DefineActivity;
import com.taikor.investment.modules.group.FlexibleActivity;
import com.taikor.investment.modules.group.GroupDescActivity;
import com.taikor.investment.modules.group.GuaranteedActivity;
import com.taikor.investment.mylibrary.TAnalytics;
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 org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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/3/29.
 */
public class GroupFragment extends BaseFragment implements
        AdapterView.OnItemClickListener, SimpleListView.OnLoadListener {

    @BindView(R.id.tv_guaranteed)
    TextView tvGuaranteed;//保本型
    @BindView(R.id.tv_flexible)
    TextView tvFlexible;//灵活型
    @BindView(R.id.tv_define)
    TextView tvDefine;//自定义
    @BindView(R.id.slv_group)
    SimpleListView simpleListView;
    @BindView(R.id.tv_group)
    TextView tvGroup;

    private int mPage = 1;
    private GroupAdapter mAdapter;
    private ProgressDialog progressDialog;
    private List<Group> groups = new ArrayList<>();

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

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        mAdapter = new GroupAdapter(getActivity());
        simpleListView.setAdapter(mAdapter);
        simpleListView.setOnItemClickListener(this);
        simpleListView.setOnLoadListener(this);

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage(getString(R.string.progress_hint));
        progressDialog.setCancelable(true);

        //设置drawableRight的图片大小
        Drawable drawable = ContextCompat.getDrawable(getActivity(), R.drawable.rectangle3);
        drawable.setBounds(0, 0, 10, 50);
        tvGroup.setCompoundDrawables(drawable, null, null, null);
    }

    @Override
    public void initData() {
        getGroupData(Constant_URL.GROUP, mPage);
    }

    // 获取组合列表
    public void getGroupData(String url, final int page) {
        progressDialog.show();
        OkHttpUtils.get().url(url)
                .addParams("userid", "20000")
                .addParams("type", "-1")
                .addParams("style", "-1")
                .addParams("proportion", "-1")
                .addParams("count", "30")
                .addParams("sortType", "3")//目前还没有skip参数
                .build().execute(new Callback<List<Group>>() {

            @Override
            public List<Group> parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().string(), new TypeToken<List<Group>>() {
                }.getType());
            }

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

            @Override
            public void onResponse(List<Group> response, int id) {
                progressDialog.dismiss();
                if (response == null) {
                    return;
                }
                groups = response;
                mAdapter.setData(response, true);
                simpleListView.finishLoad(true);
            }
        });
    }

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

    @OnClick({R.id.tv_guaranteed, R.id.tv_flexible, R.id.tv_define})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_guaranteed:
                Intent costIntent = new Intent(getActivity(), GuaranteedActivity.class);
                startActivity(costIntent);
                break;
            case R.id.tv_flexible:
                Intent flexibleIntent = new Intent(getActivity(), FlexibleActivity.class);
                startActivity(flexibleIntent);
                break;
            case R.id.tv_define:
                Intent defineIntent = new Intent(getActivity(), DefineActivity.class);
                startActivity(defineIntent);
                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String portfolioID = groups.get(position).getPortfolioID();
        //埋点
        TAnalytics.onClick("enterGroupDetail",portfolioID);
        Intent intent = new Intent(getActivity(), GroupDescActivity.class);
        intent.putExtra("itemId", portfolioID);
        intent.putExtra("from","groupPage");
        startActivity(intent);
    }

    //刷新数据
    @Subscribe(threadMode = ThreadMode.MAIN)//涉及请求网络，需要更改线程模式
    public void process(BooleanEvent event) {
        String type = event.getType();
        if (event.isFlag()) {
            if (type.equals("group") || type.equals("all"))
                getGroupData(Constant_URL.GROUP, 1);
        }
    }

    //注册事件总线
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    //解除事件总线
    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    //埋点
    @Override
    public void onHiddenChanged(boolean hidden) {
        if(!hidden){
            TAnalytics.onPageStart("groupPage");
        }else{
            TAnalytics.onPageLoad("groupPage","","","");
        }
    }
}
