package com.example.tyre;

import android.annotation.SuppressLint;
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.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
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.adapter.CarRecordAdapter;
import com.example.tyre.databinding.ActivityTyreLayoutBinding;
import com.example.tyre.entity.BaseCar;
import com.example.tyre.entity.CarLifecycleDTO;
import com.example.tyre.entity.CarMaintenanceLifecycleDTO;
import com.example.tyre.entity.EPC;
import com.example.tyre.maintenance.base.MyRecultCall;
import com.example.tyre.maintenance.base.MyResult;
import com.example.tyre.maintenance.been.BaseTyre;
import com.example.tyre.util.CarSelectionDialog;
import com.example.tyre.util.CommonDialog;
import com.example.tyre.util.MyUrl;
import com.example.tyre.util.Util;
import com.google.android.material.textfield.TextInputEditText;
import com.google.android.material.textfield.TextInputLayout;
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 TyreLayoutActivity extends AppCompatActivity implements CarRecordAdapter.ItemClickCall {

    // 防抖延迟时间 (毫秒)
    private static final long DEBOUNCE_DELAY = 500;
    public MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    TextInputEditText etPlateNumber;
    Button btnRetrieve;
    TextInputLayout tilPlateNumber;
    long lastTime;
    long nextTime;
    String min = "EC0001012026010100000001"; // 左边界（包含）
    String max = "EC0001012026010100100000"; // 右边界（包含）
    private ActivityTyreLayoutBinding binding;
    private ProgressDialog progressDialog;
    private boolean isStart = true;
    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 CarRecordAdapter adapter;
    // 用于存储最后一次扫描到的 EPC
    private String lastScannedEpc;
    // 用于处理防抖逻辑的 Handler
    private Handler debounceHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == 1 && lastScannedEpc != null) {
                // 延迟时间到，执行查询
                showLoadingDialog();

                // 查询车辆数据方法
                findCar(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;
    }

    // 点击item
    @Override
    public void onClick(int position) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityTyreLayoutBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        listEPC = new ArrayList<EPC>();
        Thread thread = new InventoryThread();
        thread.start();
        Util.initSoundPool(this);
        tilPlateNumber = binding.tilPlateNumber;
        etPlateNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                tilPlateNumber.setError(null);
            }
        });
        tilPlateNumber.setEndIconOnClickListener(v -> {
            String plateNumber = etPlateNumber.getText().toString().trim();
            if (!plateNumber.isEmpty()) {
                showLoadingDialog();
                performSearchOld(plateNumber);
            } else {
                tilPlateNumber.setError("车牌号不能为空");
            }
        });
        adapter = new CarRecordAdapter(this, this);
        binding.setAdapter(adapter);
    }

    private void bindViews() {
        etPlateNumber = binding.etPlateNumber;
        btnRetrieve = binding.btnRetrieve;
        tilPlateNumber = binding.tilPlateNumber;
    }

    private void setupClickListeners() {
        binding.btnRetrieve.setOnClickListener(v -> {
            String PlateNumber = etPlateNumber.getText().toString();
            if (PlateNumber == null || PlateNumber.isEmpty()) {
                new CommonDialog(TyreLayoutActivity.this).setMessage("请输入车牌号！").show();
                return;
            }
            carBangding(PlateNumber);
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        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();
    }

    private void selectInfo(String carNo) {
        OkGo.<MyResult>get(MyUrl.url + "/tyre/car/lifecycle/" + carNo)
                .execute(new MyRecultCall(progressDialog, this) {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        MyResult body = response.body();
                        if (body.getCode() == 0) {
                            CarLifecycleDTO carLifecycleDTO =
                                    new Gson().fromJson(body.getJson(), CarLifecycleDTO.class);
                            List<CarMaintenanceLifecycleDTO> maintenanceList =
                                    carLifecycleDTO.getMaintenanceList();
                            if (maintenanceList != null && !maintenanceList.isEmpty()) {
                                adapter.setList(maintenanceList);
                                adapter.notifyDataSetChanged();
                            }
                            // 轮位显示
                            List<BaseTyre> mountedTyres = carLifecycleDTO.getMountedTyres();
                            mountedTyres.forEach(tire -> {
                                String wheelPostion = tire.getWheelPostion();
                                initTire(wheelPostion, tire);

                            });
                            //     显示里程
                            binding.selectInfoMileage.setText(carLifecycleDTO.getCar().getInputMileage());

                        }

                    }
                });
    }

    // 初始化轮胎信息
    private void initTire(String wheelPostion, com.example.tyre.maintenance.been.BaseTyre baseTyre) {
        binding.setTire1(new com.example.tyre.maintenance.been.BaseTyre());
        binding.setTire2(new com.example.tyre.maintenance.been.BaseTyre());
        binding.setTire3(new com.example.tyre.maintenance.been.BaseTyre());
        binding.setTire4(new com.example.tyre.maintenance.been.BaseTyre());
        binding.setTire5(new com.example.tyre.maintenance.been.BaseTyre());
        binding.setTire6(new com.example.tyre.maintenance.been.BaseTyre());
        switch (wheelPostion) {
            case "左前轮":
                binding.setTire1(baseTyre);
                break;
            case "右前轮":
                binding.setTire2(baseTyre);
                break;
            case "左外轮":
                binding.setTire3(baseTyre);
                break;
            case "左内轮":
                binding.setTire4(baseTyre);
                break;

            case "右内轮":
                binding.setTire5(baseTyre);
                break;
            case "右外轮":
                binding.setTire6(baseTyre);
                break;
        }
    }

    // 检索车牌号
    private void performSearchOld(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)))
                .params("carNo", carNo)
                .execute(
                        new MyRecultCall(progressDialog, this) {
                            @Override
                            public void onSuccess(Response<MyResult> response) {
                                super.onSuccess(response);
                                var body = response.body();
                                if (body.getCode() == 0) {
                                    Gson gson = new Gson();

                                    List<BaseCar> baseCarList =
                                            gson.fromJson(body.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);
                                    }
                                }
                            }
                        }
                        /*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);




                        }
                    }
                }*/);
    }

    private void showCarSelectionDialog(List<String> carNoList) {
        CarSelectionDialog dialog = new CarSelectionDialog(this, carNoList);
        dialog.setOnCarSelectedListener(new CarSelectionDialog.OnCarSelectedListener() {
            @Override
            public void onCarSelected(String carNo) {
                // 处理选中的车辆
                etPlateNumber.setText(carNo);
                selectInfo(carNo);// 检索车辆信息
            }
        });
        dialog.show();
    }

    private void carBangding(String PlateNumber) {
        OkGo.<String>post(MyUrl.url + "/tyre/tyre/getCarBingTire")
                .tag(this).params("carNo", PlateNumber)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        // hideLoadingDialog();
                        String body = response.body();
                        Gson gson = new Gson();
//                        List<BaseTyre> baseTyreList = gson.fromJson(body, BaseTyre.class);
                        List<BaseTyre> baseTyreList =
                                gson.fromJson(body, new com.google.gson.reflect.TypeToken<List<BaseTyre>>() {
                                }.getType());
                        bindDataToViews(baseTyreList);
                    }
                });
    }
