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.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.Observer;
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.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.util.ViewHolder;
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.ui.login.LoginRvActivity;
import com.rv.home.rv.module.ui.main.home.order.OrderListActivity;
import com.rv.member.bean.MemberListBean;

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.member.view.MemberItemView;
import com.rv.member.view.MemberTopView;
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 io.reactivex.android.schedulers.AndroidSchedulers;
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.member_top_view)
    MemberTopView memberTopView;
    @BindView(R2.id.ll_cardview_content)
    LinearLayout ll_cardview_content;

    private IWXAPI api;
    private int memberLevel = 0; // 会员等级
    private int freeUseDay = 0; // 免费租车天数

    private boolean hasAgree = 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.setTitle("会员中心");
        UserInfoBean userInfoBean = (UserInfoBean) RvCache.getInstance().get(CacheEnum.USER);
        if (userInfoBean != null && userInfoBean.getData() != null) {
            memberLevel = userInfoBean.getData().getMemberLevel();
            freeUseDay = userInfoBean.getData().getRentFreeDays();
        }
        MemberListBean listBean = (MemberListBean) RvCache.getInstance().get(CacheEnum.MEMBER);
        if (listBean != null && listBean.getData() != null) {
            memberTopView.setData(listBean, memberLevel, freeUseDay, payListener);
            addMemberList(listBean);
        }


        memberTopView.setLoginListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isLogin();
            }
        });
        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");

        RxBus.tObservable(LoginSuccessfulEvent.class)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<LoginSuccessfulEvent>(disposable) {
                    @Override
                    public void onNext(LoginSuccessfulEvent event) {
                        getUserData();
                        getMemberData();
                    }
                });
    }

    @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().save(listBean, CacheEnum.MEMBER);
                    memberTopView.setData(listBean, memberLevel, freeUseDay, payListener);
                    addMemberList(listBean);
                }
                break;
            case 1:
                RvCache.getInstance().save((UserInfoBean) result, CacheEnum.USER);
                memberTopView.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;
        }
    }


    /**
     * 判断是否登录
     *
     * @return
     */
    private boolean isLogin() {
        if (TextUtils.isEmpty(OkGoUtil.getToken())) {
            startActivityForResult(LoginRvActivity.getIntent(MemberCenterActivity.this, 0), 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 addMemberList(MemberListBean listBean) {
        ll_cardview_content.removeAllViews();
        for (MemberListBean.MemberCard card : listBean.getData()) {
            MemberItemView view = new MemberItemView(this);
            view.setData(card);
//            view.setHasAgree(hasAgree);
            view.setListener(payListener);
            if (listBean.getData().indexOf(card) == listBean.getData().size() - 1)
                view.hiddenLine();
            ll_cardview_content.addView(view);
        }
    }

    @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 PayListener payListener = new PayListener() {
        @Override
        public void pay(final MemberListBean.MemberCard card, final String phone) {
            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();
                            } else if (i == R.id.ll_item_wechat) {
                                payType = 1;
                                helper.getView(com.rv.home.R.id.iv_wx_select).setSelected(true);
                                helper.getView(com.rv.home.R.id.iv_alipy_select).setSelected(false);
                            } else if (i == com.rv.home.R.id.ll_item_alipay) {
                                payType = 2;
                                helper.getView(com.rv.home.R.id.iv_wx_select).setSelected(false);
                                helper.getView(com.rv.home.R.id.iv_alipy_select).setSelected(true);

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

        @Override
        public void checkAgreement(boolean b) {
            hasAgree = b;
//            int count = ll_cardview_content.getChildCount();
//            if (count > 0) {
//                for (int i = 0; i < count; i++) {
//                    View view = ll_cardview_content.getChildAt(i);
//                    if (view instanceof MemberItemView) {
//                        ((MemberItemView) view).setHasAgree(hasAgree);
//                    }
//                }
//            }
        }
    };


    public interface PayListener {
        void pay(MemberListBean.MemberCard card, String phone);

        void checkAgreement(boolean hasAgree);
    }
}