package com.example.tyre;

import android.app.Activity;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.hdhe.uhf.reader.UhfReader;
import com.android.hdhe.uhf.readerInterface.TagModel;
import com.example.tyre.entity.AjaxResult;
import com.example.tyre.entity.BaseCar;
import com.example.tyre.entity.CarTeamEntity;
import com.example.tyre.entity.EPC;
import com.example.tyre.entity.SysDept;
import com.example.tyre.util.CarSelectionDialog;
import com.example.tyre.util.CarTeamSelectionDialog;
import com.example.tyre.util.CommonDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.PlayMusic;
import com.example.tyre.util.SharedPreferencesUtils;
import com.example.tyre.util.Util;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.pda.serialport.Tools;
import com.example.tyre.databinding.ActivityTestBinding;

public class TestActivity extends AppCompatActivity  {
    private ActivityTestBinding binding;

    Button back;
    EditText deptName;
    Button search;
    TextView in_santext;
    TextView carNo;
    TextView line;
    TextView type;
    Button confirm;
    private boolean isStart = true;
    private ProgressDialog progressDialog;
    private boolean runFlag = true;
    private boolean startFlag = false;
    private UhfReader manager; // UHF manager,UHF Operating handle
    private ArrayList<EPC> listEPC;
    private ArrayList<String> listepc = new ArrayList<String>();
    long lastTime;
    long nextTime;
    private Toast mToast;
    private Toast toast;
    private KeyReceiver keyReceiver;
    private String deptId;
    String min = "EC0001012026010100000001"; // 左边界（包含）
    String max = "EC0001012026010100100000"; // 右边界（包含）
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTestBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        listEPC = new ArrayList<EPC>();
        Thread thread = new InventoryThread();
        deptId=null;
        thread.start();
        Util.initSoundPool(this);

    }

    private void bindViews() {
        back = binding.button;
        deptName = binding.dept;
        search = binding.searchButton;
        in_santext = binding.inSantext;
        carNo = binding.pinpai;
        line = binding.carLine;
        type = binding.carType;
        confirm = binding.confirmButton;
    }

    private void setupClickListeners() {
        binding.button.setOnClickListener(v -> {
            // Intent intent = new Intent(this, HomePageActivity.class);
            // startActivity(intent);
            finish();
        });

        binding.searchButton.setOnClickListener(v -> {
            String carTeam = deptName.getText().toString();
            if (carTeam == null || carTeam.isEmpty())
            {
                new CommonDialog(TestActivity.this).setMessage("请输入车队名称！").show();
                return;
            }
            showLoadingDialog();
            car_team(carTeam);
        });

        binding.confirmButton.setOnClickListener(v -> {
            showLoadingDialog();
            carBangding();
        });
    }
    @Override
    protected void onResume() {
        super.onResume();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        registerReceiver();
    }
    @Override
    public void onBackPressed() {
        hideLoadingDialog();
        Log.e("onBackPressed", "onBackPressed:+ " );
        finish();
//        // 处理返回按钮点击事件
//        if (isStart) {
//            // 如果当前处于开始状态，可以执行退出逻辑
//            finish(); // 或者其他你想要的操作
//        } else {
//            // 否则可以阻止默认的返回行为
//            // super.onBackPressed(); // 取消注释以启用默认返回行为
//        }
    }
    @Override
    public void onPause() {
        startFlag = false;
        super.onPause();
        unregisterReceiver();
    }
    @Override
    protected void onDestroy() {
        startFlag = false;
        runFlag = false;
        super.onDestroy();
    }
    private void carBangding() {
        OkGo.<String>post(MyUrl.url + "/tyre/car/PdaBingCarRfid")
                .tag(this).params("rfid", in_santext.getText().toString())
                .tag(this).params("carNo", carNo.getText().toString())
                .tag(this).params("team", deptId)
                .tag(this).params("line", line.getText().toString())
                .tag(this).params("type", type.getText().toString())
                .params("CreateBy", SharedPreferencesUtils.getstring("user","admin"))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideLoadingDialog();
                        String body = response.body();
                        Gson gson=new Gson();
                        AjaxResult ajaxResult = gson.fromJson(body, AjaxResult.class);
                        handleResponse(ajaxResult);
//                        List<SysDept> sysDeptList = gson.fromJson(body, new TypeToken<List<SysDept>>(){}.getType());
//                        Log.e("SysDept", "sysDeptList:+ " + sysDeptList.size());
//                        if (sysDeptList!=null && sysDeptList.size()>0){
//                            List<CarTeamEntity> carTeamList = new ArrayList<>();
//                            for (SysDept car : sysDeptList) {
//                                CarTeamEntity entity = new CarTeamEntity();
//                                entity.setCarTeamName(car.getDeptName()); // 车队名称
//                                entity.setCarTeamId(String.valueOf(car.getDeptId()));     // 车队ID
//                                carTeamList.add(entity);
//                            }
//                            //显示自定义弹窗
//                            showCarSelectionDialog(carTeamList);
//                        }
                    }
                });
    }
    private void handleResponse(AjaxResult result) {
        switch (result.getCode()) {
            case "500":
                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
            case "0":
                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
        }
    }
    class InventoryThread extends Thread {
        private List<TagModel> tagList;
        byte[] accessPassword = Tools.HexString2Bytes("00000000");
        @Override
        public void run() {
            super.run();
            while (runFlag) {
                if (startFlag) {
                    tagList = manager.inventoryRealTime(); //实时盘存
                    if (tagList != null && !tagList.isEmpty()) {
                        //播放提示音
                        Util.play(1, 0);
                        for (TagModel tag : tagList) {
                            if (tag == null) {
                                String epcStr = "";
//								String epcStr = new String(epc);
                                addToList(listEPC, epcStr, (byte) -1);
                            } else {
                                String epcStr = Tools.Bytes2HexString(tag.getmEpcBytes(), tag.getmEpcBytes().length);
//								String epcStr = new String(epc);
                                byte rssi = tag.getmRssi();
                                addToList(listEPC, epcStr, rssi);
                            }

                        }
                    }
                    tagList = null;
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    // EPC add to LISTVIEW
    private void addToList(final List<EPC> list, final String epc, final byte rssi) {
        // 1. 数据处理 (在当前线程执行，避免频繁切换上下文)
        // 建议给 list 和 listepc 加锁，防止并发修改异常
        synchronized (list) {
            synchronized (listepc) {
                if (list.isEmpty()) {
                    EPC epcTag = new EPC();
                    epcTag.setEpc(epc);
                    epcTag.setCount(1);
                    epcTag.setRssi(rssi);
                    list.add(epcTag);
                    listepc.add(epc);
                } else {
                    boolean found = false;
                    for (EPC mEPC : list) {
                        if (epc.equals(mEPC.getEpc())) {
                            mEPC.setCount(mEPC.getCount() + 1);
                            mEPC.setRssi(rssi);
                            found = true;
                            break;
                        }
                    }
                    if (!found) {
                        EPC newEPC = new EPC();
                        newEPC.setEpc(epc);
                        newEPC.setCount(1);
                        newEPC.setRssi(rssi);
                        list.add(newEPC);
                        listepc.add(epc);
                    }
                }
            }
        }

        Log.e("EPC", "listepc:+ " + listepc);

        // 2. UI 更新 (强制切换到主线程)
        // 使用 in_santext.post 是最稳妥的方式，因为它天然绑定主线程 Looper
        if (in_santext != null) {
            in_santext.post(() -> {
                long lastTime = SystemClock.elapsedRealtime();
                long time = lastTime - nextTime;
                if (time >= 60) {
                    Util.play(1, 0);
                    nextTime = lastTime;
                    Log.e("TAG", "run: " + time);
                }

                if (listepc != null && !listepc.isEmpty()) {
                    startFlag = false;
                    String currentEpc = listepc.get(0).toString();
                    if (isInRange(currentEpc, min, max)) {
                        in_santext.setText(currentEpc);
                    } else {
                        new CommonDialog(this).setMessage("RFID 不在规则范围内！").show();
                    }
                }
                clearData();
            });
        }
    }
    private void clearData() {
        listEPC.removeAll(listEPC);
        listepc.removeAll(listepc);
    }
    private void showLoadingDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("数据加载中...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }
    private void hideLoadingDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    private class KeyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int keyCode = intent.getIntExtra("keyCode", 0);
            if (keyCode == 0) {
                keyCode = intent.getIntExtra("keycode", 0);
            }
            boolean keyDown = intent.getBooleanExtra("keydown", false);
            if (keyDown) {
                if (toast == null) {
                    // toast = Toast.makeText(OutStoreHouseActivity.this, "KeyReceiver:keyCode = down" + keyCode, Toast.LENGTH_SHORT);
                } else {
                    // toast.setText("KeyReceiver:keyCode = down" + keyCode);
                }
                // toast.show();
                switch (keyCode) {
                    case KeyEvent.KEYCODE_F1:
                    case KeyEvent.KEYCODE_F2:
                    case KeyEvent.KEYCODE_F3:
                    case KeyEvent.KEYCODE_F4:
                    case KeyEvent.KEYCODE_F5:
                    case 136:
                        //扫描
                        startFlag = true;
                        break;
                }
            }
        }
    }
    private void registerReceiver() {
        keyReceiver = new KeyReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction("android.rfid.FUN_KEY");
        filter.addAction("android.intent.action.FUN_KEY");
        registerReceiver(keyReceiver, filter);
    }
    private void unregisterReceiver() {
        unregisterReceiver(keyReceiver);
    }

    //查询车队信息
    private void car_team(String carTeam) {
        OkGo.<String>post(MyUrl.url + "/system/dept/PdaQueryDeptList")
                .tag(this).params("deptName", carTeam)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        hideLoadingDialog();
                        String body = response.body();
                        Gson gson=new Gson();
                        List<SysDept> sysDeptList = gson.fromJson(body, new TypeToken<List<SysDept>>(){}.getType());
                        Log.e("SysDept", "sysDeptList:+ " + sysDeptList.size());
                        if (sysDeptList!=null && sysDeptList.size()>0){
                            List<CarTeamEntity> carTeamList = new ArrayList<>();
                            for (SysDept car : sysDeptList) {
                                CarTeamEntity entity = new CarTeamEntity();
                                entity.setCarTeamName(car.getDeptName()); // 车队名称
                                entity.setCarTeamId(String.valueOf(car.getDeptId()));     // 车队ID
                                carTeamList.add(entity);
                            }
                             //显示自定义弹窗
                            showCarSelectionDialog(carTeamList);
                        }
                    }
                });
    }
    private void showCarSelectionDialog(List<CarTeamEntity> carNoList) {
        CarTeamSelectionDialog dialog = new CarTeamSelectionDialog(this, carNoList);
        dialog.setOnCarSelectedListener(new CarTeamSelectionDialog.OnCarSelectedListener() {
            @Override
            public void onCarSelected(String carNo, String carId) {
                deptName.setText(carNo);
                deptId=carId;
                // 处理选中的车辆
                // 例如设置到EditText或其他控件
                Log.e("carId", "carId: " + carId);
            }
        });
        dialog.show();
    }
    /**
     * 判断字符串是否在指定的区间内（包含边界）
     * @param target 要判断的目标字符串
     * @param min 区间左边界
     * @param max 区间右边界
     * @return true=在区间内，false=不在
     */
    public static boolean isInRange(String target, String min, String max) {
        // 空值校验，避免空指针异常
        if (target == null || min == null || max == null) {
            return false;
        }
        // compareTo规则：
        // 1. 字符串相等返回0；
        // 2. 目标字符串 > 对比字符串 返回正数；
        // 3. 目标字符串 < 对比字符串 返回负数。
        // 因此：target >= min 等价于 target.compareTo(min) >= 0；
        //      target <= max 等价于 target.compareTo(max) <= 0。
        return target.compareTo(min) >= 0 && target.compareTo(max) <= 0;
    }
}