package com.example.wkttestapp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.ConsoleMessage;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;

import com.example.wkttestapp.utils.WebAppJsInterface;

import okhttp3.OkHttpClient;

public class MainActivity extends Activity {
    private int clickCount = 0;
    private OkHttpClient mOkHttpClient;
    WebView webView;
    private Button btnSendLocation;
    private Button btnViewMyLocation;
    private Button btnViewOtherLocation;
    private Button btnToggle;
    private LinearLayout buttonsContainer;
    private boolean isExpanded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.createWebView();
        initButtons();
        setupToggleButton();
    }

    private void initButtons() {
        buttonsContainer = findViewById(R.id.buttons_container);
        btnSendLocation = findViewById(R.id.btn_send_location);
        btnViewMyLocation = findViewById(R.id.btn_view_my_location);
        btnViewOtherLocation = findViewById(R.id.btn_view_other_location);
        btnToggle = findViewById(R.id.btn_toggle);

        // 发送自己定位按钮点击事件
        btnSendLocation.setOnClickListener(v -> {
            if (webView != null) {
                webView.evaluateJavascript(
                        "window.receiveLocationData(47.352663, 87.831563, 'send_location')",
                        null
                );
                // 点击后收起按钮
                toggleButtons();
            }
        });

        // 查看自己发出定位按钮点击事件
        btnViewMyLocation.setOnClickListener(v -> {
            if (webView != null) {
                webView.evaluateJavascript(
                        "window.receiveLocationData(47.352663, 87.831563, 'view_my_location')",
                        null
                );
                // 点击后收起按钮
                toggleButtons();
            }
        });

        // 查看他人发出定位按钮点击事件
        btnViewOtherLocation.setOnClickListener(v -> {
            if (webView != null) {
                webView.evaluateJavascript(
                        "window.receiveLocationData(47.352663, 87.831563, 'view_other_location')",
                        null
                );
                // 点击后收起按钮
                toggleButtons();
            }
        });
    }

    private void setupToggleButton() {
        btnToggle.setOnClickListener(v -> toggleButtons());
    }

    private void toggleButtons() {
        Animation fadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
        Animation fadeOut = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);

        if (isExpanded) {
            // 收起按钮
            buttonsContainer.startAnimation(fadeOut);
            buttonsContainer.setVisibility(View.GONE);
            btnToggle.setBackgroundResource(R.drawable.ic_control_button);
        } else {
            // 展开按钮
            buttonsContainer.startAnimation(fadeIn);
            buttonsContainer.setVisibility(View.VISIBLE);
            // 可以在这里更换按钮图标，表示状态变化
            btnToggle.setBackgroundResource(R.drawable.ic_control_button);
        }

        isExpanded = !isExpanded;
    }

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

    @SuppressLint("SetJavaScriptEnabled")
    private void createWebView() {
        webView = findViewById(R.id.webview);

        // 自定义WebChromeClient以捕获控制台日志
        WebChromeClient webChromeClient = new WebChromeClient() {
            @Override
            public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
                // 打印 JavaScript 控制台信息
                // 获取日志级别
                ConsoleMessage.MessageLevel messageLevel = consoleMessage.messageLevel();
                // 获取日志信息
                String message = consoleMessage.message();
                // 获取日志所在行号
                int lineNumber = consoleMessage.lineNumber();
                // 获取日志所在源文件
                String sourceId = consoleMessage.sourceId();

                // 根据日志级别进行不同处理
                switch (messageLevel) {
                    case ERROR:
                        System.err.println("JavaScript ERROR: " + message + "  in  " + sourceId + "  from  " + lineNumber + "  line ");
                        break;
                    case WARNING:
                        System.out.println("JavaScript WARNING: " + message + "  in  " + sourceId + "  from  " + lineNumber + "  line ");
                        break;
                    default:
                        System.out.println("JavaScript LogInfo : " + message + "  in  " + sourceId + "  from  " + lineNumber + "  line ");
                        break;
                }
                return true;

            }
        };

        webView.setWebChromeClient(webChromeClient);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return true;
            }
        });

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setUseWideViewPort(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setSupportZoom(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webView.requestFocusFromTouch();
        webView.addJavascriptInterface(new WebAppJsInterface(), "tcAPI");

        webView.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                    webView.goBack();
                    return true;
                }
            }
            return false;
        });


        webView.loadUrl("http://wuhan.gishub.com.cn:10000/case/xinjiangcard/");
    }

}
