package com.taikor.investment.modules.group;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.taikor.investment.MainActivity;
import com.taikor.investment.R;
import com.taikor.investment.adapter.FixedProductAdapter;
import com.taikor.investment.adapter.MustProductAdapter;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.bean.CostProduct;
import com.taikor.investment.bean.Groups;
import com.taikor.investment.bean.OutputResult;
import com.taikor.investment.bean.Products;
import com.taikor.investment.event.BooleanEvent;
import com.taikor.investment.event.FixedProductEvent;
import com.taikor.investment.event.MustProductEvent;
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.yanzhenjie.recyclerview.swipe.Closeable;
import com.yanzhenjie.recyclerview.swipe.OnSwipeMenuItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenu;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuItem;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
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 GuaranteedActivity extends BaseActivity implements FixedProductAdapter.FixedListener
        , MustProductAdapter.MustListener, View.OnFocusChangeListener {

    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle;//标题
    @BindView(R.id.et_total_money)
    EditText etTotalMoney;//总金额
    @BindView(R.id.rv_fixed_product)
    SwipeMenuRecyclerView rvFixedProduct;
    @BindView(R.id.tv_base_income)
    TextView tvBaseIncome;//固定产品的基础收益
    @BindView(R.id.tv_invest_money1)
    TextView tvFixedTotalMoney1;//固定产品合计金额
    @BindView(R.id.seek_bar)
    RangeSeekBar seekBar;
    @BindView(R.id.tv_set_eval_income)
    TextView tvSetEvalIncome;//用户设置的预期收益>基础收益
    @BindView(R.id.tv_invest_money2)
    TextView tvInvestMoney;//可配置金额
    @BindView(R.id.rv_must_product)
    SwipeMenuRecyclerView rvMustProduct;
    @BindView(R.id.tv_eval_income)
    TextView tvEvalIncome;//计算出来的预期收益，用来匹配产品库
    @BindView(R.id.tv_left_money)
    TextView tvLeftMoney;//剩下的投资金额
    @BindView(R.id.tv_add_fixed)
    TextView tvAddFixed;//添加固定产品
    @BindView(R.id.tv_add_must)
    TextView tvAddMust;//添加必选产品
    @BindView(R.id.et_group_name)
    EditText etGroupName;//组合名称

    private boolean success;
    private String groupName;
    private FixedProductAdapter fixedAdapter;
    private MustProductAdapter mustAdapter;
    private List<Products> fixedProductList = new ArrayList<>();//上传的数据
    private List<Products> mustProductList = new ArrayList<>();//上传的数据

    //用来记录计算的金额
    private double total_money = 0, //可投资总金额
            invest_money = 0, //可配置金额
            left_money = 0, //剩余投资金额
            base_income = 0, //基础收益率
            set_income = 0, //seek bar设置的预期收益 
            eval_income = 0;//剩余金额对应的预期收益
    //列表的条目
    private List<CostProduct> fixedList = new ArrayList<>(), mustList = new ArrayList<>();
    //记录产品ID
    private Map<String, String> fixedID = new HashMap<>(), mustID = new HashMap<>();
    public String TAG = "GuaranteedActivity";

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

    @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() {
        initProductData();
        initSeekBar();
        tvBarTitle.setText("保本型组合推荐");
        etTotalMoney.setOnFocusChangeListener(this);
        etGroupName.setOnFocusChangeListener(this);
    }

    /**
     * 初始化数据
     */
    @Override
    public void initData() {
        //固定产品和必选产品：1，初始化1条  2，必须有1条不能删除
        fixedList.add(0, new CostProduct());
        fixedAdapter.setData(fixedList);
        rvFixedProduct.setAdapter(fixedAdapter);

        mustList.add(0, new CostProduct());
        mustAdapter.setData(mustList);
        rvMustProduct.setAdapter(mustAdapter);
    }

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

        //监听进度的拖动
        seekBar.setOnRangeChangedListener(new RangeSeekBar.OnRangeChangedListener() {
            @Override
            public void onRangeChanged(RangeSeekBar view, float min, float max, boolean isFromUser) {
                if (min <= 50) {
                    set_income = min / 5;
                    tvSetEvalIncome.setText(DegreeUtils.setDoubleTwo(set_income) + "%");
                    tvEvalIncome.setText(DegreeUtils.setDoubleTwo(set_income) + "%");
                } else if (min <= 66) {
                    set_income = min / 3.3;
                    tvSetEvalIncome.setText(DegreeUtils.setDoubleTwo(set_income) + "%");
                    tvEvalIncome.setText(DegreeUtils.setDoubleTwo(set_income) + "%");
                } else {
                    set_income = min;
                    tvSetEvalIncome.setText(DegreeUtils.setDoubleTwo(set_income) + "%");
                    tvEvalIncome.setText(DegreeUtils.setDoubleTwo(set_income) + "%");
                }
            }
        });
    }

    /**
     * 初始化产品
     */
    public void initProductData() {
        fixedAdapter = new FixedProductAdapter(this);
        LinearLayoutManager fixedLayout = new LinearLayoutManager(this);
        fixedLayout.setOrientation(LinearLayoutManager.VERTICAL);
        rvFixedProduct.setLayoutManager(fixedLayout);
        rvFixedProduct.setSwipeMenuCreator(swipeMenuCreator);
        rvFixedProduct.setSwipeMenuItemClickListener(menuItemClickListener1);

        mustAdapter = new MustProductAdapter(this);
        LinearLayoutManager mustLayout = new LinearLayoutManager(this);
        mustLayout.setOrientation(LinearLayoutManager.VERTICAL);
        rvMustProduct.setLayoutManager(mustLayout);
        rvMustProduct.setSwipeMenuCreator(swipeMenuCreator);
        rvMustProduct.setSwipeMenuItemClickListener(menuItemClickListener2);
    }

    /**
     * 菜单创建器
     */
    private SwipeMenuCreator swipeMenuCreator = new SwipeMenuCreator() {
        @Override
        public void onCreateMenu(SwipeMenu swipeLeftMenu, SwipeMenu swipeRightMenu, int viewType) {
            int width = 180;

            // MATCH_PARENT 自适应高度，保持和内容一样高；也可以指定菜单具体高度，也可以用WRAP_CONTENT
            int height = ViewGroup.LayoutParams.MATCH_PARENT;

            {//在右侧添加
                SwipeMenuItem deleteItem = new SwipeMenuItem(GuaranteedActivity.this)
                        .setBackgroundDrawable(R.drawable.bg_text_red)
                        .setImage(R.drawable.delete3)
//                        .setText("删除") // 文字，还可以设置文字颜色，大小等。。
                        .setTextColor(Color.WHITE)
                        .setWidth(width)
                        .setHeight(height);
                swipeRightMenu.addMenuItem(deleteItem);// 添加一个按钮到右侧侧菜单。
            }
        }
    };

    /**
     * 菜单点击监听——固定产品
     */
    private OnSwipeMenuItemClickListener menuItemClickListener1 = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView
         *                        #RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。

            if (menuPosition == 0) {// 删除按钮被点击。
                if (adapterPosition == 0) {
                    ToastUtils.showShort(GuaranteedActivity.this, "第一条不能被删除！");
                    return;
                }
                //更新索引
                fixedList.remove(adapterPosition);
                fixedAdapter.notifyItemRemoved(adapterPosition);
                //更新计算的值
                updateFixed();
            }
        }
    };

    /**
     * 菜单点击监听——必选产品
     */
    private OnSwipeMenuItemClickListener menuItemClickListener2 = new OnSwipeMenuItemClickListener() {
        /**
         * Item的菜单被点击的时候调用。
         * @param closeable       closeable. 用来关闭菜单。
         * @param adapterPosition adapterPosition. 这个菜单所在的item在Adapter中position。
         * @param menuPosition    menuPosition. 这个菜单的position。比如你为某个Item创建了2个MenuItem，那么这个position可能是是 0、1，
         * @param direction       如果是左侧菜单，值是：SwipeMenuRecyclerView#LEFT_DIRECTION，如果是右侧菜单，值是：SwipeMenuRecyclerView
         *                        #RIGHT_DIRECTION.
         */
        @Override
        public void onItemClick(Closeable closeable, int adapterPosition, int menuPosition, int direction) {
            closeable.smoothCloseMenu();// 关闭被点击的菜单。

            if (menuPosition == 0) {// 删除按钮被点击。
                if (adapterPosition == 0) {
                    ToastUtils.showShort(GuaranteedActivity.this, "第一条不能被删除！");
                    return;
                }
                //更新索引
                mustList.remove(adapterPosition);
                mustAdapter.notifyItemRemoved(adapterPosition);
                //更新计算的值
                updateMust();
            }
        }
    };

    @OnClick({R.id.tv_bar_back, R.id.bt_guaranteed_group, R.id.tv_add_fixed, R.id.tv_add_must})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bar_back:
                finish();
                break;
            case R.id.tv_add_fixed:
                fixedList.add(fixedList.size(), new CostProduct());
                fixedAdapter.notifyItemInserted(fixedList.size());
                break;
            case R.id.tv_add_must:
                mustList.add(mustList.size(), new CostProduct());
                mustAdapter.notifyItemInserted(mustList.size());
                break;
            case R.id.bt_guaranteed_group://生成投资组合
                makeGroup();
                break;
        }
    }

    //失去焦点，获取组合名称和投资总金额
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) {
            switch (v.getId()) {
                case R.id.et_group_name:
                    String s = etGroupName.getText().toString();
                    if (TextUtils.isEmpty(s)) {
                        ToastUtils.showShort(GuaranteedActivity.this, "请输入组合名称");
                    } else {
                        groupName = s;
                    }
                    break;
                case R.id.et_total_money:
                    String s1 = etTotalMoney.getText().toString();
                    if (TextUtils.isEmpty(s1)) {
                        ToastUtils.showShort(GuaranteedActivity.this, "请输入投资金额");
                    } else {
                        total_money = Double.valueOf(s1);
                    }
                    break;
            }
        }
    }

    /**
     * 生成投资组合
     */
    private void makeGroup() {
        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);
