package com.rv.share;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
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 android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.base.utils.tools.android.NetworkUtil;
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.share.bean.AllGoodsListBean;
import com.rv.share.bean.BeanTourOrderAliPay;
import com.rv.share.bean.BeanTourOrderPay;
import com.rv.share.bean.OrderGoodsBean;
import com.rv.share.presenter.PreCardWebviewPresenter;
import com.rv.share.view.AllPreCardDialog;
import com.rv.share.view.RvWebView;
import com.yuyife.okgo.OkGoUtil;

import java.util.HashMap;
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;

public class PreCardWebViewActivity extends BaseStatusActivity<PreCardWebviewPresenter> {
    @BindView(R2.id.ll_contact)
    LinearLayout llContact;
    @BindView(R2.id.tv_buy)
    TextView tvBuy;
    @BindView(R2.id.ll_content)
    LinearLayout llContent;
    @BindView(R2.id.img_left)
    ImageView ivTitleLeft;
    @BindView(R2.id.tv_left)
    TextView tvTitleLeft;
    @BindView(R2.id.tv_center)
    TextView tvTitleCenter;
    @BindView(R2.id.tv_right)
    TextView tvTitleRight;
    @BindView(R2.id.img_right)
    ImageView ivTitleRight;
    private String url;
    private String title;
    private RvWebView rvWebView;
    private AllGoodsListBean bean;
    private AllPreCardDialog dialog;

