package com.example.jhpapp;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.LifecycleEventObserver;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.jhpapp.utils.DeviceIdUtil;
import com.example.jhpapp.utils.DownloadUtils;
import com.example.jhpapp.utils.LocalAddressUtil;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.PlaybackException;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import pl.droidsonroids.gif.GifImageView;

public class MainActivity extends BaseActivity {

    private WebView webIDs;
    private Context context;
    Button call_Js,but1,but02,but2,but3;
    TextView js_info;
    TextView textValue;
    GifImageView webViewLoading;

    // ❷ 播放模块：全局监听器（避免重复创建）+ volatile保障线程可见性
    private volatile SimpleExoPlayer player;
    private final Player.Listener globalPlayerListener = new Player.Listener() {
        @Override
        public void onPlaybackStateChanged(int playbackState) {
            switch (playbackState) {
                case Player.STATE_IDLE:
                    Log.i("mediaplay","状态: 空闲");
                    break;
                case Player.STATE_BUFFERING:
                    Log.i("mediaplay","状态: 缓冲中");
                    break;
                case Player.STATE_READY:
                    Log.i("mediaplay","状态: 就绪");
                    // 就绪后自动播放（仅全局监听器处理，避免重复）
                    if (player != null && !player.isPlaying()) {
                        player.play();
                    }
                    break;
                case Player.STATE_ENDED:
                    Log.i("mediaplay","状态: 播放完成");
                    // ❸ 封装通知JS方法，增加Activity状态检查
                    notifyJs("mediaPlayOver", "success");
                    // 播放完成后重置播放器，避免下次播放异常
                    if (player != null) {
                        player.stop();
                    }
                    break;
            }
        }

        @Override
        public void onPlayerError(PlaybackException error) {
            Log.e("mediaplay", "播放错误: " + error.getMessage());
            switch (error.errorCode) {
                case PlaybackException.ERROR_CODE_DECODING_FAILED:
                    Log.e("mediaplay", "解码失败");
                    break;
                case PlaybackException.ERROR_CODE_IO_NETWORK_CONNECTION_FAILED:
                    Log.e("mediaplay", "网络连接失败");
                    break;
            }
            // ❹ 播放错误通知前端JS
            notifyJs("mediaPlayOver", "error");
        }

        @Override
        public void onIsPlayingChanged(boolean isPlaying) {
            Log.i("mediaplay","播放状态: " + isPlaying);
        }
    };

    //项目安装包下载链接
    public static final String APP_APKDOWN = "https://**?type=apk&target=selfprint";

    //文件存储功能
    SharedPreferences mPreferences;
    SharedPreferences.Editor mEditor;


    // ❺ 绑定生命周期的Handler（避免泄漏）
    private Handler handlerWebErr;