//                Log.d(TAG,response.body().string());
//                return null;
            }

            @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, "success：" + response.isSuccess());
                Log.d(TAG, "创建的结果：" + response.getMessage());
                if (success) {
                    //埋点
                    TAnalytics.onClick("createGroup", "1");
                    Intent intent2 = new Intent(GuaranteedActivity.this, GroupDescActivity.class);
                    intent2.putExtra("itemId", response.getData().getGroupId());
                    intent2.putExtra("from","breakPage");
                    startActivity(intent2);
                    finish();
                }
            }
        });
    }

    // 获取Group
    private Groups getGroups() {
        //添加固定产品
        addFixedProduct();
        //添加必选产品
        addMustProduct();

        Groups groups = new Groups();
        groups.setUserID("20000");
        groups.setPortfolioName(groupName);
        groups.setExpectedProfit(set_income);
        groups.setInvestmentAmount(total_money);
        groups.setType(1);
        groups.setProducts(fixedProductList);
        groups.setProducts(mustProductList);
        return groups;
    }

    private void addMustProduct() {
        RecyclerView.LayoutManager mustManager = rvMustProduct.getLayoutManager();
        View view2;
        MustProductAdapter.MustViewHolder viewHolder;
        for (int i = 0; i < mustList.size(); i++) {
            Products pros = new Products();

            view2 = mustManager.getChildAt(i);
            viewHolder = (MustProductAdapter.MustViewHolder) rvMustProduct.getChildViewHolder(view2);
            String name = viewHolder.productName.getText().toString();
            String money = viewHolder.productMoney.getText().toString();
            Set<String> set = mustID.keySet();

            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(money)) {
                String id = null;
                for (String s : set) {
                    if (name.equals(s)) {//通过比较名字，相同的话，获取名字对应的id
                        id = mustID.get(s);
                        break;
                    }
                }

                pros.setProductID(id);//传递过来
                pros.setProductName(name);
                pros.setPurchaseAmount(Double.valueOf(money));
                pros.setProportion(Double.valueOf(money) / total_money);
            }
            mustProductList.add(pros);
        }
    }

    private void addFixedProduct() {
        RecyclerView.LayoutManager fixedManager = rvFixedProduct.getLayoutManager();
        FixedProductAdapter.FixedViewHolder holder;
        View view;

        for (int i = 0; i < fixedList.size(); i++) {
            Products pros = new Products();

            view = fixedManager.getChildAt(i);
            holder = (FixedProductAdapter.FixedViewHolder) rvFixedProduct.getChildViewHolder(view);
            String name = holder.productName.getText().toString();
            String money = holder.productMoney.getText().toString();
            Set<String> set = fixedID.keySet();

            //防止删除空条目异常
            if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(money)) {
                String id = null;
                for (String s : set) {
                    if (name.equals(s)) {//通过比较名字，相同的话，获取名字对应的id
                        id = fixedID.get(s);
                        break;
                    }
                }
                pros.setProductID(id);//传递过来
                pros.setProductName(name);
                pros.setPurchaseAmount(Double.valueOf(money));
                pros.setProportion(Double.valueOf(money) / total_money);
            }

            fixedProductList.add(pros);
        }
    }

    /**
     * 设置固定产品名称
     */
    @Override
    public void setFixedName(int pos) {
        Intent productListIntent = new Intent(GuaranteedActivity.this, ProductSearchActivity.class);
        productListIntent.putExtra("jump_desc", false);
        productListIntent.putExtra("type", "fixed");
        productListIntent.putExtra("fixed_position", pos);
        startActivity(productListIntent);
    }

    //设置必选产品名称
    @Override
    public void setMustName(int position) {
        Intent productListIntent = new Intent(GuaranteedActivity.this, ProductSearchActivity.class);
        productListIntent.putExtra("jump_desc", false);
        productListIntent.putExtra("type", "must");
        productListIntent.putExtra("must_position", position);
        startActivity(productListIntent);
    }

    // 处理数据：固定产品
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveData(FixedProductEvent event) {
        //获取数据
        String productName = event.getProductName();
        String productId = event.getProductId();
        double income = event.getIncome();
        int position = event.getPosition();
        fixedID.put(productName, productId);

        RecyclerView.LayoutManager manager = rvFixedProduct.getLayoutManager();
        View view = manager.getChildAt(position);
        FixedProductAdapter.FixedViewHolder childViewHolder = (FixedProductAdapter.FixedViewHolder) rvFixedProduct.getChildViewHolder(view);

        //设置界面
        childViewHolder.productName.setText(productName);
        childViewHolder.productTime.setText("1年");
        if (income > 0) {
            childViewHolder.productIncome.setTextColor(Color.parseColor("#FD3642"));
        } else {
            childViewHolder.productIncome.setTextColor(Color.parseColor("#07B60E"));
        }
        childViewHolder.productIncome.setText(DegreeUtils.setDoubleTwo(income) + "%");
        //更新计算的值
//        updateFixed();
    }

    //处理数据：必选产品
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void processData(MustProductEvent event) {
        //获取数据
        String productName = event.getProductName();
        String productId = event.getProductId();
        double income = event.getIncome();
        int position = event.getPosition();

        mustID.put(productName, productId);
        RecyclerView.LayoutManager manager = rvMustProduct.getLayoutManager();
        View view = manager.getChildAt(position);
        MustProductAdapter.MustViewHolder viewHolder = (MustProductAdapter.MustViewHolder) rvMustProduct.getChildViewHolder(view);
        //设置界面
        viewHolder.productName.setText(productName);
        viewHolder.productTime.setText("1年");
        if (income > 0) {
            viewHolder.productIncome.setTextColor(Color.parseColor("#FD3642"));
        } else {
            viewHolder.productIncome.setTextColor(Color.parseColor("#07B60E"));
        }
        viewHolder.productIncome.setText(DegreeUtils.setDoubleTwo(income) + "%");
        //更新计算的值
//        updateMust();
    }

    /**
     * 设置固定产品的金额
     */
    @Override
    public void setFixedMoney() {
        updateFixed();
    }

    /**
     * 更新固定产品的值
     */
    private void updateFixed() {
        double moneySum = 0, money_income_sum = 0;

        RecyclerView.LayoutManager manager = rvFixedProduct.getLayoutManager();
        FixedProductAdapter.FixedViewHolder holder;
        View view;

        for (int i = 0; i < fixedList.size(); i++) {
            view = manager.getChildAt(i);
            holder = (FixedProductAdapter.FixedViewHolder) rvFixedProduct.getChildViewHolder(view);
            String money = holder.productMoney.getText().toString();
            String income = holder.productIncome.getText().toString();
            //防止删除空条目异常
            if (!money.equals("——") && !income.equals("——")) {
                double childInvestMoney = Double.valueOf(money);
                String[] split = income.split("%");
                double childIncome = Double.valueOf(split[0]);

                //金额总和
                moneySum = moneySum + childInvestMoney;
                //金额 乘以 收益率的总和
                money_income_sum = money_income_sum + childInvestMoney * childIncome / 100;
                //基础收益率=金额 乘以 收益率的总和/金额总和
                base_income = money_income_sum / moneySum;
                //可配置金额=金额总和 乘以 基础收益率
                invest_money = moneySum * base_income / (1 + base_income);
            }
        }
        if (moneySum > total_money) {
            ToastUtils.showShort(GuaranteedActivity.this, "不能大于总的投资金额,请重新设置！");
        }
        //更新View
        tvBaseIncome.setText(DegreeUtils.setDoubleTwo(base_income * 100) + "%");
        tvFixedTotalMoney1.setText(String.valueOf(moneySum));
        tvInvestMoney.setText(DegreeUtils.setDoubleTwo(invest_money));
    }

    /**
     * 设置必选产品的金额
     */
    @Override
    public void setMustMoney() {
        updateMust();
    }

    /**
     * 更新必选产品的值
     */
    private void updateMust() {
        double moneySum = 0, money_income_sum = 0;

        RecyclerView.LayoutManager manager = rvMustProduct.getLayoutManager();
        View view;
        MustProductAdapter.MustViewHolder viewHolder;

        for (int i = 0; i < mustList.size(); i++) {
            view = manager.getChildAt(i);
            viewHolder = (MustProductAdapter.MustViewHolder) rvMustProduct.getChildViewHolder(view);
            String money = viewHolder.productMoney.getText().toString();
            String income = viewHolder.productIncome.getText().toString();
            if (!money.equals("——") && !income.equals("——")) {
                double childInvestMoney = Double.valueOf(money);
                String[] split = income.split("%");
                double childIncome = Double.valueOf(split[0]);
                //金额总和
                moneySum = moneySum + childInvestMoney;
                //金额 乘以 收益率的总和
                money_income_sum = money_income_sum + childInvestMoney * childIncome / 100;
                //剩余投资金额=可投资金额-金额
                left_money = invest_money - moneySum;
                //预期收益=(可投资金额*用户设置预期收益-金额1*收益1-金额2*收益2)/剩余投资金额
                eval_income = (invest_money * set_income / 100 - money_income_sum) / left_money;
            }
            //更新View
            tvLeftMoney.setText(DegreeUtils.setDoubleTwo(left_money));
            tvEvalIncome.setText(DegreeUtils.setDoubleTwo(eval_income * 100) + "%");
        }
    }

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

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