package chaoran.business.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.JsonReader;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;
import android.webkit.*;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import chaoran.business.BrandEnum;
import chaoran.business.R;
import chaoran.business.adapter.*;
import chaoran.business.engine.entity.NetworkSetting;
import chaoran.business.engine.impl.NetworkSettingEngine;
import chaoran.business.engine.SettingEngine;
import chaoran.business.engine.impl.TekVoiceEngine;
import chaoran.business.engine.VoiceEngine;
import chaoran.business.service.ScanServiceEDA50P;
import chaoran.business.service.ScanServiceZEBRA;
import chaoran.business.utils.DataCleanManager;
import chaoran.business.utils.LocalAddressUtil;
import chaoran.business.utils.StatusBarUtil;
import chaoran.business.utils.FileChooserHelper;

/**
 * 流程：联网认证设备型号，验证通过，查找设备品牌进行调用驱动操作
 */

/**
 * 提供文字转语音功能，实时播报PDA状态
 */
public class MainActivity extends AppCompatActivity implements ResultListener{

    public static int SCREEN_ROTATION = 3; // 屏幕旋转的设置
    public static int hideBar = 0; // 屏幕旋转的设置

    private WebView webView;
    private Adapter adapter;
    private VoiceEngine voiceEngine;
    private SettingEngine settingEngine;
    private ProgressBar progressBar;
    private ActionBar actionBar;
    private FileChooserHelper fileChooserHelper;
    private LocalAddressUtil localAddressUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            DataCleanManager.clearAllCache(this); // 清空缓存
        }catch (Exception e) {
            e.printStackTrace();
        }

        initView();
        initData();
        //SCREEN_ORIENTATION_USER，不能旋转180，0、90、270都可以旋转
        //SCREEN_ORIENTATION_FULL_SENSOR 都可以旋转，但是在不打开旋转的情况下，一样可以旋转
        //SCREEN_ORIENTATION_FULL_USER 关闭旋转则不会旋转了
        // 取消监听屏幕方向，使用用户的，等出现了问题再来调整；之前有一款pda系统旋转有bug
//        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);
        if (SCREEN_ROTATION == 1) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);//竖
        }else if (SCREEN_ROTATION == 2) {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);//横
        }else if (SCREEN_ROTATION == 3){
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_USER);//随便
        }else if (SCREEN_ROTATION == 5) { // 正竖
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }else if (SCREEN_ROTATION == 6) {// 倒竖
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
        }else if (SCREEN_ROTATION == 7) {// 正横
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        }else if (SCREEN_ROTATION == 8) {// 倒横
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }else {
            this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); // 禁止
        }
