package com.yyrh.ui.dialog;

import android.app.Activity;
import android.content.Context;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.DownloadListener;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import android.widget.ImageView;
import android.widget.LinearLayout;


import com.yyrh.constant.SDKSettings;
import com.yyrh.ui.PageJsInteraction;
import com.yyrh.ui.userlist.DatabaseHelper;

import com.yyrh.utils.ResourceUtil;
import com.yyrh.utils.TosUtil;
import com.yyrh.utils.Utils;


import java.net.URISyntaxException;
import java.util.HashMap;

import static com.yyrh.constant.SDKSettings.isLandscape;
import static com.yyrh.constant.SDKSettings.isVefityRealName;

public class WvPageListDialog extends BaseDialog {


    private ImageView close_btn,loading;
    private Context context;
    private WebView webView;
    private WebSettings webSettings;

    private String url;
    public OnClosePageListener listener;
    private boolean isHiddenClo = false;
    public WvPageListDialog(Context context) {
        super(context);
        this.context = context;
    }


    public WvPageListDialog(Context context, int theme,String url) {
        super(context, theme);
        this.context = context;

        this.url = url;

    }

    public WvPageListDialog(Context context, int theme,String url,OnClosePageListener listener) {
        super(context, theme);
        this.context = context;

        this.url = url;
        this.listener = listener;
    }
    public WvPageListDialog(Context context, int theme,String url,OnClosePageListener listener,boolean isHiddenClose) {
        super(context, theme);
        this.context = context;

        this.url = url;
        this.listener = listener;
        this.isHiddenClo = isHiddenClose;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            setContentView(ResourceUtil.getLayoutId(context,
                    "hnyy_webview_common_dialog"));




        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            Window window = getWindow();
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);


            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(lp);
        }


            setCancelable(false);



        if (!isLandscape){

            LinearLayout ll_webview_common = findViewById(ResourceUtil.getId(context, "ll_webview_common"));
            ll_webview_common.setScaleX(0.9f);
            ll_webview_common.setScaleY(0.9f);

        }

        webView = findViewById(ResourceUtil.getId(context,
                "wb_user_info"));

        close_btn = findViewById(ResourceUtil.getId(context,
                "close_btn"));

        loading = findViewById(ResourceUtil.getId(context, "hnyy_loading"));
        Animation rotateAnimation = AnimationUtils.loadAnimation(context, ResourceUtil.getAnimId(context, "hnyy_rotate_anim"));
        loading.startAnimation(rotateAnimation);

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

                if (listener != null){
                    listener.onClose();
                }

                webView.destroy();
                dismiss();

            }
        });
        if (isHiddenClo){
            close_btn.setVisibility(View.GONE);
        }

//        reback_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (webView.canGoBack()) {
//                    webView.goBack();
//                }else {
//                    webView.destroy();
//                    dismiss();
//                }
//
//            }
//        });


//        wv_title.setText(title);
        webSettings = webView.getSettings();
        webSettings.setAllowFileAccess(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setBuiltInZoomControls(false);// 设置支持缩放
        webSettings.setDomStorageEnabled(true);
        webView.setHorizontalScrollBarEnabled(false);//水平不显示
        webView.setVerticalScrollBarEnabled(false); //垂直不显示

        webView.addJavascriptInterface(new PageJsInteraction(this), "yyrhsdk");
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                loading.clearAnimation();
                loading.setVisibility(View.GONE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {




                if (url.startsWith("http:") || url.startsWith("https")) {
                    return super.shouldOverrideUrlLoading(view, url);
                } else if (url.startsWith("mqqwpa://")) {

                    Intent intent = null;
                    try {
                        intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                        context.startActivity(intent);
                    } catch (URISyntaxException e) {
                        e.printStackTrace();
                    }

                    webView.goBack();
                    return true;

                }else{
                    return true;
                }
            }

        });

        webView.setDownloadListener(new DownloadListener() {
            @Override
            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                context.startActivity(intent);
            }
        });


        webView.setBackgroundColor(0);
        webView.getBackground().setAlpha(0);


        webView.loadUrl(url);
    }




    public interface OnClosePageListener {
         void onClose();
         void onDissmiss();
         void onRealNameSuccess(String birthday);
    }



    @Override
    public void zfColse() {
        super.zfColse();
        if (listener != null){
            listener.onClose();
        }
        dismiss();
    }

    @Override
    public void showJsMsg(String message) {
        super.showJsMsg(message);
        new TosUtil(context,TosUtil.TOAST_ERROR,  message).show();
    }

    @Override
    public void usrRn(String message) {
        super.usrRn(message);
        isVefityRealName = true;
        SDKSettings.loginData.rn_bd = message;
        listener.onRealNameSuccess(message);
    }

    @Override
    public void modifyPwd(String message) {
        super.modifyPwd(message);


        HashMap<String, String> map = new HashMap();
        map.put("username", SDKSettings.loginData.uname);
        map.put("password", message);
        Utils.setSharedPreferences("yyrh",map,context);



        String timeStamp = System.currentTimeMillis() + "";

        String delete_sql = "delete from user where name = '" + SDKSettings.loginData.uname + "'";

        String insert_sql = "insert into user(name,pwd,time) values('" +SDKSettings.loginData.uname
                + "','" + message + "','" + timeStamp + "')";

        DatabaseHelper.excuteSql(context, delete_sql);
        DatabaseHelper.excuteSql(context, insert_sql);
    }


    @Override
    public void openq0q0(String url) {
        super.openq0q0(url);

        {
            Log.i("openq0q0", url);
            if (Utils.judgeStrNull(url)) {
                return;
            }
            if (url.equals("mqqwpa://")) {
                try {

                    Intent intent = context.getPackageManager().getLaunchIntentForPackage("com.tencent.mobileqq");
                    context.startActivity(intent);

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

                }
            } else {
                Intent intent = null;
                try {
                    intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                    context.startActivity(intent);
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }

            }


        }
    }

    @Override
    public void dismiss() {
        super.dismiss();
        if (isHiddenClo){
            if (SDKSettings.loginData.rn_bd.equals("")){
                SDKSettings.loginData.channel_uid = "";
                SDKSettings.loginData.uname = "";

            }

        }
        if (listener != null){
            listener.onDissmiss();
        }


    }
}