    // ❻ 生命周期观察者（管理播放器暂停/恢复）
    private final LifecycleEventObserver lifecycleObserver = (source, event) -> {
        if (player == null) return;
        switch (event) {
            case ON_PAUSE:
                // 后台暂停播放
                if (player.isPlaying()) {
                    player.pause();
                }
                break;
            case ON_RESUME:
                // 前台恢复播放（仅就绪状态）
                if (player.getPlaybackState() == Player.STATE_READY && !player.isPlaying()) {
                    player.play();
                }
                break;
            case ON_DESTROY:
                // 销毁时清理Handler
                if (handlerWebErr != null) {
                    handlerWebErr.removeCallbacksAndMessages(null);
                }
                break;
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint({"SetJavaScriptEnabled", "JavascriptInterface"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        context = this;

        // ❶ 绑定生命周期观察者
        getLifecycle().addObserver(lifecycleObserver);

        // 初始化Handler（与主线程绑定，避免泄漏）
        handlerWebErr = new Handler(Looper.getMainLooper());

        //初始化
        init();

        //版本判断
//        appVersionCheck();
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_main;
    }

    //版本判断
    private void appVersionCheck(){
        Log.i("version","Code:"+ LocalAddressUtil.getAppVersionCode(context));
        Log.i("version","Name:"+ LocalAddressUtil.getAppVersionName(context));
        new DownloadUtils(context, APP_APKDOWN, "prtkSelfPrint"+ LocalAddressUtil.getAppVersionCode(context)+".apk");
    }

    //初始化操作
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint({"SetJavaScriptEnabled", "SetTextI18n"})
    private void init(){

        //组件初始化
        webIDs = (WebView) findViewById(R.id.webID);
        call_Js= (Button) findViewById(R.id.call_js);
        but1= (Button) findViewById(R.id.but1);
        but02 = (Button) findViewById(R.id.but02);
        but2= (Button) findViewById(R.id.but2);
        but3 = (Button) findViewById(R.id.but3);
        js_info= (TextView) findViewById(R.id.js_info);
        textValue = (TextView) findViewById(R.id.textValue);
        webViewLoading = (GifImageView) findViewById(R.id.webViewLoading);

        //本地存储文件名 "zzjfile"
        mPreferences = getSharedPreferences("zzjfile", Context.MODE_PRIVATE);
        mEditor = mPreferences.edit();

        //webview设置
        WebSettings webSettings = webIDs.getSettings();
        webSettings.setJavaScriptEnabled(true);//设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//设置缓存使用方式为优先加载本地缓存
        webSettings.setDomStorageEnabled(true);//开启DOM存储API功能
        webSettings.setAllowFileAccess(true);//设置可以访问文件
        webSettings.setUseWideViewPort(true);//设置适应屏幕
        webSettings.setSupportZoom(true);//设置缩放
        webSettings.setDisplayZoomControls(true);//显示缩放控件

        webSettings.setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        webSettings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        webSettings.setAppCacheEnabled(true);//是否使用缓存
        webSettings.setLoadsImagesAutomatically(true); // 加载图片
        webSettings.setMediaPlaybackRequiresUserGesture(false);//播放音频，多媒体需要用户手动？设置为false为可自动播放

        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

        webViewLoading.setImageResource(R.drawable.loadingafter);
        Toast.makeText(MainActivity.this,"设备加载中-",Toast.LENGTH_SHORT).show();
        //注册JS调用节点
        webIDs.addJavascriptInterface(this,"JavaClientCall");
        webIDs.setWebViewClient(webViewClient);
        webIDs.loadUrl("http://10.1.34.29:8090/callapp/");
//        webIDs.loadUrl("http://10.1.19.20:8100");
//        webIDs.loadUrl("https://np.h03.p0551.com/callapp/");


        //读卡事件
        but1.setOnClickListener(onClickListener);
        //打印模块状态
        but02.setOnClickListener(onClickListener);
        //打印事件
        but2.setOnClickListener(onClickListener);
        //播放测试
        but3.setOnClickListener(onClickListener);
        //与React交互验证
        call_Js.setOnClickListener(onClickListener);

        initMedAudio();
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
//                case R.id.but1:
//                    break;
//                case R.id.but02:
//                    break;
//                case R.id.but2:
//                    break;
                case R.id.but3:
//                    mediaFilePlay("http://10.1.34.29:8090/images29/wav/ffd029b9983de18e2017042a3d7c393b.wav");
//                    mediaFilePlay("https://np.h03.p0551.com/images/wav/eba7ea72748b33c07d55ca7c443d6146.wav");
                    break;
                case R.id.call_js:          //調用js中的javaUseJs()方法
//                  webIDs.loadUrl("javascript:javaUseJs(555)");
                  //此函数可获取js端回调
//                    webIDs.evaluateJavascript("window.javaUseJs('"+_strValue+"')", new ValueCallback<String>() {
//                        @Override
//                        public void onReceiveValue(String s) {
                            //此处为 js 返回的结果
//                        }
//                    });
                    break;
                default:
                    break;
            }
        }
    };


    final WebViewClient webViewClient = new WebViewClient() {
        //记录页面是否已成功加载
        private boolean isPageLoaded = false;

        //设置是否交由内置的webview来处理加载页面的操作
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            // 重置加载状态
            isPageLoaded = false;
            return super.shouldOverrideUrlLoading(view, request);
        }

        //在webview开始加载URL时回调，方便开发者做一些操作
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            webViewLoading.setVisibility(View.VISIBLE);
            isPageLoaded = false;
        }

