package com.android.chmo.ui.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.chmo.R;
import com.android.chmo.app.ChmoApplication;
import com.android.chmo.base.BaseActivity;
import com.android.chmo.http.HttpApi;
import com.android.chmo.ui.dialog.ShareDialog;
import com.android.chmo.ui.view.TopBar;
import com.android.chmo.wxapi.WeChatManager;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import butterknife.BindView;

public class WebViewActivity extends BaseActivity implements ShareDialog.OnShareListener {
    @BindView(R.id.webView)
    WebView     webView;
    @BindView(R.id.progressbar)
    ProgressBar progressBar;
    @BindView(R.id.top_bar)
    TopBar      topBar;

    private String      url;
    private ShareDialog shareDialog;
    private IWXAPI      iwxapi;
    private String      shareUrl   = HttpApi.BASE_URL + "share.jsp?type=1&code=" + ChmoApplication.getApp().getLoginUser().qrcode;
    private String      shareTitle = "千模通告";
    private String      shareDesc  = "模特，网红，空姐，校花，邀您一键视频验证";

    public static void start(Context context, String url) {
        Intent intent = new Intent(context, WebViewActivity.class);
        intent.putExtra("url", url);
        context.startActivity(intent);
        ((Activity) context).overridePendingTransition(R.anim.push_right_in, R.anim.push_left_out);
    }

    @Override
    protected int getContentResId() {
        return R.layout.activity_web_view;
    }

    @Override
    public void initView() {
        url = getIntent().getStringExtra("url");

        ImageView imageView = new ImageView(this);
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, getResources().getDimensionPixelSize(R.dimen.top_bar_height));
        params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
        params.rightMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, getResources().getDisplayMetrics());
        imageView.setLayoutParams(params);
        imageView.setImageResource(R.mipmap.icon_fenxiang);
        imageView.setScaleType(ImageView.ScaleType.CENTER);
        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                share();
            }
        });
        topBar.addView(imageView);

        webView.addJavascriptInterface(this, "chmo");//添加js监听 这样html就能调用客户端
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webViewClient);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        WebSettings webSettings = webView.getSettings();
        webSettings.setUserAgentString(webSettings.getUserAgentString() + " chmo");
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);//不使用缓存，只从网络获取数据.

        //支持屏幕缩放
        webSettings.setSupportZoom(false);
        webSettings.setDisplayZoomControls(false);

        webView.loadUrl(url);

        shareDialog = new ShareDialog(this);
        shareDialog.setOnShareListener(this);
        WeChatManager weChatManager = WeChatManager.getInstance();
        weChatManager.init(this);
        iwxapi = weChatManager.getApi();
    }

    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    private WebChromeClient webChromeClient = new WebChromeClient() {
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            new AlertDialog.Builder(webView.getContext())
                    .setMessage(message)
                    .setPositiveButton("确定", (dialog, which) -> result.confirm())
                    .setCancelable(false)
                    .show();
            return true;
        }

        @Override
        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
            new AlertDialog.Builder(webView.getContext())
                    .setMessage(message)
                    .setPositiveButton("确定", (dialog, which) -> result.confirm())
                    .setNegativeButton("取消", (dialog, which) -> result.cancel())
                    .setCancelable(false)
                    .show();
            return true;
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            topBar.setTitle(title);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }
    };

    @JavascriptInterface
    public void modelDetail(String memberPK) {
        Toast.makeText(this, memberPK, Toast.LENGTH_SHORT).show();
    }

    @JavascriptInterface
    public void share() {
        runOnUiThread(() -> shareDialog.show());
    }

    @JavascriptInterface
    public void setShareInfo(String url, String title, String desc) {
        if (!TextUtils.isEmpty(url)) {
            if (!url.startsWith("http")) {
                url = HttpApi.BASE_URL + url;
            }
            shareUrl = url;
        }
        shareUrl = url;
        shareTitle = title;
        shareDesc = desc;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {
            webView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        webView.destroy();
        webView = null;
    }

    @Override
    public void onShareWechatSession() {
        WXWebpageObject webpageObject = new WXWebpageObject(shareUrl);
        WXMediaMessage message = new WXMediaMessage();
        message.mediaObject = webpageObject;
        message.title = shareTitle;
        message.description = shareDesc;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        message.setThumbImage(bmp);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneSession;
        req.message = message;
        boolean success = iwxapi.sendReq(req);
        Log.d("success", success + "");
    }

    @Override
    public void onShareWechatTimeline() {
        WXWebpageObject webpageObject = new WXWebpageObject(shareUrl);
        WXMediaMessage message = new WXMediaMessage();
        message.mediaObject = webpageObject;
        message.title = shareTitle + "——" + shareDesc;
        message.description = shareTitle + "——" + shareDesc;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
        message.setThumbImage(bmp);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.scene = SendMessageToWX.Req.WXSceneTimeline;
        req.message = message;
        iwxapi.sendReq(req);
    }
}
