package com.taikor.investment.modules.customer;

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

import com.google.gson.Gson;
import com.taikor.investment.MainActivity;
import com.taikor.investment.R;
import com.taikor.investment.adapter.RepoAdapter;
import com.taikor.investment.base.BaseActivity;
import com.taikor.investment.bean.Customers;
import com.taikor.investment.bean.OutputResult;
import com.taikor.investment.bean.Products;
import com.taikor.investment.bean.Repo;
import com.taikor.investment.event.BooleanEvent;
import com.taikor.investment.event.DataEvent;
import com.taikor.investment.modules.group.GroupDescActivity;
import com.taikor.investment.mylibrary.TAnalytics;
import com.taikor.investment.utils.DegreeUtils;
import com.taikor.investment.utils.Constant_URL;
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 butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * 持仓设置,第一次为空
 * Created by Any on 2017/4/12.
 */
public class SetStorageActivity extends BaseActivity {
    
    @BindView(R.id.tv_add_product)
    TextView tvAddProduct;//添加
    @BindView(R.id.tv_save)
    TextView tvSave;//保存
    @BindView(R.id.ll_no_exist_product)
    LinearLayout llNoExistProduct;//没有产品的页面
    @BindView(R.id.rv_product)
    SwipeMenuRecyclerView rvProduct;
    @BindView(R.id.ll_exist_product)
    LinearLayout llExistProduct;//添加产品后的页面
    @BindView(R.id.tv_bar_title)
    TextView tvBarTitle; //标题
    OutputResult result;

    private boolean success = false;
    private RepoAdapter mAdapter = null;
    private ArrayList<Repo> showData = new ArrayList<>();//显示产品的列表
    private ArrayList<Products> postData = new ArrayList<>();//上传的产品列表
    private static String customerName, customerSex, customerPhone, groupName, customerTag, customerRemark;

    public int getContentViewId() {
        return R.layout.activity_customer_set_storage;
    }