    public static Intent getIntent(Context context, String url, String name) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("title", name);
        return intent;
    }

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

    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, final Intent intent) {
        titleView.setVisibility(View.GONE);
        url = intent.getStringExtra("url");
        title = intent.getStringExtra("title");
        initRxbus();
        if (!TextUtils.isEmpty(title)) {
            tvTitleCenter.setVisibility(View.VISIBLE);
            tvTitleCenter.setText(title);
        }
        ivTitleLeft.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (rvWebView.canGoBack()) {
                    //返回上一个页
                    rvWebView.goBack();
                    return;
                }
                finish();
            }
        });
        rvWebView = new RvWebView(getApplicationContext(), listener);
        if (NetworkUtil.isNetworkAvailable(this)) {
            llContent.addView(rvWebView);
            if (!TextUtils.isEmpty(url)) {
                rvWebView.loadUrl(url);
            }
        } else {
            Toast.makeText(this, "网络异常", Toast.LENGTH_SHORT).show();
        }

        llContact.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_DIAL);
                Uri uri = Uri.parse("tel:4000369369");
                intent.setData(uri);
                startActivity(intent);
            }
        });

        tvBuy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (TextUtils.isEmpty(OkGoUtil.getToken())) {
                    Intent intent = LoginRvActivity.getIntent(PreCardWebViewActivity.this, 1);
                    startActivity(intent);
                    return;
                }

                if (bean != null) {
                    if (dialog == null)
                        dialog = new AllPreCardDialog(PreCardWebViewActivity.this, bean, payListener);
                    dialog.show();
                    return;
                }

                Map<String, String> header = new HashMap<>(2);
                header.put("Authorization", OkGoUtil.getToken());
                Map<String, String> map = new HashMap<>(2);
                map.put("type", "4");

                mPresenter.getData(RvFrameConfig.HOST, 0, ApiConfig.HTTP_URL_ACTIVITY_ALL_GOODS, AllGoodsListBean.class, map, header, true);
            }
        });
        initRxBus();

    }

    private AllPreCardDialog.PayListener payListener = new AllPreCardDialog.PayListener() {
        @Override
        public void pay(AllGoodsListBean.DetailList detailList, int n) {
            showPayDialog(detailList,n);

        }
    };

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

    @Override
    protected void loadData(Bundle savedInstanceState, Intent intent) {
        super.loadData(savedInstanceState, intent);
        if (rvWebView != null)
            mPresenter.setWebView(rvWebView);
    }

    @Override
    public void onShowResult(int requestType, BaseBean result) {
        switch (requestType) {
            case 0:
                bean = (AllGoodsListBean) result;
                if (((AllGoodsListBean) result).isRel()) {
                    if (dialog == null)
                        dialog = new AllPreCardDialog(PreCardWebViewActivity.this, bean, payListener);
                    dialog.show();
                }
                break;
            case 1:
                OrderGoodsBean orderGoodsBean = (OrderGoodsBean) result;
                if (orderGoodsBean.isRel() && orderGoodsBean.getData() != null) {
                    mPresenter.orderPay(orderGoodsBean.getData().no, payType, 1);
                }
                break;
            case 3:
                mPresenter.pay(PreCardWebViewActivity.this, (BeanTourOrderPay) result);
                break;
            case 4:
                mPresenter.aliPay(PreCardWebViewActivity.this, (BeanTourOrderAliPay) result);
                break;
        }
    }

    @Override
    public void onBackPressedSupport() {
        if (rvWebView.canGoBack()) {
            //返回上一个页
            rvWebView.goBack();
            return;
        }
        super.onBackPressedSupport();
    }

    private int payType = 1;

    private void showPayDialog(final AllGoodsListBean.DetailList detailList, final int number) {
        new PaymentTypeSelection(mActivity) {
            @Override
            public void helper(final ViewHolder helper) {
                super.helper(helper);

                helper.setText(R.id.tv_amount, String.format("￥%1$s", detailList.goodsPrice.doubleValue() * number));
                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(title, detailList, number);
                        }
                    }
                }, R.id.iv_close, R.id.ll_item_wechat, R.id.ll_item_alipay, R.id.tv_pay_immediately);

            }
        }.show();
    }


    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 {
                        startActivity(OrderListActivity.getIntent(mActivity, 3));
                        finish();
                    }
                });

        disposableFail = RxBus.tObservable(PaymentFailedEvent.class)
                .observeOn(Schedulers.newThread())
                .subscribe(new Consumer<PaymentFailedEvent>() {
                    @Override
                    public void accept(PaymentFailedEvent payEvent) throws Exception {
                        if (mActivity.getClass().equals(PreCardWebViewActivity.class)) {
                            ARouter.getInstance().build(Constance.ACTIVITY_URL_ORDERLIST).navigation();
                            finish();
                        }
                    }
                });
        Log.e("xxxxxxxxxxxxxx", disposableSuc == disposableFail ? "true" : "false");

    }


    @Override
    public void onDestroy() {
        if (rvWebView != null) {
            llContent.removeAllViews();
            rvWebView.stopLoading();// 停止当前加载
            rvWebView.clearMatches();// 清除网页查找的高亮匹配字符。
            rvWebView.clearHistory();// 清除当前 WebView 访问的历史记录
            rvWebView.clearSslPreferences();//清除ssl信息
            rvWebView.clearCache(true);//清空网页访问留下的缓存数据。需要注意的时，由于缓存是全局的，所以只要是WebView用到的缓存都会被清空，即便其他地方也会使用到。该方法接受一个参数，从命名即可看出作用。若设为false，则只清空内存里的资源缓存，而不清空磁盘里的。
            rvWebView.loadUrl("about:blank");// 清空当前加载
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
                rvWebView.removeJavascriptInterface("AndroidNative");// 向 Web端注入 java 对象
            }
            rvWebView.destroy();// 生命周期销毁
        }

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

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

        super.onDestroy();
    }

    private RvWebView.WebViewListener listener = new RvWebView.WebViewListener() {
        @Override
        public void share(final String url, final String iconUrl, final String title, final String circleTitle, final String desc, final String imgUrl) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mPresenter.showShareDialog(url, iconUrl, title, circleTitle, desc, imgUrl);
                }
            });
        }

        @Override
        public void share(final String url, final String title, final String desc) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mPresenter.showShareDialog(url, null, title, null, desc, null);
                }
            });
        }

        @Override
        public void finish() {
            finish();
        }

        @Override
        public void showShareIcon(final String url, final String iconUrl, final String title, final String circleTitle, final String desc, final String imgUrl) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ivTitleRight.setVisibility(View.VISIBLE);
                    ivTitleRight.setImageResource(R.drawable.tourism_rv_rentingcar_icon_share);
                }
            });
            ivTitleRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.showShareDialog(url, iconUrl, title, circleTitle, desc, imgUrl);
                }
            });
        }
    };
}