//        myOrientationDetector = new MyOrientationDetector(this, this);
//        myOrientationDetector.enable();

    }

    public static String readInitFile(Context context) {
        StringBuffer init = new StringBuffer();
        try {
        AssetManager assetManager = context.getAssets();
            // 打开文件输入流
            InputStream inputStream = assetManager.open("init.json");
            // 使用BufferedReader进行逐行读取
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                init.append(line);
            }
            reader.close();
        } catch (IOException e) {
            Log.e("AssetError", "Failed to read asset file: init.json", e);
        }
        return init.toString();
    }

    private void initData() {
        BrandEnum brand = BrandEnum.code(Build.MANUFACTURER);
        Toast.makeText(this, Build.MANUFACTURER, Toast.LENGTH_LONG).show();
        Log.i("brand===",brand.toString());
        switch (brand) {
            case UROBO:
                adapter = new UroBoAdapter(this, this);
                break;
            case ROCKCHIP:
                adapter = new RockChipAdapter(this, this);
                break;
            case IDATA:
                adapter = new IDataAdapter(this, this);
                break;
            case ALPS:
                adapter = new AlpsAdapter(this, this);
                break;
            case SEUIC:
                adapter = new SeuicAdapter(this, this);
                break;
            case HONEY_WELL_EDA50P:
                // 51、56都是同一个code
            case HONEY_WELL_EDA51:
                if (
                        "eda50p".equals(Build.MODEL.toLowerCase())
                        || "eda51".equals(Build.MODEL.toLowerCase())
                        || "tc26".equals(Build.MODEL.toLowerCase())
                ) {
                    // 走服务模式
                    adapter = new HoneywellAdapter(this, this);
                }else {
                    // 走广播模式
                    adapter = new HoneywellEda56Adapter(this, this);
                }
                break;
            case ZEBRA_TECHNOLOGIES:
                adapter = new ZebraAdapter(this, this);
                break;
            case HISENSE:
                adapter = new HisenseAdapter(this, this);
                break;
            case LACHESIS:
                adapter = new LachesisAdapter(this, this);
                break;
            case UROVO:
                adapter = new UrovoAdapter(this, this);
                break;
            case HKWS:
            case HKWS2:
                adapter = new HkwsAdapter(this, this);
                break;
            case NEW_LAND:
                adapter = new NewlandAdapter(this, this);
                break;
            case IOT_DEVICE:
                adapter = new IOT_DeviceAdapter(this, this);
                break;
            case QUALCOMM:
                adapter = new QualcommAdapter(this, this);
                break;
            case HORIEMTECH:
                adapter = new HoriemtechAdapter(this, this);
                break;
            case AIFUU:
                adapter = new AifuuAdapter(this, this);
                break;
            default:
                adapter = new DefaultAdapter(this, this);
        }
        if (null != adapter) {
            adapter.start();
        }
    }
    @SuppressLint("JavascriptInterface")
    private void initView() {
        actionBar = getSupportActionBar();
        voiceEngine = new TekVoiceEngine(this);
        settingEngine = new NetworkSettingEngine(this);
        fileChooserHelper = new FileChooserHelper(this);
        webView = findViewById(R.id.webView);
        progressBar = findViewById(R.id.loading);
        webView.setWebViewClient(disposeView());
        webView.setWebChromeClient(createWebChromeClient());
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);



        //设置接口进行windows暴露
        settings.setDomStorageEnabled(true);
        //语音引擎
        webView.addJavascriptInterface(voiceEngine, "TekVoiceEngine");
        //网络设置展示
        webView.addJavascriptInterface(settingEngine, "NetworkSettingEngine");
        //重新加载页面
        webView.addJavascriptInterface(this, "View");
        localAddressUtil = new LocalAddressUtil(this, this, webView);
        webView.addJavascriptInterface(localAddressUtil, "Localpda");
        webView.loadUrl(url());