    @Override
    public void initView() {
        tvBarTitle.setText("持仓设置");
        llNoExistProduct.setVisibility(View.VISIBLE);
        tvSave.getBackground().setAlpha(125);

        mAdapter = new RepoAdapter();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        rvProduct.setLayoutManager(manager);
        rvProduct.setSwipeMenuCreator(swipeMenuCreator);
        rvProduct.setSwipeMenuItemClickListener(menuItemClickListener1);
        rvProduct.addItemDecoration((new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL)));
        //获取传递的数据
        getTransmitData();
    }

    /**
     * 菜单创建器
     */
    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(SetStorageActivity.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) {// 删除按钮被点击。
                //获取要移除的列表中的产品的id
                RecyclerView.LayoutManager layoutManager = rvProduct.getLayoutManager();
                View childAt = layoutManager.getChildAt(adapterPosition);
                RepoAdapter.RepoHolder childViewHolder = (RepoAdapter.RepoHolder) rvProduct.getChildViewHolder(childAt);
                String productId = childViewHolder.tvRepoFundId.getText().toString();
                //比较整个产品列表，移除相同id，对应的产品
                for (int i = 0; i < postData.size(); i++) {
                    if (productId.equals(postData.get(i).getProductID())) {
                        postData.remove(postData.get(i));
                        break;
                    }
                }
                //更新索引
                showData.remove(adapterPosition);
                mAdapter.notifyItemRemoved(adapterPosition);
                if (adapterPosition != showData.size())
                    mAdapter.notifyItemRangeChanged(adapterPosition, showData.size() - adapterPosition);

                //重新计算比例
                double sum = getTotalMoney(postData);
                for (int i = 0; i < showData.size(); i++) {
                    double proportion = showData.get(i).getMoney() / sum;
                    showData.get(i).setProportion(DegreeUtils.setDoubleTwo(proportion));
                }
            }
        }
    };

    /**
     * 获取传递过来的客户的信息
     */
    private void getTransmitData() {
        Intent intent = getIntent();
        boolean add_customer = intent.getBooleanExtra("add_customer", false);//添加客户跳转
        //如果是从新建客户跳转过来，清空之前的列表数据
        if (add_customer) {
            //获取从添加客户传递过来的客户数据
            customerName = intent.getStringExtra("customer_name");
            customerSex = intent.getStringExtra("customer_sex");
            customerPhone = intent.getStringExtra("customer_phone");
            groupName = intent.getStringExtra("group_name");
            customerTag = intent.getStringExtra("customer_tag");
            customerRemark = intent.getStringExtra("customer_remark");
        }
    }

    //获取基金详情传递过来的数据
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DataEvent event) {
        ArrayList<Products> list = event.getList();
        postData.clear();
        showData.clear();
        postData.addAll(list);
        //计算出总金额
        double sum = getTotalMoney(list);
        //获取显示的集合数据
        for (int i = 0; i < list.size(); i++) {
            Repo repo = new Repo();
            double purchaseAmount = list.get(i).getPurchaseAmount();
            double proportion = purchaseAmount / sum * 100;
            repo.setFund_id(list.get(i).getProductID());
            repo.setFund_name(list.get(i).getProductName());
            repo.setMoney(purchaseAmount);
            repo.setProportion(DegreeUtils.setDoubleTwo(proportion));
            showData.add(repo);
        }

        //设置数据
        if (showData.size() != 0) {
            mAdapter.setData(showData);
            rvProduct.setAdapter(mAdapter);
            llNoExistProduct.setVisibility(View.GONE);
            llExistProduct.setVisibility(View.VISIBLE);
            tvSave.getBackground().setAlpha(255);
        }
    }

    // 获取显示列表的总金额
    private double getTotalMoney(ArrayList<Products> list) {
        double totalMoney = 0;
        for (int i = 0; i < list.size(); i++) {
            totalMoney = totalMoney + list.get(i).getPurchaseAmount();
        }
        return totalMoney;
    }

    @OnClick({R.id.tv_bar_back, R.id.tv_add_product, R.id.tv_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_bar_back://返回新建客户页面
                finish();
                break;
            case R.id.tv_add_product://跳转基金列表
                Intent intent = new Intent(this, FundsActivity.class);
                intent.putExtra("repo", postData);
                startActivity(intent);
                break;
            case R.id.tv_save://跳转客户列表，新增一条数据
                if (showData.size() == 0) {
                    tvSave.setClickable(false);
                    return;
                }
                //上传一条数据
                postCustomerData(Constant_URL.NEW_CUSTOMER);
//                if(success){
//                    //埋点
//                    TAnalytics.onClick("createCustomer","userID");
//                    //发送消息，客户列表重新请求数据
//                    EventBus.getDefault().post(new BooleanEvent(success, "customer"));
//                    //跳转主页面，切换客户列表
//                    Intent mainIntent = new Intent(SetStorageActivity.this, MainActivity.class);
//                    mainIntent.putExtra("default_fragment", true);
//                    mainIntent.putExtra("fragment_position", "3");
//                    startActivity(mainIntent);
//                }
                break;
        }
    }

    //上传新建的客户数据
    public void postCustomerData(String url) {
        Customers customers = new Customers();
        customers.setUserID("20000");
        customers.setCustomerName(customerName);
        customers.setGender(customerSex);
        customers.setPhoneNumber(customerPhone);
        customers.setPortfolioName(groupName);
        customers.setTag(customerTag);
        customers.setRemarks(customerRemark);
        customers.setProducts(postData);
        //将Customers对象转成JSON字符串
        Gson gson = new Gson();
        final String toJson = gson.toJson(customers);

        OkHttpUtils.postString()
                .url(url)
                .content(toJson)
                .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("SetStorageActivity",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();
//                 result = response;
                Log.d("SetStorageActivity","结果："+response.isSuccess());
                Log.d("SetStorageActivity",response.getMessage());
                if (success) {
//                    //埋点
                    TAnalytics.onClick("createCustomer",toJson);
                    Intent mainIntent = new Intent(SetStorageActivity.this, CustomerDescActivity.class);
                    mainIntent.putExtra("itemId", response.getData().getGroupId());
                    mainIntent.putExtra("customerId", response.getData().getUserId());
                    mainIntent.putExtra("from", "createCustomerPage");
                    startActivity(mainIntent);
                    finish();
                }
            }
        });
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}



