package com.rv.member;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.ui.image.round.RoundImageView;
import com.frame.base.bus.PaymentFailedEvent;
import com.frame.base.bus.PaymentSuccessfulEvent;
import com.frame.base.bus.RxBus;
import com.frame.base.url.Constance;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.util.ViewHolder;
import com.ruiwenliu.wrapper.util.glide.GlideManager;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.component.dialog.PaymentTypeSelection;
import com.rv.home.rv.module.ApiConfig;
import com.rv.home.rv.module.basic.BaseStatusActivity;
import com.rv.home.rv.module.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.main.home.order.OrderListActivity;
import com.rv.member.bean.MemberListBean;

import com.rv.member.adapter.MemberListAdapter;
import com.rv.member.bean.BeanTourOrderPay;
import com.rv.member.bean.MemberOrderBean;
import com.rv.member.bean.UserInfoBean;
import com.rv.member.presenter.MemberPresenter;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yuyife.okgo.OkGoUtil;

import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;


/*******
 * 会员中心
 * created by john
 */
public class MemberCenterActivity extends BaseStatusActivity<MemberPresenter> {

    private static final int REQUEST_LOGIN = 10000;
    private static final int REQUEST_VERIFIED = 10001;

    @BindView(R2.id.iv_avatar)
    RoundImageView ivAvatar;
    @BindView(R2.id.tv_nickname)
    TextView tvNickname;
    @BindView(R2.id.iv_member)
    ImageView ivMember;
    @BindView(R2.id.tv_login)
    TextView tvLogin;
    @BindView(R2.id.tv_verified)
    TextView tvVerified;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tv_consume_record)
    TextView tvConsumeRecord;
    @BindView(R2.id.tv_free_day)
    TextView tvFreeDay;
    @BindView(R2.id.tv_purchase_record)
    TextView tvPurchaseRecord;

    private MemberListAdapter adapter;
    private UserInfoBean.UserInfo info;
    private IWXAPI api;
    private int memberLevel = 0; // 会员等级

    public static Intent getIntent(Context context) {
        return new Intent(context, MemberCenterActivity.class);
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_member;
    }

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, Intent intent) {
        api = WXAPIFactory.createWXAPI(this, RvFrameConfig.APP_ID);
        titleView.setVisibility(View.GONE);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayout.VERTICAL, false));
        initRxBus();
    }

    @SuppressLint("CheckResult")
    private void initRxBus() {
        RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<PaymentSuccessfulEvent>() {
                    @Override
                    public void accept(PaymentSuccessfulEvent payEvent) throws Exception {
                        getUserData();
                    }
                });

        RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<PaymentFailedEvent>() {
                    @Override
                    public void accept(PaymentFailedEvent payEvent) throws Exception {
                        if (mActivity.getClass().equals(MemberCenterActivity.class)) {
                            ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
                            finish();
                        }
                    }
                });
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {

        switch (requestType) {
            case 0:
                if (adapter == null) {
                    adapter = new MemberListAdapter(((MemberListBean) result).getData(), memberLevel, MemberCenterActivity.this, payListener);
                    recyclerView.setAdapter(adapter);
                } else {
                    adapter.setDate(((MemberListBean) result).getData());
                }
                break;
            case 1:
                setUserInfoData((UserInfoBean) result);
                break;
            case 2:
                MemberOrderBean orderBean = (MemberOrderBean) result;
                mPresenter.orderPay(orderBean.getData().getNo(), payType, 1);
                break;
            case 3:
                mPresenter.pay(MemberCenterActivity.this, api, (BeanTourOrderPay) result);
                break;
        }
    }


    @OnClick({R2.id.iv_avatar, R2.id.tv_login, R2.id.tv_verified, R2.id.iv_title, R2.id.tv_consume_record, R2.id.tv_purchase_record, R2.id.tv_free_day})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.iv_avatar) {
            //头像
            if (!isLogin()) return;
        } else if (id == R.id.tv_login) {
            if (!isLogin()) return;
        } else if (id == R.id.tv_verified) {
            //实名认证
            if (!isLogin()) return;
            ComponentName componentName = new ComponentName(MemberCenterActivity.this, "com.rv.rvmine.personal.IDCardCertificationActivity");
            Intent intent = new Intent();
            intent.setComponent(componentName);
            startActivityForResult(intent, REQUEST_VERIFIED);
        } else if (id == R.id.iv_title) {
            finish();
        } else if (id == R.id.tv_consume_record) {
            startActivity(new Intent(MemberCenterActivity.this, ConsumeRecordActivity.class));
        } else if (id == R.id.tv_purchase_record) {
            startActivity(new Intent(MemberCenterActivity.this, PurchaseRecordActivity.class));
        } else if (id == R.id.tv_free_day) {
//            startActivity(new Intent(MemberCenterActivity.this, FreesDayActivity.class));
        }
    }

    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            startActivityForResult(LoginRvActivity.getIntent(MemberCenterActivity.this), REQUEST_LOGIN);
            return false;
        }
        return true;
    }


    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        getUserData();
        getMemberData();
    }

    /**********
     * 获取会员中心信息
     */
    private void getMemberData() {
        mPresenter.getData(RvFrameConfig.ADMIN_POST, 0, ApiConfig.HTTP_URL_MEMBER_LIST, MemberListBean.class, true);
    }

    /**
     * 获取用户信息请求
     */
    private void getUserData() {
        Map<String, Object> headMap = new LinkedHashMap<>();
        if (OkGoUtil.getToken() != null) {
            headMap.put("Authorization", OkGoUtil.getToken());
            mPresenter.getDataHead(RvFrameConfig.ADMIN_POST, 1, ApiConfig.HTTP_URL_APP_USER_INFO, UserInfoBean.class, headMap, true);
        }
    }

    private void setUserInfoData(UserInfoBean infoBean) {
        if (infoBean != null) {
            info = infoBean.getData();
            if (info != null) {
                GlideManager.getInstance(this).loadImage(info.getHeadimgurl(), ivAvatar);
                tvNickname.setText(info.getUsername());
                if (info.getCertificationStatus() == 0) { //实名认证状态:0-未认证，1-已认证
                    tvVerified.setText("未实名认证");
                    tvVerified.setEnabled(true);
                } else if (info.getCertificationStatus() == 1) {
                    tvVerified.setText("已实名认证");
                    tvVerified.setEnabled(false);
                }

                tvConsumeRecord.setText(info.getPayCount() + "\n 消费记录");
                tvFreeDay.setText(info.getRentFreeDays() + "\n 可免费租车 (天)");
                tvPurchaseRecord.setText(info.getBuyCount() + "\n 购买记录 (次)");
            }

            if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                tvNickname.setVisibility(View.GONE);
                ivMember.setVisibility(View.GONE);
                tvLogin.setVisibility(View.VISIBLE);
                tvVerified.setVisibility(View.GONE);
            } else {
                tvNickname.setVisibility(View.VISIBLE);
                tvLogin.setVisibility(View.GONE);
                tvVerified.setVisibility(View.VISIBLE);
                if (info != null) {
                    ivMember.setVisibility(View.VISIBLE);

                    if (info.getIsMember() == 0) {
                        memberLevel = 0;
                        if (adapter != null) {
                            adapter.setMemberLevel(memberLevel);
                        }
                        ivMember.setImageResource(R.drawable.mycenter_icon_goldmembership_1);
                    } else {
                        memberLevel = info.getMemberLevel();
                        if (adapter != null) {
                            adapter.setMemberLevel(memberLevel);
                        }
                        switch (info.getMemberLevel()) {
                            case 1:
                                ivMember.setImageResource(R.drawable.mycenter_icon_ord_membership);
                                break;
                            case 2:
                                ivMember.setImageResource(R.drawable.mycenter_icon_goldmembership);
                                break;
                            case 3:
                                ivMember.setImageResource(R.drawable.mycenter_icon_sil_membership);
                                break;
                            default:
                                break;
                        }
                    }
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOGIN) {
            getUserData();
            getMemberData();
        } else if (requestCode == REQUEST_VERIFIED) {
            getUserData();
        }
    }


    private int payType = 1;
    private MemberListAdapter.PayListener payListener = new MemberListAdapter.PayListener() {
        @Override
        public void pay(final MemberListBean.MemberCard card) {
            if (!isLogin()) return;

            new PaymentTypeSelection(MemberCenterActivity.this) {
                @Override
                public void helper(final ViewHolder helper) {
                    super.helper(helper);
                    helper.setText(R.id.tv_amount, String.format("￥%1$s", card.getPrice()));
                    helper.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            int i = v.getId();
                            if (i == R.id.iv_close) {
                                dismiss();
//                                createOrder(name, phone, 0);
                            } else if (i == R.id.ll_item_wechat) {
                                payType = 1;
                                helper.setChecked(R.id.rb_wechat, true);
                                helper.setChecked(R.id.rb_alipay, false);
                            } else if (i == R.id.ll_item_alipay) {
                                showToast("该功能还没有开通！");
//                                payType = 2 ;
//                                helper.setChecked(R.id.rb_wechat,false);
//                                helper.setChecked(R.id.rb_alipay,true);

                            } else if (i == R.id.tv_pay_immediately) {
                                dismiss();
                                mPresenter.createOrder(card, 2);
                            }
                        }
                    }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
                }
            }.show();
        }
    };
}