//    private void bindDataToViews(List<BaseTyre> dataList) {
//        // 假设 dataList.get(0) 是左前轮，dataList.get(1) 是右前轮...
//        // 请根据你实际的列表顺序调整索引
//
//        if (dataList.size() >= 2) {
//            // 绑定左前轮
//            updateTireView(findViewById(R.id.tire_left_front), dataList.get(0));
//
//            // 绑定右前轮
//            updateTireView(findViewById(R.id.tire_right_front), dataList.get(1));
//
//            // 绑定其他轮胎...
//            // updateTireView(findViewById(R.id.tire_left_mid), dataList.get(2));
//        }
//    }

    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());
                        etPlateNumber.setText(carNo);
                    } else {
                        new CommonDialog(TyreLayoutActivity.this).setMessage("请检查车辆芯片绑定数据！").show();
                    }
                } catch (JsonSyntaxException e) {
                    return;
                }
            }
        });
    }

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

    /**
     * 核心方法：将数据绑定到具体的 Include 视图上
     */
    private void bindDataToViews(List<BaseTyre> dataList) {
        if (dataList == null) return;

        // 遍历列表，根据具体位置找到对应的 View
        for (BaseTyre tyre : dataList) {
            View targetView = null;

            // 根据后端返回的位置字段判断要更新哪个布局
            // 假设 tyre.getPosition() 返回 "LF" (左前), "RF" (右前) 等
            String pos = tyre.getWheelPostion();

            if ("左前轮".equals(pos) || "1".equals(pos)) {
                targetView = findViewById(R.id.tire_left_front);
                TextView viewById = targetView.findViewById(R.id.iv_tire_icon);
                viewById.setText("左前轮");
            } else if ("右前轮".equals(pos) || "2".equals(pos)) {
                targetView = findViewById(R.id.tire_right_front);
                TextView viewById = targetView.findViewById(R.id.iv_tire_icon);
                viewById.setText("右前轮");
            } else if ("左内轮".equals(pos)) {
                targetView = findViewById(R.id.tire_middle_left);
                TextView viewById = targetView.findViewById(R.id.iv_tire_icon);
                viewById.setText("左内轮");
            } else if ("右内轮".equals(pos)) {
                targetView = findViewById(R.id.tire_middle_right);
                TextView viewById = targetView.findViewById(R.id.iv_tire_icon);
                viewById.setText("右内轮");
            } else if ("左外轮".equals(pos)) {
                targetView = findViewById(R.id.tire_bottom_left);
                TextView viewById = targetView.findViewById(R.id.iv_tire_icon);
                viewById.setText("左外轮");
            } else if ("右外轮".equals(pos)) {
                targetView = findViewById(R.id.tire_bottom_right);
                TextView viewById = targetView.findViewById(R.id.iv_tire_icon);
                viewById.setText("右外轮");
            }
            // ... 其他位置

            if (targetView != null) {
                updateTireView(targetView, tyre);
            }
        }
    }

    /**
     * 通用方法：更新单个轮胎卡片的 UI
     *
     * @param container include 标签对应的根布局 View
     * @param data      该轮胎的数据对象
     */
    private void updateTireView(View container, BaseTyre data) {
        if (container == null) return;

        // 【关键点】：必须在 container 内部查找控件，而不是在 Activity 中直接查找
        TextView tvBrand = container.findViewById(R.id.tv_brand);
        TextView tvSpec = container.findViewById(R.id.tv_spec);
        TextView tvSelfNo = container.findViewById(R.id.tv_self_no); // 或者是 tv_install_date
        TextView tvDate = container.findViewById(R.id.tv_install_date); // 或者是 tv_install_date
        // 设置数据
        if (tvBrand != null) tvBrand.setText("品牌: " + data.getTyreBrand());
        if (tvSpec != null) tvSpec.setText("规格: " + data.getTyreModel());
        if (tvSelfNo != null) tvSelfNo.setText("自编号: " + data.getSelfNo());
        // if (tvDate != null) tvDate.setText("日期: " + data.getCreateTime());
    }

    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);
                        // 请求后台
                        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 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 showLoadingDialog() {
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("数据加载中...");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void hideLoadingDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    // 1. 定义数据模型类 (对应后台返回的字段)
    public static class TireData {
        public String position; // 轮位名称
        public String brand;    // 品牌
        public String spec;     // 规格
        public String installDate; // 安装日期

        public TireData(String position, String brand, String spec, String installDate) {
            this.position = position;
            this.brand = brand;
            this.spec = spec;
            this.installDate = installDate;
        }
    }

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

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