package com.taikor.investment.modules.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;

import com.google.gson.Gson;
import com.taikor.investment.R;
import com.taikor.investment.adapter.FlexibleGroupAdapter;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.bean.Groups;
import com.taikor.investment.bean.OutputResult;
import com.taikor.investment.bean.Products;
import com.taikor.investment.bean.SettingProduct;
import com.taikor.investment.event.SettingProductEvent;
import com.taikor.investment.modules.product.ProductSearchActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.DegreeUtils;
import com.taikor.investment.utils.ScreenUtils;
import com.taikor.investment.utils.ToastUtils;
import com.taikor.investment.utils.Constant_URL;
import com.taikor.investment.view.RangeSeekBar;
import com.taikor.investment.view.RangeSeekBar2;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

/**
 * 灵活型
 * Created by Any on 2017/4/13.
 */
public class FlexibleActivity extends BaseActivity
        implements FlexibleGroupAdapter.DeleteItemListener, View.OnFocusChangeListener, TextView.OnEditorActionListener {

    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle;//标题
    @BindView(R.id.et_invest_money)
    EditText etInvestMoney;//可投资总金额
    @BindView(R.id.tv_income_pro)
    TextView tvIncomePro;//预期收益率
    @BindView(R.id.tv_flex_pro)
    TextView tvFlexPro;//可承受波动率
    @BindView(R.id.seek_bar1_flex)
    RangeSeekBar seekBar1Flex;//预期收益率拖动条
    @BindView(R.id.seek_bar2_flex)
    RangeSeekBar2 seekBar2Flex;//可承受波动率拖动条
    @BindView(R.id.rb_private)
    RadioButton rbPrivate;//私募
    @BindView(R.id.rb_blend)
    RadioButton rbBlend;//混合
    @BindView(R.id.rb_public)
    RadioButton rbPublic;//公募
    @BindView(R.id.tv_add_must_product)
    TextView tvAddMustProduct;
    @BindView(R.id.rv_flexible_product)
    RecyclerView rvFlexibleProduct;
    @BindView(R.id.et_group_name)
    EditText etGroupName;//组合名称

    private boolean success;
    private int productType = 1;
    private String groupName, investMoney;
    private FlexibleGroupAdapter mAdapter = null;
    private double expectedIncome = 0, volatilityIncome = 0;
    private ArrayList<SettingProduct> list = new ArrayList<>();
    private List<Products> postProducts = new ArrayList<>();//上传的产品
    private Map<String, String> idMap = new HashMap<>();
    private String TAG = "FlexibleActivity";

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

    @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 initView() {
        initSeekBar();
        tvBarTitle.setText("灵活型组合推荐");
        etGroupName.setOnFocusChangeListener(this);
        etInvestMoney.setOnEditorActionListener(this);
    }

    @Override
    public void initData() {
        rvFlexibleProduct.setLayoutManager(new GridLayoutManager(this, 2));//两列
        mAdapter = new FlexibleGroupAdapter(this);
        mAdapter.setData(list, null);
        rvFlexibleProduct.setAdapter(mAdapter);
    }

    /**
     * 初始化拖动条
     */
    public void initSeekBar() {
        int width = ScreenUtils.getScreenWidth(this);
        int height = ScreenUtils.getScreenHeight(this);
        seekBar1Flex.setWidthHeight(width, height * 2 / 15);// 重新绘制宽高，否则自定义控件放在ScrollView里面没有高度不显示
        seekBar2Flex.setWidthHeight(width, height * 2 / 15);
        seekBar2Flex.setValue(5);//起始点
        seekBar1Flex.setValue(5);

        //预期收益
        seekBar1Flex.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float min, float max, boolean isFromUser) {
                if (min <= 50) {
                    expectedIncome = min / 5;
                    tvIncomePro.setText("预期收益：" + DegreeUtils.setDoubleTwo(expectedIncome) + "%");
                } else if (min <= 66) {
                    expectedIncome = min / 3.3;
                    tvIncomePro.setText("预期收益：" + DegreeUtils.setDoubleTwo(expectedIncome) + "%");
                } else {
                    expectedIncome = min;
                    tvIncomePro.setText("预期收益：" + DegreeUtils.setDoubleTwo(expectedIncome) + "%");
                }
            }
        });

        //可承受波动率
        seekBar2Flex.setOnRangeChangedListener(new RangeSeekBar2.OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar2 view, float min, float max, boolean isFromUser) {
                volatilityIncome = min;
                tvFlexPro.setText("可承受波动率：" + DegreeUtils.setDoubleTwo(volatilityIncome) + "%");
            }
        });
    }

    // 焦点改变获取组合名称
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            String s1 = etGroupName.getText().toString();
            if (TextUtils.isEmpty(s1))
                ToastUtils.showShort(FlexibleActivity.this, "请输入组合名称");
            else
                groupName = s1;
        }
    }

    //   完成获取投资金额
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            String s = etInvestMoney.getText().toString();
            if (TextUtils.isEmpty(s))
                ToastUtils.showShort(FlexibleActivity.this, "请输入投资金额");
            else
                investMoney = s;
        }

        return false;
    }

    @OnClick({R.id.tv_bar_back, R.id.tv_add_must_product, R.id.rb_private, R.id.rb_public, R.id.rb_blend, R.id.bt_flexible_group})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bar_back:
                finish();
                break;
            case R.id.rb_private:
                productType = 1;
                break;
            case R.id.rb_blend:
                productType = 2;
                break;
            case R.id.rb_public:
                productType = 3;
                break;
            case R.id.tv_add_must_product://添加条目
                list.add(list.size(), new SettingProduct());
                mAdapter.notifyItemInserted(list.size());
                break;
            case R.id.bt_flexible_group:
                makeGroup();
                break;
        }
    }

    /**
     * 生成组合
     */
    private void makeGroup() {
        if (TextUtils.isEmpty(groupName) || TextUtils.isEmpty(investMoney)) {
            ToastUtils.showShort(FlexibleActivity.this, "组合名称和投资金额不能为空！");
            return;
        }
            postGroupData(Constant_URL.NEW_GROUP);
    }

    //上传组合
    public void postGroupData(String url) {
        Groups groups = getGroups();

        Gson gson = new Gson();
        String s = gson.toJson(groups);
        Log.d(TAG, "创建的组合：" + s);
        OkHttpUtils.postString()
                .url(url)
                .content(s)
                .mediaType(MediaType.parse("application/json;charset=utf-8"))
                .build().execute(new Callback<OutputResult>() {
            @Override
            public OutputResult parseNetworkResponse(Response response, int id) throws Exception {
                Gson gson = new Gson();
                return gson.fromJson(response.body().string(), OutputResult.class);
            }

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

            }

            @Override
            public void onResponse(OutputResult response, int id) {
                if (response == null) {
                    return;
                }
                success = response.isSuccess();
                Log.d(TAG, "创建的结果：" + response.getMessage());
                if (success) {
                    //埋点
                    TAnalytics.onClick("createGroup", "2");
                    Intent intent = new Intent(FlexibleActivity.this, GroupDescActivity.class);
                    intent.putExtra("itemId", response.getData().getGroupId());
                    intent.putExtra("from","flexiblePage");
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    // 获取Groups
    private Groups getGroups() {
        addProduct();
        Groups groups = new Groups();
        groups.setUserID("20000");
        groups.setPortfolioName(groupName);
        groups.setExpectedProfit(expectedIncome);
        groups.setMaxVolatility(volatilityIncome);
        groups.setInvestmentAmount(Double.valueOf(investMoney));
        groups.setType(2);
        groups.setProductType(productType);
        //目前还没有添加数据
        groups.setProducts(postProducts);
        return groups;
    }

    private void addProduct() {
        RecyclerView.LayoutManager manager = rvFlexibleProduct.getLayoutManager();
        View view;
        FlexibleGroupAdapter.MyViewHolder childViewHolder;
        for (int i = 0; i < list.size(); i++) {
            view = manager.getChildAt(i);
            childViewHolder = (FlexibleGroupAdapter.MyViewHolder) rvFlexibleProduct.getChildViewHolder(view);
            Products pros = new Products();
            String name = childViewHolder.tvProduct.getText().toString();
            Set<String> set = idMap.keySet();

            if (!TextUtils.isEmpty(name)) {
                String id = null;
                for (String s : set) {
                    if (name.equals(s)) {//通过比较名字，相同的话，获取名字对应的id
                        id = idMap.get(s);
                        break;
                    }
                }
                pros.setProductName(name);
                pros.setProductID(id);
                Double totalMoney = Double.valueOf(investMoney);
                double perMoney = totalMoney / list.size();
                pros.setPurchaseAmount(perMoney);
                pros.setProportion(perMoney/totalMoney);
            }
            postProducts.add(pros);
        }
    }

    //设置产品名称，跳转到产品列表
    @Override
    public void setProductName(int position) {
        Intent intent = new Intent(FlexibleActivity.this, ProductSearchActivity.class);
        intent.putExtra("jump_desc", false);
        intent.putExtra("type", "setting");
        intent.putExtra("setting_position", position);
        startActivity(intent);
    }

    //获取从产品列表传递的数，并显示
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveData(SettingProductEvent event) {
        RecyclerView.LayoutManager manager = rvFlexibleProduct.getLayoutManager();
        //获取数据
        String productName = event.getProductName();
        String productId = event.getProductId();
        idMap.put(productName, productId);
        int position = event.getPosition();
        View view = manager.getChildAt(position);
        FlexibleGroupAdapter.MyViewHolder childViewHolder = (FlexibleGroupAdapter.MyViewHolder) rvFlexibleProduct.getChildViewHolder(view);

        //设置界面
        childViewHolder.tvProduct.setText(productName);
    }

    //删除产品
    @Override
    public void delete(int position) {
        List<String> nameList = getList(rvFlexibleProduct.getChildCount());
        list.remove(position);
        nameList.remove(position);
        mAdapter.setData(list, nameList);
    }

    //获取产品名称的集合
    public List<String> getList(int size) {
        List<String> nameList = new ArrayList<>();
        RecyclerView.LayoutManager layoutManager = rvFlexibleProduct.getLayoutManager();
        FlexibleGroupAdapter.MyViewHolder viewHolder;
        View view;
        if (size != 0) {
            for (int i = 0; i < size; i++) {
                view = layoutManager.getChildAt(i);
                viewHolder = (FlexibleGroupAdapter.MyViewHolder) rvFlexibleProduct.getChildViewHolder(view);
                String name = viewHolder.tvProduct.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    nameList.add("");
                } else {
                    nameList.add(name);
                }
            }
        }
        return nameList;
    }

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

    @Override
    protected void onPause() {
        super.onPause();
//        TAnalytics.onPageLoad("flexiblePage", "groupPage", "", "");
    }
}