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.TextView;

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.control.SwitchButton;
import com.rv.component.dialog.PaymentTypeSelection;
import com.rv.component.utils.Arith;
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.MemberCompareView;
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.xxrv.coupon.api.CouponApi;
import com.xxrv.coupon.bean.CarCouponBean;
import com.yuyife.okgo.OkGoUtil;

import java.util.Arrays;
import java.util.Comparator;
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.member_compare_view)
    MemberCompareView compareView;
    @BindView(R2.id.tv_member_discount_hint)
    TextView tvMemberDisCountHint;
    @BindView(R2.id.tv_member_free_day_hint)
    TextView tvMemberFreeDayHint;

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

    private boolean hasAgree = false;

    private CarCouponBean.DataBean.CarCouponTypeDataBean.CarCouponDataBean couponBean;


    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);
            compareView.setData(listBean.getData());
            setMemberDiscountAndFreeDay(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);
                    compareView.setData(listBean.getData());
                    setMemberDiscountAndFreeDay(listBean);
                }
                break;
            case 1:
                RvCache.getInstance().save((UserInfoBean) result, CacheEnum.USER);
                memberTopView.setUserInfoData((UserInfoBean) result);
                break;
            case 2:
                MemberOrderBean orderBean = (MemberOrderBean) result;
                if (orderBean != null && orderBean.getData() != null) {
                    if (orderBean.getData().getRealAmount().doubleValue() == 0) {
                        ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST)
                                .withInt("position", 3)
                                .navigation();
                        finish();
                    } else {
                        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;
            case 5:
                CarCouponBean bean = (CarCouponBean) result;
                if (bean != null) {
                    if (bean.getData() != null) {
                        couponBean = bean.getData().getCoupon();
                    }
                }

                showPayDialog();
                break;
        }
    }


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

    private void setMemberDiscountAndFreeDay(MemberListBean listBean) {
        if (listBean.getData().size() == 3) {
            Integer[] discounts = new Integer[3];
            Integer[] freeDays = new Integer[3];
            for (int i = 0; i < listBean.getData().size(); i++) {
                MemberListBean.MemberCard card = listBean.getData().get(i);
                discounts[i] = card.getDiscount() / 10;
                freeDays[i] = card.getNumber();
            }
            Arrays.sort(discounts, new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o2 - o1;
                }
            });
            Arrays.sort(freeDays, new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    return o1 - o2;
                }
            });
            tvMemberFreeDayHint.setText(String.format(getString(R.string.tv_member_free_day), freeDays));
            tvMemberDisCountHint.setText(String.format(getString(R.string.tv_member_rent_discount), discounts));
        }
    }

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

    private void getCouponData() {
        if (OkGoUtil.getToken() != null) {
            Map<String, Object> headMap = new LinkedHashMap<>();

            headMap.put("Authorization", OkGoUtil.getToken());
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("type", 0);
            map.put("channel", "4");
            map.put("amount", selectCard.getPrice());
            mPresenter.getData(RvFrameConfig.HOST, 5, CouponApi.HTTP_URL_COUPON_TYPELIST, CarCouponBean.class, map, headMap, true);
        }
//        if (OkGoUtil.getToken() != null) {
//            Map<String, Object> headMap = new LinkedHashMap<>();
//            headMap.put("Authorization", OkGoUtil.getToken());
//            Map<String, Object> map = new LinkedHashMap<>();
//            map.put("type", "0");
//            map.put("channel", 4);
//            mPresenter.getData(RvFrameConfig.HOST, 5, CouponApi.HTTP_URL_COUPON_LIST, CouponBean.class, map, headMap, false);
//        }
    }

    /**********
     * 获取会员中心信息
     */
    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 MemberListBean.MemberCard selectCard;
    private String userPhone;
    private PayListener payListener = new PayListener() {
        @Override
        public void pay(final MemberListBean.MemberCard card, final String phone) {
            if (!isLogin()) return;
            selectCard = card;
            userPhone = phone;
            couponBean = null;
            getCouponData();
        }

        @Override
        public void checkAgreement(boolean b) {
            hasAgree = b;
        }
    };

    private boolean isUseCoupon = false;

    private void showPayDialog() {
        new PaymentTypeSelection(MemberCenterActivity.this) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);
                if (couponBean != null) {
                    isUseCoupon = true;
                    double realPrice = Arith.sub(selectCard.getPrice().doubleValue(), couponBean.getUsedAmount());
                    helper.setText(R.id.tv_amount, String.format("￥%1$s", realPrice < 0 ? 0 : realPrice));
                } else {
                    isUseCoupon = false;
                    helper.setText(R.id.tv_amount, String.format("￥%1$s", selectCard.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(selectCard, isUseCoupon ? (couponBean != null ? couponBean.getTickerNo() : "") : "", userPhone, 2);
                        }
                    }
                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
                if (couponBean != null) {
                    helper.getItemView().findViewById(R.id.ll_item_coupon).setVisibility(View.VISIBLE);
                    TextView tvCouponNumber = helper.getItemView().findViewById(R.id.tv_coupon_number);
                    tvCouponNumber.setVisibility(View.VISIBLE);
                    tvCouponNumber.setText("使用" + couponBean.getUsedAmount() + "元代金券");
                    helper.getItemView().findViewById(R.id.line_coupon).setVisibility(View.VISIBLE);
                    SwitchButton switchButton = helper.getItemView().findViewById(R.id.sb_coupon_select);
                    switchButton.setVisibility(View.VISIBLE);
                    switchButton.setChecked(true);
                    switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                            if (isChecked) {
                                isUseCoupon = true;
                                double realPrice = Arith.sub(selectCard.getPrice().doubleValue(), couponBean.getUsedAmount());
                                helper.setText(R.id.tv_amount, String.format("￥%1$s", realPrice < 0 ? 0 : realPrice));
                            } else {
                                isUseCoupon = false;
                                helper.setText(R.id.tv_amount, String.format("￥%1$s", selectCard.getPrice()));
                            }
                        }
                    });
                }
            }
        }.show();

//        new PaymentTypeSelection(MemberCenterActivity.this) {
//            @Override
//            public void helper(final ViewHolder helper) {
//                super.helper(helper);
//                helper.setText(R.id.tv_amount, String.format("￥%1$s", selectCard.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(selectCard,"", userPhone, 2);
//                        }
//                    }
//                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);
//            }
//        }.show();
    }

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

        void checkAgreement(boolean hasAgree);
    }
}