package com.rv.share;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.base.utils.tools.android.NetworkUtil;
import com.frame.base.bus.LoginSuccessfulEvent;
import com.frame.base.bus.Observer;
import com.frame.base.bus.RxBus;
import com.frame.rv.config.RvFrameConfig;
import com.ruiwenliu.wrapper.base.BaseBean;
import com.ruiwenliu.wrapper.base.BaseStatusActivity;
import com.ruiwenliu.wrapper.weight.TitleView;
import com.rv.share.presenter.WebViewPresenter;
import com.rv.share.view.RvWebView;

import butterknife.BindView;
import io.reactivex.android.schedulers.AndroidSchedulers;

public class WebViewActivity extends BaseStatusActivity<WebViewPresenter> {
    @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;

    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_web_view;
    }


    @Override
    protected void initView(Bundle savedInstanceState, TitleView titleView, 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();
        }
    }

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

    }

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

    @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();// 生命周期销毁
        }
        super.onDestroy();
    }

    private RvWebView.WebViewListener listener = new RvWebView.WebViewListener() {
        @Override
        public void share(final String url, final String imgUrl, final String title, final String circleTitle, final String desc) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String billUrl = RvFrameConfig.HOST + "/h5/appHtml/view/poster.html";
                    mPresenter.showShareDialog(url, imgUrl, title, circleTitle, desc, billUrl);
                }
            });
        }

        @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 imgUrl, final String title, final String circleTitle, final String desc) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ivTitleRight.setVisibility(View.VISIBLE);
                    ivTitleRight.setImageResource(R.drawable.tourism_rv_rentingcar_icon_share);
                }
            });
            String billUrl = null;
            if (!TextUtils.isEmpty(url) && url.contains("invitationCourtesyShare.html")) {
                billUrl = RvFrameConfig.HOST + "/h5/appHtml/view/poster.html";
            } else if (!TextUtils.isEmpty(url) && url.contains("newPeopleH5.html")) {
                billUrl = RvFrameConfig.HOST + "/h5/appHtml/view/newPeoplePoster.html";
            }
            final String finalBillUrl = billUrl;
            ivTitleRight.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPresenter.showShareDialog(url, imgUrl, title, circleTitle, desc, finalBillUrl);
                }
            });
        }
    };
}
