package com.hc.webapp.web;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.URLUtil;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.hc.webapp.BuildConfig;
import com.hc.webapp.MainActivity;
import com.hc.webapp.NetworkConnectChangedListener;
import com.hc.webapp.NetworkConnectChangedReceiver;
import com.hc.webapp.R;


import org.json.JSONObject;

import java.net.HttpURLConnection;
import java.util.Timer;
import java.util.TimerTask;


@SuppressWarnings("unused")
public abstract class BaseWebActivity extends AppCompatActivity {

    public static final int REQUEST_PLAY_FINISH = 0x100;

    protected WebView webView;
    private ImageView noticeImage;
    protected FrameLayout webViewContainer;
    protected boolean hasShowWebView = false;
    protected boolean hasOneFloatViewToShow = true;
    String TAG = "BaseWebActivity";
    /**
     * JS调用对象名
     */
    private String JsInvokeName = AndroidToJS.class.getSimpleName();
    /**
     * 是否监听返回按键，作用于{@link BaseWebActivity#onKeyDown(int, KeyEvent)}
     */
    private boolean shouldOverrideBackKeyEvent;
    /**
     * 是否监听返回按键，作用于{@link BaseWebActivity#onBackPressed()}
     */
    private boolean shouldOverrideBackPressToJS = true;

    private int platformType = BuildConfig.platformType; //1：百事通，2：银河，3：未来
    private int deviceType = BuildConfig.devicesType;


    /**
     * 监听网络状态广播
     */
    private NetworkConnectChangedReceiver networkConnectChangedReceiver;

    /**
     * 获取启动页web地址
     */
    protected abstract String getIndexURL();

    /**
     * 获取JS调用对象名。
     */
    protected String getJsInvokeName() {
        return JsInvokeName;
    }

    /**
     * 设置是否监听返回按键
     *
     * @param shouldOverrideBackKeyEvent 默认为<code>false</code>
     */
    protected void setShouldOverrideBackKeyEvent(boolean shouldOverrideBackKeyEvent) {
        this.shouldOverrideBackKeyEvent = shouldOverrideBackKeyEvent;
    }

    /**
     * 设置是否替换返回键为JS调用
     *
     * @param shouldOverrideBackPressForJS 默认为<code>true</code>
     */
    public void setShouldOverrideBackPressToJS(boolean shouldOverrideBackPressForJS) {
        this.shouldOverrideBackPressToJS = shouldOverrideBackPressForJS;
    }

    public void setPlayVideoListener(AndroidToJS androidToJS) {
    }

    public WebView getWebView() {
        return webView;
    }

    public void handleIntent(Intent intent) {

    }

    @Override
    protected void onStart() {
        super.onStart();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    //检查网络是否可用,add by 许林2018/12/5
    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);

        if (manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();

        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }

        return true;
    }

    private void showNoNetImage(){
        BaseWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                noticeImage.setVisibility(View.VISIBLE);
            }
        });
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                BaseWebActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        noticeImage.setVisibility(View.INVISIBLE);
                    }
                });
            }
        },2000);
    }

    protected void showCancelCollectImage(){
        BaseWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                noticeImage.setImageResource(R.drawable.cancel_collect);
                noticeImage.setVisibility(View.VISIBLE);
            }
        });
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                BaseWebActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        noticeImage.setVisibility(View.INVISIBLE);
                    }
                });
            }
        },2000);
    }

    protected void showCollectSuccessImage(){
        BaseWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                RelativeLayout layout = new RelativeLayout(BaseWebActivity.this);
                layout.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
                ImageView imageView = new ImageView(BaseWebActivity.this);
                int imageWidth = getResources().getDimensionPixelSize(R.dimen.notice_width);
                int imageHeight = getResources().getDimensionPixelSize(R.dimen.notice_height);
                RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(imageWidth,imageHeight);
                layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
                layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
                int marginBottom = getResources().getDimensionPixelSize(R.dimen.notice_bottom_distance);
                layoutParams.setMargins(0,0,0,marginBottom);
                imageView.setLayoutParams(layoutParams);
                layout.addView(imageView);
                webViewContainer.addView(layout);
            }
        });
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                BaseWebActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        noticeImage.setVisibility(View.INVISIBLE);
                    }
                });
            }
        },2000);
    }

    private void CheckNetWorkLoop(CheckNetWorkListener listener){
        if(!isNetworkAvailable(this)){
            showNoNetImage();
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    CheckNetWorkLoop(listener);
                }
            },5000);
            listener.checkResult(false);
        }else{
            listener.checkResult(true);
        }
    }

    interface CheckNetWorkListener{
        public void checkResult(boolean result);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        //hasOneFloatViewToShow = true;
        if (getIntent() != null) {
            handleIntent(getIntent());
        }


        webViewContainer = findViewById(R.id.webview_container);
        noticeImage = findViewById(R.id.notice_image);


        webView = new WebView(this);
        webView.setBackgroundColor(ContextCompat.getColor(this, android.R.color.transparent));
//        webView.setBackgroundResource(R.drawable.img_start_bg);
        //setContentView(webView, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        webViewContainer.addView(webView,new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT));
        initWebSetting(webView);
        webView.setVisibility(View.INVISIBLE);

        if(!isNetworkAvailable(this)){
            setShouldOverrideBackPressToJS(false);
            CheckNetWorkLoop(new CheckNetWorkListener() {
                @Override
                public void checkResult(boolean result) {
                    if(result){
                        setShouldOverrideBackPressToJS(true);
                        BaseWebActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                webView.loadUrl(getIndexURL());
                            }
                        });
                    }else{
                        setShouldOverrideBackPressToJS(false);
                    }
                }
            });
        }else{
            setShouldOverrideBackPressToJS(true);
            webView.loadUrl(getIndexURL());
        }

    }

    /*
     * add by xulin 20181221 start
     * */
    private void registerReceiver(){
        registerNetworkConnectChangedReceiver(new NetworkConnectChangedListener() {
            @Override
            public void onConnected() {
                hideNoNet();
            }

            @Override
            public void onDisConnected() {
                showNoNet();
            }
        });
    }

    protected void showNoNet(){
        BaseWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                destroyWebView();
                destroyVideoView();
                noticeImage.setVisibility(View.VISIBLE);
            }
        });
    };

    private void destroyWebView(){
        if (webView != null) {
            webView.setVisibility(View.INVISIBLE);
        }
    }

    protected abstract void destroyVideoView();

    protected void hideNoNet(){
        BaseWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                reloadWebView();
                noticeImage.setVisibility(View.VISIBLE);
            }
        });
    };

    private void reloadWebView(){
        webView.setVisibility(View.VISIBLE);
        webView.loadUrl(getIndexURL());
    }

    private void registerNetworkConnectChangedReceiver(NetworkConnectChangedListener networkConnectChangedListener){
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                IntentFilter filter = new IntentFilter();
                filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
                filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
                filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
                networkConnectChangedReceiver = new NetworkConnectChangedReceiver(BaseWebActivity.this,networkConnectChangedListener);
                registerReceiver(networkConnectChangedReceiver, filter);
            }
        },2000);
    }

    /*
     * add by xulin 20181221 end
     * */

    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface", "AddJavascriptInterface"})
    private void initWebSetting(WebView webView) {
        WebSettings webSettings = webView.getSettings();
        // 由H5端适配屏幕，具体参考文档：https://developer.chrome.com/multidevice/webview/pixelperfect
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 设置JS交互
        webSettings.setJavaScriptEnabled(true);

        AndroidToJS onJsEvent = new AndroidToJS(this, webView);
        setPlayVideoListener(onJsEvent);
        webView.addJavascriptInterface(onJsEvent, getJsInvokeName());
        // 设置WebClient
        webView.setWebViewClient(new HCWebViewClient());
        webView.setWebChromeClient(new HCWebChromeClient());

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView view, String url)
            {
                Log.d("MainActivity","onPageFinished");
                hasShowWebView = true;
                webView.setVisibility(View.VISIBLE);
                if(hasOneFloatViewToShow){
                    delayShowFloatView();
                }
                updateApk();
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            }
        });

        // 设置是否开启web内容调试，具体调试方式查看：https://developers.google.com/web/tools/chrome-devtools/remote-debugging/?utm_source=dcc&utm_medium=redirect&utm_campaign=2016q3
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(BuildConfig.isDebug);
        }
    }

    protected void updateApk(){
        String url = "http://112.35.32.145:8090/index.php?m=Home&c=AndroidApi&a=uploadVersion&origin="+platformType + "&platform=" + deviceType;
        Log.d(TAG,"update url:" + url);
        GetRuquest getRuquest = new GetRuquest();
        getRuquest.RequestAsync(url, new GetRequestListener() {
            @Override
            public void onResult(String msg) {
                try{
                    JSONObject jsonObject = new JSONObject(msg);
                    int code = jsonObject.getInt("code");
                    if(code == 0){
                        JSONObject data = jsonObject.getJSONObject("data");
                        int versionCode = data.getInt("versionCode");
                        int currentVCode = BaseWebActivity.this.getPackageManager().getPackageInfo(
                                BaseWebActivity.this.getPackageName(),0
                        ).versionCode;
                        boolean hasUpdate = false;
                        if(versionCode > currentVCode){
                            hasUpdate = true;
                            Toast("版本有更新,后台正在下载中...");
                            String versionName = data.getString("versionName");
                            String url = data.getString("url");
                            int size = data.getInt("size");
                            String updateContent = data.getString("updateContent");
                            String md5 = data.getString("md5");
                            new DownloadInstall(BaseWebActivity.this).start(url,md5);
                        }

                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        });
    }




    private void Toast(String msg){
        BaseWebActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(BaseWebActivity.this,msg,Toast.LENGTH_SHORT).show();
            }
        });
    }

    protected abstract void delayShowFloatView();

    @Override
    protected void onResume() {
        super.onResume();
        if (webView != null) {
            webView.onResume();
        }
    }

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

    @Override
    protected void onPause() {
        super.onPause();
        if (webView != null) {
            webView.onPause();
        }
    }


    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.removeJavascriptInterface(JsInvokeName);
            webView.clearCache(true);
            webView.clearFormData();
            webView.clearMatches();
            webView.clearSslPreferences();
            webView.clearDisappearingChildren();
            webView.clearHistory();
            webView.clearAnimation();
            webView.loadUrl("about:blank");
            webView.removeAllViews();

            webView = null;
        }
        unregisterReceiver(networkConnectChangedReceiver);
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (shouldOverrideBackPressToJS) {
            notifyKeyEvent("back",8,true);
            AndroidToJS.evaluateJavascript(webView, AndroidToJS.JS_EVENT_BACK);
        } else {
            super.onBackPressed();
        }
    }

    public void notifyKeyEvent(String key, final int code, boolean keyDown) {
        Log.d(TAG, "notifyKeyEvent('" + key + "', " + code + ", " + keyDown + ")" );
        webView.loadUrl("javascript:" +
                "(function(){" +
                "var e=document.createEvent('Event');" +
                "e.initEvent('keydown',true, true); " +
                "e.keyCode=" + code + ";" +
                "e.which=" + code + ";" +
                "document.body.dispatchEvent(e);})()");
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == RESULT_OK) {
//            switch (requestCode) {
//                case REQUEST_PLAY_FINISH:
//                    Logger.d("播放结束，调用javascript:onPlayBackEvent()");
//                    AndroidToJS.evaluateJavascript(webView, AndroidToJS.JS_EVENT_PLAY_FINISH);
//                    break;
//                default:
//                    break;
//            }
//        }
//    }
}
