package com.example.tyre;


import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.android.hdhe.uhf.reader.UhfReader;
import com.android.hdhe.uhf.readerInterface.TagModel;
import com.example.tyre.databinding.ActivityUpBinding;
import com.example.tyre.entity.AjaxResult;
import com.example.tyre.entity.BaseCar;
import com.example.tyre.entity.BaseTyre;
import com.example.tyre.entity.EPC;
import com.example.tyre.maintenance.base.MyRecultCall;
import com.example.tyre.maintenance.base.MyResult;
import com.example.tyre.util.CarSelectionDialog;
import com.example.tyre.util.CommonDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.SharedPreferencesUtils;
import com.example.tyre.util.Util;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
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 okhttp3.MediaType;
import okhttp3.RequestBody;

public class UpActivity extends AllBaseActivity implements AdapterView.OnItemSelectedListener {

    // 防抖延迟时间 (毫秒)
    private static final long DEBOUNCE_DELAY = 500;
    public MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    TextView EPC;
    TextView azlw;
    Spinner condition;
    EditText start;
    Button searchButton;
    Button ok;
    Button back;
    TextView th;
    TextView zbh;
    EditText car;
    long lastTime;
    long nextTime;
    String min = "EC0001012026010100000001"; // 左边界（包含）
    String max = "EC0001012026010100100000"; // 右边界（包含）
    private ActivityUpBinding binding;
    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>();
    private Toast mToast;
    private Toast toast;
    private KeyReceiver keyReceiver;
    private boolean dataType;
    private List<String> locationList;
    private String location;
    // 用于存储最后一次扫描到的 EPC
    private String lastScannedEpc;
    private BaseTyre baseTyreResult;
    // 用于处理防抖逻辑的 Handler
    private Handler debounceHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1 && lastScannedEpc != null) {
                // 延迟时间到，执行查询
                showLoadingDialog();
                if (isInRange(lastScannedEpc, min, max)) {
                    // 查询车辆数据方法
                    findCar(lastScannedEpc);
                } else {
                    find(lastScannedEpc);
                }
                lastScannedEpc = null; // 清空，等待下一次扫描
            }
            return true;
        }
    });

    /**
     * 判断字符串是否在指定的区间内（包含边界）
     *
     * @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;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityUpBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        listEPC = new ArrayList<EPC>();


        showLoadingDialog();

        Thread thread = new InventoryThread();
        thread.start();
        Util.initSoundPool(this);

        Intent intent = getIntent();

        if (intent.getBooleanExtra("dataType", false)) dataType = true;
        else dataType = false;
        if (dataType) {
            // 从保养跳转过来的

            location = intent.getStringExtra("location");
            binding.azlw.setText(location);
            binding.car.setText(intent.getStringExtra("carNo"));
            binding.start.setText(intent.getStringExtra("licheng"));
            progressDialog.dismiss();
        } else {
            condition.setOnItemSelectedListener(this);
            check_spinner();
        }
        locationList = new ArrayList<>() {{
            add("左前轮");
            add("右前轮");
            add("右内轮");
            add("右外轮");
            add("左内轮");
            add("左外轮");
        }};

    }

    private void bindViews() {
        EPC = binding.epc;
        azlw = binding.azlw;
        condition = binding.condition;
        start = binding.start;
        searchButton = binding.searchButton;
        ok = binding.ok;
        back = binding.back;
        th = binding.th;
        zbh = binding.zbh;
        car = binding.car;
    }

    private void setupClickListeners() {
        binding.ok.setOnClickListener(v -> {
            String rfid = EPC.getText().toString();
            String carNo = car.getText().toString();
            String millage = start.getText().toString();
            String wheel = azlw.getText().toString();
            String selfNo = zbh.getText().toString();

            if (rfid == null || rfid.isEmpty()) {
                new CommonDialog(UpActivity.this).setMessage("请扫描轮胎！").show();
                return;
            }
            if (carNo == null || carNo.isEmpty()) {
                new CommonDialog(UpActivity.this).setMessage("请选择安装车辆！").show();
                return;
            }
            if (millage == null || millage.isEmpty()) {
                new CommonDialog(UpActivity.this).setMessage("请输入起始里程！").show();
                return;
            }
            if (wheel == null || wheel.isEmpty()) {
                new CommonDialog(UpActivity.this).setMessage("请选择安装轮位！").show();
                return;
            }
            if (selfNo == null || selfNo.isEmpty()) {
                new CommonDialog(UpActivity.this).setMessage("请输入自编号！").show();
                return;
            }
            up_insert(rfid, carNo, millage, wheel, selfNo);
            showLoadingDialog();
        });

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

        binding.searchButton.setOnClickListener(v -> {
            String carNo = car.getText().toString();
            if (carNo == null || carNo.isEmpty()) {
                new CommonDialog(UpActivity.this).setMessage("请输入车牌号！").show();
                return;
            }
            showLoadingDialog();
            car_spinner(carNo);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (dataType) {
            // 从保养跳转过来的
            binding.azlw.setText(location);
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        registerReceiver();
    }

    @Override
    public void onPause() {
        startFlag = false;
        super.onPause();
        unregisterReceiver();
    }

    @Override
    protected void onDestroy() {
        startFlag = false;
        runFlag = false;
        super.onDestroy();
    }

    // EPC add to LISTVIEW
    private void addToList(final List<EPC> list, final String epc, final byte rssi) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                // The epc for the first time
                if (list.isEmpty()) {
                    EPC epcTag = new EPC();
                    epcTag.setEpc(epc);
                    epcTag.setCount(1);
                    epcTag.setRssi(rssi);
                    list.add(epcTag);
                    listepc.add(epc);

                } else {
                    for (int i = 0; i < list.size(); i++) {
                        EPC mEPC = list.get(i);
                        // list contain this epc
                        if (epc.equals(mEPC.getEpc())) {
                            mEPC.setCount(mEPC.getCount() + 1);
                            mEPC.setRssi(rssi);
                            list.set(i, mEPC);
                            break;
                        } else if (i == (list.size() - 1)) {
                            // list doesn't contain this epc
                            EPC newEPC = new EPC();
                            newEPC.setEpc(epc);
                            newEPC.setCount(1);
                            newEPC.setRssi(rssi);
                            list.add(newEPC);
                            listepc.add(epc);
                        }
                    }
                }

                // play sound
                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);
                    if (isInRange(currentEpc, min, max)) {
                        // 请求后台 查询车辆信息
                        // car.setText(currentEpc);
                        // 请求后台
                    } else {
                        EPC.setText(currentEpc);
                        // 请求后台
                        debounceHandler.removeMessages(1);
                    }
                    debounceHandler.removeMessages(1);
                    lastScannedEpc = currentEpc;
                    debounceHandler.sendEmptyMessageDelayed(1, DEBOUNCE_DELAY);
                }

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

    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();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        if (parent.getId() == R.id.condition) {
            azlw.setText(parent.getItemAtPosition(position).toString());
        }

    }

    // 添加缺失的方法
    @Override
    public void onNothingSelected(AdapterView<?> parent) {
    }

    // 提交函数
    private void up_insert(String rfid, String carNo, String millage, String wheel, String selfNo) {
        OkGo.<String>post(MyUrl.url + "/tyre/install/PdaInstallTyre")
                .tag(this)
                .params("tyreRfid", rfid)
                .params("mileage", millage)
                .params("carNo", carNo)
                .params("wheelPostion", wheel)
                .params("selfNo", selfNo)
                .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);
                        if (ajaxResult.getCode().equals("0") && dataType) {
                            Intent intent = new Intent();
                            baseTyreResult.setWheelPostion(wheel);
                            intent.putExtra("json", gson.toJson(baseTyreResult));
                            setResult(RESULT_OK, intent);
                            finish();
                            return;
                        }


                        handleResponse(ajaxResult);
//                try {
//                    Gson gson = new Gson();
//                    BaseTyre baseTyre = gson.fromJson(body, BaseTyre.class);
//                    if (baseTyre != null) {
//                        // 空值处理：若字段为 null 则显示空字符串
//                        String TyreNo = safeGetString(baseTyre.getTyreNo());
//                        th.setText(TyreNo);
//                    }
//                } catch (JsonSyntaxException e) {
//                    return;
//                }
                    }
                });
    }

    private void handleResponse(AjaxResult result) {
        switch (result.getCode()) {
            case "500":
                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
            case "0":
                // 新增轮换
                try {
                    int i = locationList.indexOf(binding.azlw.getText().toString());
                    int size = locationList.size();
                    if (i < size) {
                        i++;
                        binding.azlw.setText(locationList.get(i));
                    } else {
                        binding.azlw.setText(locationList.get(0));
                    }
                } catch (Exception e) {

                }

                new CommonDialog(this).setMessage(result.getMsg()).show();
                break;
        }
    }

    //    基本信息查询
    private void findCar(String carNumber) {
        OkGo.<String>post(MyUrl.url + "/tyre/car/queryCarByRfid").tag(this).params("rfid", carNumber).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                hideLoadingDialog();
                try {
                    Gson gson = new Gson();
                    BaseCar baseCar = gson.fromJson(body, BaseCar.class);
                    if (baseCar != null) {
                        // 空值处理：若字段为 null 则显示空字符串
                        String carNo = safeGetString(baseCar.getCarNo());
                        car.setText(carNo);
                    } else {
                        new CommonDialog(UpActivity.this).setMessage("请检查车辆芯片绑定数据！").show();
                    }
                } catch (JsonSyntaxException e) {
                    return;
                }
            }
        });
    }

    //    基本信息查询
    private void find(String epc) {
        OkGo.<String>post(MyUrl.url + "/tyre/tyre/pdaQueryTyreInfo").tag(this).params("tyreEpc", epc).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                hideLoadingDialog();
                try {
                    Gson gson = new Gson();
                    BaseTyre baseTyre = gson.fromJson(body, BaseTyre.class);

                    if (baseTyre != null) {
                        baseTyreResult = baseTyre;
                        // 空值处理：若字段为 null 则显示空字符串
                        String TyreNo = safeGetString(baseTyre.getTyreNo());
                        th.setText(TyreNo);
                        zbh.setText(baseTyre.getSelfNo());
                    } else {
                        new CommonDialog(UpActivity.this).setMessage("系统无此轮胎！").show();
                        th.setText("");
                        zbh.setText("");
                    }
                } catch (JsonSyntaxException e) {
                    return;
                }
            }
        });
    }

    private String safeGetString(String value) {
        return value == null || "null".equals(value) ? "" : value;
    }

    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 check_spinner() {
        Gson gson = new Gson();
        OkGo.<String>post(MyUrl.url + "/system/dict/data/wheelPositionList").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                hideLoadingDialog();
                String body = response.body();
                List<String> stringList = new ArrayList<>();
                stringList = gson.fromJson(body, new TypeToken<List<String>>() {
                }.getType());
                ArrayAdapter<String> arrayAdapter =
                        new ArrayAdapter<>(UpActivity.this, android.R.layout.simple_list_item_1, stringList);
                condition.setAdapter(arrayAdapter);
            }
        });

        condition.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                azlw.setText(parent.getItemAtPosition(position).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

    }

    private void car_spinner(String carNo) {

        Map<String, String> map = new HashMap<>();
        map.put("carNo", carNo);
        OkGo.<MyResult>post(MyUrl.url + "/tyre/car/PdaQueryCarList").tag(this)
                .upRequestBody(RequestBody.create(JSON, new Gson().toJson(map)))
                .execute(new MyRecultCall(progressDialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        var myResult = response.body();
                        if (myResult.getCode() == 0) {
                            Gson gson = new Gson();
                            List<BaseCar> baseCarList =
                                    gson.fromJson(myResult.getJson(), new TypeToken<List<BaseCar>>() {
                                    }.getType());
                            Log.e("EPC", "listepc:+ " + baseCarList.size());
                            if (baseCarList != null && baseCarList.size() > 0) {
                                List<String> carNoList = new ArrayList<>();
                                for (BaseCar car : baseCarList) {
                                    carNoList.add(car.getCarNo());
                                }
                                // 显示自定义弹窗
                                showCarSelectionDialog(carNoList);

                            }
                        }
                    }
                });
    }

    private void showCarSelectionDialog(List<String> carNoList) {
        CarSelectionDialog dialog = new CarSelectionDialog(this, carNoList);
        dialog.setOnCarSelectedListener(new CarSelectionDialog.OnCarSelectedListener() {
            @Override
            public void onCarSelected(String carNo) {
                car.setText(carNo);
                // 处理选中的车辆
                // 例如设置到EditText或其他控件
                // editTextCarNo.setText(carNo);
            }
        });
        dialog.show();
    }
//        carAdapter.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                car.setText(parent.getItemAtPosition(position).toString());
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//            }
//        });


    class InventoryThread extends Thread {
        byte[] accessPassword = Tools.HexString2Bytes("00000000");
        private List<TagModel> tagList;

        @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();
                    }
                }
            }
        }
    }

    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;
                }
            }
        }

        ;
    }
}
