package com.rv.rvmine.member;

import android.annotation.SuppressLint;
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.rvmine.R;
import com.rv.rvmine.R2;
import com.rv.rvmine.member.adapter.MemberListAdapter;
import com.rv.rvmine.member.bean.BeanTourOrderPay;
import com.rv.rvmine.bean.MemberListBean;
import com.rv.rvmine.member.bean.MemberOrderBean;
import com.rv.rvmine.member.bean.MemberOrderPostBodyBean;
import com.rv.rvmine.member.bean.PayBodyBean;
import com.rv.rvmine.bean.UserInfoBean;
import com.rv.rvmine.member.presenter.MemberPresenter;
import com.rv.rvmine.personal.IDCardCertificationActivity;
import com.tencent.mm.opensdk.modelpay.PayReq;
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;

    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 {
                        finish();
                    }
                });

        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(), 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})
    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) {
            //登录
            startActivityForResult(LoginRvActivity.getIntent(MemberCenterActivity.this), REQUEST_LOGIN);
        } else if (id == R.id.tv_verified) {
            //实名认证
            if (isLogin()) return;
            startActivityForResult(IDCardCertificationActivity.getIntent(MemberCenterActivity.this), REQUEST_VERIFIED);
        }
    }

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


    @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 可免费租车 (天)");
                tvFreeDay.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) {
                        ivMember.setImageResource(R.drawable.mycenter_icon_goldmembership_1);
                    } else {
                        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) {

            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();
        }
    };
}