//        StatusBarUtil.transparencyBar( this); // 设置全部透明，需要在页面设置一个参数进行布局的样式跳转，不同的手机端，状态栏高度不一样（apk设置状态栏高度无效，这个是安卓9的一个bug），所以在此采取隐藏状态栏
        if (hideBar == 1) {
            StatusBarUtil.hideStatusBar( this); // 设置全部透明
        }
    }

    private boolean isPageFinished = false; // 新增标志位

    /**
     * 创建WebChromeClient以支持文件选择
     */
    private WebChromeClient createWebChromeClient() {
        return new WebChromeClient() {
            // For Android 5.0+
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                                             FileChooserParams fileChooserParams) {
                // 检查是否接受图片
                String[] acceptTypes = fileChooserParams.getAcceptTypes();
                boolean acceptImage = false;
                boolean acceptCamera = false;
                boolean cameraOnly = false;

                if (acceptTypes != null && acceptTypes.length > 0) {
                    for (String type : acceptTypes) {
                        if (type.contains("image")) {
                            acceptImage = true;
                            break;
                        }
                    }
                }

                // 检查capture模式
                if (fileChooserParams.isCaptureEnabled()) {
                    acceptCamera = true;
                    
                    // 注意：Android WebView中，capture="user"或capture="environment"都会返回true
                    // 我们通过简单的方式判断：如果是图片且启用capture，默认显示选择器
                    // 只有在特定情况下才直接打开相机
                    
                    // 这里我们不设置cameraOnly=true，让所有capture都显示选择器
                    // 如果需要仅相机模式，可以通过其他方式（如URL参数）来控制
                }

                fileChooserHelper.openFileChooser(filePathCallback, acceptImage, acceptCamera, cameraOnly);
                return true;
            }
        };
    }

    //配置客户端
    private WebViewClient disposeView() {
        return new WebViewClient() {
            //页面开始加载时
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                progressBar.setVisibility(View.VISIBLE);
                isPageFinished = false;
            }

            //页面加载完成时
            @Override
            public void onPageFinished(WebView view, String url) {
                if (!url.startsWith("file"))
                    actionBar.hide();
                else
                    actionBar.show();
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.INVISIBLE);
                isPageFinished = true;
            }

            //网络发生错误时,先展示错误界面，然后关闭加载条
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                setHtml(webView, errorCode);
                actionBar.show();
                actionBar.setTitle(R.string.title_activity_main);
                super.onReceivedError(view, errorCode, description, failingUrl);
                progressBar.setVisibility(View.INVISIBLE);
            }

            private void setHtml(WebView view, int errorCode) {
                switch (errorCode) {
                    // https://www.apiref.com/android-zh/android/webkit/WebViewClient.html；根据这个code进行的设置
                    // -数的都是有
                    case -2:
                    case -6:
                    case -8:
                        webView.loadUrl("file:///android_asset/error/netError.html");
                        break;
                    case 404:
                    case -14:
                    case -12:
                        webView.loadUrl("file:///android_asset/error/404.html");
                        break;
                    case 500:
                        webView.loadUrl("file:///android_asset/error/500.html");
                        break;
                    default:
                        webView.loadUrl("file:///android_asset/error/index.html");
                }
            }

            private void handleReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                if (isPageFinished) {
                    // 页面已加载完成，交由 JS 处理错误
                    String jsError = String.format("javascript:handleWebError(%d, '%s')", error.getErrorCode(), error.getDescription());
                    view.loadUrl(jsError);
                } else {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        setHtml(webView, error.getErrorCode());
                    }
                    actionBar.show();
                    actionBar.setTitle(R.string.title_activity_main);
                }
                progressBar.setVisibility(View.INVISIBLE);
                super.onReceivedError(view, request, error);
            }

            //安卓6.0以上发生错误时回调
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                handleReceivedError(view, request, error);
            }
        };
    }


    @Override
    protected void onResume() {
        //再次唤醒该页面时，重新加载页面和语音配置
        //webView.loadUrl(url());
     //   voiceEngine.reload();
        super.onResume();
        if (adapter != null) {
            adapter.stop2();
            adapter.start();
        }
//        int rotate = 1;
//        if (startDirection == 1) {
//            rotate = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; // 正竖屏
//        }else if (startDirection == 2) {
//            rotate = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; // 倒竖屏
//        }else if (startDirection == 3) {
//            rotate = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; // 正横屏
//        }else if (startDirection == 4) {
//            rotate = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; // 倒横屏
//        }
//        this.setRequestedOrientation(rotate);
    }

    @Override
    @SuppressLint("SetJavaScriptEnabled")
    public void result(String result) {
        runOnUiThread(() -> webView.loadUrl("javascript:render(\'" + result + "\')"));
    }
    @Override
    protected void onDestroy() {
        if (adapter != null) {
            adapter.stop();
        }
        super.onDestroy();
        if (diPlayer != null) {
            diPlayer.stop();
            diPlayer.release();
            diPlayer = null;
        }
        if (duPlayer != null) {
            duPlayer.stop();
            duPlayer.release();
            duPlayer = null;
        }
        if (dingPlayer != null) {
            dingPlayer.stop();
            dingPlayer.release();
            dingPlayer = null;
        }
        if (vibrator != null) {
            vibrator.cancel();
        }
        completionListener = null;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_setting_network:
                startActivity(new Intent(this, NetworkSettingActivity.class));
                break;
            case R.id.action_setting_voice:
                startActivity(new Intent(this, VoiceSettingActivity.class));
                break;
            case R.id.action_file_test:
                startActivity(new Intent(this, FileTestActivity.class));
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //拼接url
    private String url() {
        SharedPreferences spf = this.getSharedPreferences("crtech", Context.MODE_PRIVATE);
        Integer port = spf.getInt("port", -1);
        Map<String, Object> map = null;
        if (port == -1) {
            try {
                String init = readInitFile(this);
//                String init = null;
                if (init != null && init.length() > 0) {
                    Gson gson = new Gson();
                    map = gson.fromJson(init, new TypeToken<Map<String, Object>>(){}.getType());
                    // 说明采取了配置，并且存在ip才认为是一个合法的json配置
                    if (map.containsKey("ip") && map.get("ip").toString().length() > 0) {
                        NetworkSetting initData = new NetworkSetting();
                        initData.setAddress(map.get("ip").toString());
                        initData.setPort(Integer.parseInt(map.get("port").toString()));
                        initData.setPath(map.get("path").toString());
                        initData.setScreen_rotation(Integer.parseInt(map.getOrDefault("screen_rotation", "3").toString()));
                        initData.setHide_bar(Integer.parseInt(map.getOrDefault("hide_bar", "0").toString()));
                        settingEngine.saveSetting(initData);
                        spf = this.getSharedPreferences("crtech", Context.MODE_PRIVATE);
                        port = initData.getPort();
                    }else {
                        map = null;
                    }
                }
            }catch (Exception e) {
                Log.e("MainActivity", "get init file error");
                return "file:///android_asset/demo/index.html";
            }
            if (map == null) {
                return "file:///android_asset/demo/index.html";
            }
        }
        String address = spf.getString("address", "").replaceAll(" ", "");
        String path = spf.getString("path", "").replaceAll(" ", "");
        String link = address.concat(":").concat(String.valueOf(port)).concat(path);
        SCREEN_ROTATION = spf.getInt("screen_rotation", 3);
        hideBar = spf.getInt("hide_bar", 0);
        return link.startsWith("http://") ? link : "http://".concat(link);
    }

    @JavascriptInterface
    public void reload() {
        runOnUiThread(() -> {
            webView.loadUrl(url());
        });
    }
    private MediaPlayer diPlayer = null;
    private MediaPlayer duPlayer = null;
    private MediaPlayer dingPlayer = null;
    private String ttsNr;
    public Vibrator vibrator;

    @JavascriptInterface
    public void play(String msg, String type, int isZd) throws IOException {
        ttsNr = msg;
        if ("1".equals(type)) {
            if (diPlayer == null) {
                diPlayer = MediaPlayer.create(this, R.raw.didi);
                diPlayer.setOnCompletionListener(completionListener);
            }
            diPlayer.start();
        } else if ("2".equals(type)) {
            if (duPlayer == null) {
                duPlayer = MediaPlayer.create(this, R.raw.dudu);
                duPlayer.setOnCompletionListener(completionListener);
            }
            duPlayer.start();
        } else if ("10".equals(type)) {
            if (dingPlayer == null) {
                dingPlayer = MediaPlayer.create(this, R.raw.ding);
                dingPlayer.setOnCompletionListener(completionListener);
            }
            dingPlayer.start();
        } else {
            //isZd = 1;
            if (voiceEngine != null) {
                voiceEngine.startSpeaking(msg);
            }
        }
        if (isZd == 1) {
            if (vibrator == null) {
                vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
            }
            vibrator.vibrate(2000);
        }
    }

    private MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
        // @Override
        public void onCompletion(MediaPlayer mp) {
            if (ttsNr != null) {
                if (voiceEngine != null) {
                    voiceEngine.startSpeaking(ttsNr);
                }
                ttsNr = null;
            }
        }
    };

    @SuppressLint("JavascriptInterface")
    @JavascriptInterface
    public void openIndex() throws IOException {
        runOnUiThread(() -> {
            webView.loadUrl("file:///android_asset/demo/index.html");
        });
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onBackPressed() {
        // 创建退出确认对话框
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage("是否退出程序？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish(); // 关闭当前 Activity
                        // 如果需要彻底退出应用（适用于多任务场景），可以添加：
                        // System.exit(0);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
        // 不调用 super.onBackPressed()，避免直接退出
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (!fileChooserHelper.onActivityResult(requestCode, resultCode, data)
                && (localAddressUtil == null || !localAddressUtil.onActivityResult(requestCode, resultCode, data))) {
            // 如果不是文件选择器的结果，可以在这里处理其他结果
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (!fileChooserHelper.onRequestPermissionsResult(requestCode, permissions, grantResults)
                && (localAddressUtil == null || !localAddressUtil.onRequestPermissionsResult(requestCode, permissions, grantResults))) {
            // 如果不是文件选择器的权限请求，可以在这里处理其他权限请求
        }
    }
}