        //在加载完当前页面时的回调方法
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            // 页面成功加载完成
            isPageLoaded = true;
            webViewLoading.setVisibility(View.GONE);
            webIDs.setVisibility(View.VISIBLE);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();  // 接受所有网站的证书
            Toast.makeText(MainActivity.this,"URL加载失败:"+error,Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                // 忽略页面已成功加载后的错误
                if (isPageLoaded) {
                    Toast.makeText(MainActivity.this, "URL加载成功"+isPageLoaded, Toast.LENGTH_SHORT).show();
                    return;
                }
                Toast.makeText(MainActivity.this, "网络连接不稳定，即将重试..."+isPageLoaded, Toast.LENGTH_SHORT).show();

                // 延迟后重新加载
                handlerWebErr.postDelayed(() -> {
                    webIDs.reload();
                }, 2500);
        }
    };


    public void initMedAudio(){
        if (player == null) {
            player = new SimpleExoPlayer.Builder(this).build();
            // 仅添加一次全局监听器
            player.addListener(globalPlayerListener);
        }
    }

    // ❷ 封装通知JS方法（统一处理线程+状态检查）
    private void notifyJs(String method, String param) {
        // 检查Activity状态，避免销毁后调用
        if (isFinishing() || isDestroyed() || webIDs == null) {
            Log.w("mediaplay", "Activity已销毁，跳过JS通知");
            return;
        }
        // 确保在主线程执行
        runOnUiThread(() -> {
            try {
                webIDs.loadUrl("javascript:" + method + "('" + param + "')");
            } catch (Exception e) {
                Log.e("mediaplay", "通知JS失败: " + e.getMessage());
            }
        });
    }


    /**
     * 以下方法提供给webview中的JS调用————————————————————————————————————————————————————————————————————start
     */

    // 获取设备唯一码
    @JavascriptInterface
    public void getDeviceID(){
        String localID_ = DeviceIdUtil.getDeviceId(MainActivity.this);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webIDs.loadUrl("javascript:webGetDeviceId('"+ localID_ +"')");
            }
        });
    }

    // 播放音频文件
    @JavascriptInterface
    public void mediaFilePlay(String audioInfo){

        if (audioInfo == null || audioInfo.trim().isEmpty()) {
            Log.e("mediaplay", "音频Uri为空");
            notifyJs("mediaPlayOver", "error");
            return;
        }

        // ❸ 切换到主线程操作播放器（使用ExoPlayer工具类判断主线程）
        // 改用原生API判断主线程（无依赖风险）
        if (Looper.getMainLooper() == Looper.myLooper()) {
            doPlayAudio(audioInfo);
        } else {
            new Handler(Looper.getMainLooper()).post(() -> doPlayAudio(audioInfo));
        }
    }
    /**
     * 以上方法提供给webview中的JS调用————————————————————————————————————————————————————————————————————end
     */

    // ❹ 实际播放逻辑（主线程执行）
    private void doPlayAudio(String audioInfo) {
        // 双重检查播放器是否初始化
        if (player == null) {
            initMedAudio();
        }
        try {
            // 重置播放器：清空旧媒体源，避免冲突
            player.stop();
            player.clearMediaItems();

            // 设置本地媒体源
//          int resId = R.raw.dwgm;
//          Uri uri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resId);
//          MediaItem mediaItem = MediaItem.fromUri(uri);

            // 设置新媒体源并准备
            MediaItem mediaItem = MediaItem.fromUri(audioInfo);
            player.setMediaItem(mediaItem);
            player.prepare();
        } catch (Exception e) {
            Log.e("mediaplay", "播放准备失败: " + e.getMessage());
            notifyJs("mediaPlayOver", "error");
        }
    }


    /**
     * 重写按键操作处理方法
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event){
        //如果为按下back键操作并且webview能返回前一页，则设置返回
        if ((keyCode== KeyEvent.KEYCODE_BACK)&&webIDs.canGoBack()){
            webIDs.goBack();
            return true;
        }
        return super.onKeyDown(keyCode,event);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        // 1. 移除生命周期观察者
        getLifecycle().removeObserver(lifecycleObserver);

        // 2. 释放播放器（核心：移除监听器+释放+置空）
        if (player != null) {
            player.removeListener(globalPlayerListener); // 移除监听器，切断引用
            player.release();
            player = null;
        }

        // 3. 清理Handler，避免延迟任务执行
        if (handlerWebErr != null) {
            handlerWebErr.removeCallbacksAndMessages(null);
            handlerWebErr = null;
        }

        // 4. 释放WebView（避免泄漏）
        if (webIDs != null) {
            webIDs.removeAllViews();
            webIDs.destroy();
            webIDs = null;
        }
    }
}