package com.rv.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.util.Log;
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.ruiwenliu.wrapper.bean.UserInfoBean;
import com.rv.member.presenter.MemberPresenter;
import com.rv.component.utils.RvCache;
import com.rv.component.utils.CacheEnum;
import com.rv.tourism.bean.BeanTourOrderAliPay;
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.disposables.Disposable;
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;
    private static final int REQUEST_PAY = 10002;

    @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;
    @BindView(R2.id.tv_member)
    TextView tvMember;

    private MemberListAdapter adapter;
    private UserInfoBean.UserInfo info;
    private IWXAPI api;
    private int memberLevel = 0; // 会员等级
    private int freeUseDay = 0; // 免费租车天数
    private boolean verified = false; // 是否实名认证

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

//        MemberListBean listBean = MemberCache.getInstance(MemberCenterActivity.this).get();
        MemberListBean listBean = (MemberListBean) RvCache.getInstance(MemberCenterActivity.this).get(CacheEnum.MEMBER);
        if (listBean != null && listBean.getData() != null) {
            adapter = new MemberListAdapter(listBean.getData(), memberLevel, freeUseDay, MemberCenterActivity.this, payListener);
            recyclerView.setAdapter(adapter);
        }
        UserInfoBean bean = (UserInfoBean) RvCache.getInstance(MemberCenterActivity.this).get(CacheEnum.USER);
        if (bean != null) {
            setUserInfoData(bean);
        }
        initRxBus();
    }

    private Disposable disposableSuc;
    private Disposable disposableFail;


    @SuppressLint("CheckResult")
    private void initRxBus() {
        disposableSuc = RxBus.tObservable(PaymentSuccessfulEvent.class)
                .observeOn(Schedulers.io())
                .subscribe(new Consumer<PaymentSuccessfulEvent>() {
                    @Override
                    public void accept(PaymentSuccessfulEvent payEvent) throws Exception {
                        Class aClass = Class.forName("com.rv.rvmine.rxbusevent.UserInfoEvent");
                        RxBus.post(aClass.newInstance());
                        startActivityForResult(OrderListActivity.getIntent(MemberCenterActivity.this, 3), REQUEST_PAY);
                    }
                });

        disposableFail = 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();
                        }
                    }
                });
        Log.e("xxxxxxxxxxxxxx", disposableSuc == disposableFail ? "true" : "false");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (disposableSuc != null && !disposableSuc.isDisposed()) {
            disposableSuc.dispose();
        }

        if (disposableFail != null && !disposableFail.isDisposed()) {
            disposableFail.dispose();
        }
    }

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

        switch (requestType) {
            case 0:
                MemberListBean listBean = (MemberListBean) result;
                if (listBean != null && listBean.isRel() && listBean.getData() != null && !listBean.getData().isEmpty()) {
                    RvCache.getInstance(getApplicationContext()).save(listBean, CacheEnum.MEMBER);
//                    MemberCache.getInstance(getApplicationContext()).save(listBean);
                    if (adapter == null) {
                        adapter = new MemberListAdapter(listBean.getData(), memberLevel, freeUseDay, MemberCenterActivity.this, payListener);
                        recyclerView.setAdapter(adapter);
                    } else {
                        adapter.setDate(listBean.getData());
                    }
                }
                break;
            case 1:
                RvCache.getInstance(getApplicationContext()).save((UserInfoBean) result, CacheEnum.USER);
                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;
            case 4:
                mPresenter.aliPay(MemberCenterActivity.this,  (BeanTourOrderAliPay) 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;
            ARouter.getInstance().build(Constance.ACTIVITY_URL_IDCARDCERTIFICATION)
                    .navigation(this, 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;
    }

    private boolean isVerified() {
        if (!verified) {
            ARouter.getInstance().build(Constance.ACTIVITY_URL_IDCARDCERTIFICATION)
                    .navigation(this, REQUEST_VERIFIED);
        }
        return verified;
    }


    @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-已认证
                    verified = false;
                    tvVerified.setText("未实名认证");
                    tvVerified.setEnabled(true);
                } else if (info.getCertificationStatus() == 1) {
                    verified = true;
                    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);
                ((View) ivMember.getParent()).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) {

                    ((View) ivMember.getParent()).setVisibility(View.VISIBLE);
//                    ivMember.setVisibility(View.VISIBLE);
                    if (!TextUtils.isEmpty(info.getIcon()))
                        GlideManager.getInstance(getApplicationContext()).loadImage(info.getIcon(), ivMember);
                    freeUseDay = info.getRentFreeDays();
                    if (info.getIsMember() == 0) {
                        memberLevel = 0;
                        if (adapter != null) {
                            adapter.setMemberLevel(memberLevel, freeUseDay);
                        }
                        tvMember.setText("普通用户");
//                        ivMember.setImageResource(R.drawable.mycenter_icon_goldmembership_1);
                    } else {
                        memberLevel = info.getMemberLevel();
                        if (adapter != null) {
                            adapter.setMemberLevel(memberLevel, freeUseDay);
                        }
                        switch (info.getMemberLevel()) {
                            case 1:
                                tvMember.setText("普通会员");
                                break;
                            case 2:
                                tvMember.setText("黄金会员");
                                break;
                            case 3:
                                tvMember.setText("钻石会员");
                                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();
        } else if (requestCode == REQUEST_PAY) {
            getUserData();
            getMemberData();
        }
    }


    private int payType = 1;
    private MemberListAdapter.PayListener payListener = new MemberListAdapter.PayListener() {
        @Override
        public void pay(final MemberListBean.MemberCard card) {
            if (!isLogin()) return;
//            if (!isVerified()) 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();
                            } 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) {
                                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();
        }
    };
}
