package com.taikor.investment.modules.find;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
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.MasterAdapter;
import com.taikor.investment.base.BaseFragment;
import com.taikor.investment.bean.Group;
import com.taikor.investment.event.GroupEvent;
import com.taikor.investment.modules.group.GroupDescActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.CommonUtils;
import com.taikor.investment.utils.ScreenUtils;
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/4/11.
 */
public class MasterFragment extends BaseFragment implements
        View.OnClickListener, AdapterView.OnItemClickListener,
        SimpleListView.OnLoadListener {

    @BindView(R.id.rb_style_mas)
    RadioButton rbStyle;
    @BindView(R.id.rb_proportion_mas)
    RadioButton rbProportion;
    @BindView(R.id.slv_master)
    SimpleListView slvMaster;

    private int mPage = 1;
    private int width, height;
    private MasterAdapter mAdapter;
    private String style = "-1", proportion = "-1";
    private PopupWindow styleWindow, proportionWindow;
    private List<Group> groups = new ArrayList<>();
    private List<RadioButton> styleButton = new ArrayList<>(), proportionButton = new ArrayList<>();
    private String[] styleValue = {"-1", "1", "2", "3", "4"}, proportionValue = {"-1", "1", "2", "3", "4", "5"};

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

    @Override
    protected void initView(View view, Bundle savedInstanceState) {
        //获取屏幕的大小
        width = ScreenUtils.getScreenWidth(getActivity());
        height = ScreenUtils.getScreenHeight(getActivity());
        initStyleWindow();
        initProWindow();
        mAdapter = new MasterAdapter(getActivity());
        slvMaster.setAdapter(mAdapter);
        slvMaster.setOnLoadListener(this);
        slvMaster.setOnItemClickListener(this);
    }

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

    //请求数据
    public void getGroupData(String url, final int page) {
        OkHttpUtils.get().url(url)
                .addParams("type", "2")
                .addParams("style", style)
                .addParams("proportion", proportion)
                .addParams("count", "5")
                .addParams("sortType", "3")
                .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) {
            }

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

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

    @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","masterPage");
        startActivity(intent);
    }


    @OnClick({R.id.rb_style_mas, R.id.rb_proportion_mas})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_style_mas:
                styleWindow.showAsDropDown(rbStyle, 0, 5);
                break;
            case R.id.rb_proportion_mas:
                proportionWindow.showAsDropDown(rbProportion, 0, 5);
                break;
        }
    }

    //设置透明度
    private void setAlpha(float alpha) {
        Window window = getActivity().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.alpha = alpha;
        window.setAttributes(params);
    }

    //恢复透明度
    private class DismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            setAlpha(1f);
        }
    }

    //修改界面
    public void changeView(PopupWindow popupWindow, final RadioButton radioButton) {
        popupWindow.dismiss();
        if (radioButton.isChecked()) {
            radioButton.setChecked(false);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.view_style:
                changeView(styleWindow, rbStyle);
                break;
            case R.id.view_pro:
                changeView(proportionWindow, rbProportion);
                break;
            case R.id.tv_sure_style:
                changeView(styleWindow, rbStyle);
                for (int i = 0; i < styleButton.size(); i++) {
                    if (styleButton.get(i).isChecked())
                        style = styleValue[i];
                }
                //刷新界面
                EventBus.getDefault().post(new GroupEvent());
                break;
            case R.id.tv_sure_pro:
                changeView(proportionWindow, rbProportion);
                for (int i = 0; i < proportionButton.size(); i++) {
                    if (proportionButton.get(i).isChecked())
                        proportion = proportionValue[i];
                }
                //刷新界面
                EventBus.getDefault().post(new GroupEvent());
                break;
        }
    }

    //用于筛选时刷新数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(GroupEvent event) {
        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);
    }

    //风格弹出框
    public void initStyleWindow() {
        //创建popupWindow对象
        final View stylePop = getActivity().getLayoutInflater().inflate(R.layout.ppw_style, null);
        //初始化popupWindow对象
        styleWindow = new PopupWindow(stylePop, width, height - CommonUtils.dip2px(getActivity(), 300), true);
        //点击其他位置，popupWindow消失
        styleWindow.setTouchable(true);
        styleWindow.setOutsideTouchable(true);
        styleWindow.setBackgroundDrawable(ContextCompat.getDrawable(getActivity(), android.R.color.transparent));
        styleWindow.setOnDismissListener(new DismissListener());
        //初始化popupWindow的布局中的其他控件
        RadioButton rbNoLimit = (RadioButton) stylePop.findViewById(R.id.rb_no_style);
        RadioButton rbKeep = (RadioButton) stylePop.findViewById(R.id.rb_keep);
        RadioButton rbSteady = (RadioButton) stylePop.findViewById(R.id.rb_steady);
        RadioButton rbBalance = (RadioButton) stylePop.findViewById(R.id.rb_balance);
        RadioButton rbRadical = (RadioButton) stylePop.findViewById(R.id.rb_radical);
        TextView tvSure = (TextView) stylePop.findViewById(R.id.tv_sure_style);
        View view = stylePop.findViewById(R.id.view_style);
        rbNoLimit.setChecked(true);
        styleButton.add(rbNoLimit);
        styleButton.add(rbKeep);
        styleButton.add(rbSteady);
        styleButton.add(rbBalance);
        styleButton.add(rbRadical);
        tvSure.setOnClickListener(this);
        view.setOnClickListener(this);
    }

    //比例弹出框
    public void initProWindow() {
        //创建popupWindow对象
        final View proPop = getActivity().getLayoutInflater().inflate(R.layout.ppw_proportion, null);
        //初始化popupWindow对象
        proportionWindow = new PopupWindow(proPop, width, height - CommonUtils.dip2px(getActivity(), 300), true);
        //点击其他位置，popupWindow消失
        proportionWindow.setTouchable(true);
        proportionWindow.setOutsideTouchable(true);
        proportionWindow.setBackgroundDrawable(ContextCompat.getDrawable(getActivity(), android.R.color.transparent));
        proportionWindow.setOnDismissListener(new DismissListener());
        //初始化popupWindow的布局中的其他控件
        RadioButton rbNoLimit = (RadioButton) proPop.findViewById(R.id.rb_no_pro);
        RadioButton rbCostStrategy = (RadioButton) proPop.findViewById(R.id.rb_cost_strategy);
        RadioButton rbStockDebt = (RadioButton) proPop.findViewById(R.id.rb_stock_debt);
        RadioButton rbStockStrategy = (RadioButton) proPop.findViewById(R.id.rb_stock_strategy);
        RadioButton rbDebtStrategy = (RadioButton) proPop.findViewById(R.id.rb_debt_strategy);
        RadioButton rbMoreStrategy = (RadioButton) proPop.findViewById(R.id.rb_more_strategy);
        TextView tvSure = (TextView) proPop.findViewById(R.id.tv_sure_pro);
        View view = proPop.findViewById(R.id.view_pro);
        rbNoLimit.setChecked(true);
        proportionButton.add(rbNoLimit);
        proportionButton.add(rbCostStrategy);
        proportionButton.add(rbStockDebt);
        proportionButton.add(rbStockStrategy);
        proportionButton.add(rbDebtStrategy);
        proportionButton.add(rbMoreStrategy);
        tvSure.setOnClickListener(this);
        view.setOnClickListener(this);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        if(isVisibleToUser){
//           TAnalytics.onPageStart("master");
        }else{
//           TAnalytics.onPageLoad(getActivity(),"master","","","");
        }
    }
}
