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.Spinner;
import android.widget.Toast;

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.BaseTyre;
import com.example.tyre.entity.Check;
import com.example.tyre.entity.CheckInfoSpinnerVo;
import com.example.tyre.entity.EPC;
import com.example.tyre.entity.InStoreSpinnerVo;
import com.example.tyre.entity.Tyre;
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.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.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import cn.pda.serialport.Tools;

import com.example.tyre.databinding.ActivityCheckBinding;

public class CheckActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private ActivityCheckBinding binding;

    TextInputEditText epcInput;
    TextInputEditText tyreNoInput;
    TextInputEditText selfNoInput;
    TextInputEditText remarkInput;
    TextInputEditText patternDepthInput;
    TextInputEditText mileageInput;

    TextInputLayout epcLayout;
    TextInputLayout tyreNoLayout;
    TextInputLayout selfNoLayout;
    TextInputLayout mileageNoLayout;
    TextInputLayout patternDepthNoLayout;

    Spinner resultSpinner;
    Spinner checkTypeSpinner;


    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<com.example.tyre.entity.EPC> listEPC;
    private ArrayList<String> listepc = new ArrayList<String>();
    long lastTime;
    long nextTime;
    private Toast mToast;
    private Toast toast;
    private KeyReceiver keyReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCheckBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        listEPC = new ArrayList<EPC>();
        Thread thread = new InventoryThread();
        thread.start();
        Util.initSoundPool(this);
        resultSpinner.setOnItemSelectedListener(this);
        checkTypeSpinner.setOnItemSelectedListener(this);
        check_spinner();
        showLoadingDialog();
    }

    private void bindViews() {
        epcInput = binding.epcDisplay;
        tyreNoInput = binding.th;
        selfNoInput = binding.zbh;
        remarkInput = binding.tyrecon;
        patternDepthInput = binding.patternDepth;
        mileageInput = binding.mileage;

        epcLayout = binding.epcLayout;
        tyreNoLayout = binding.thLayout;
        selfNoLayout = binding.zbhLayout;
        mileageNoLayout = binding.mileageLayout;
        patternDepthNoLayout = binding.patternDepthLayout;

        resultSpinner = binding.result;
        checkTypeSpinner = binding.checkTypeSpinner;
    }

    @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();
    }
    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) {
        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);
                    epcInput.setText(currentEpc);
                    //请求后台
                    debounceHandler.removeMessages(1);
                    lastScannedEpc = currentEpc;
                    debounceHandler.sendEmptyMessageDelayed(1, DEBOUNCE_DELAY);
//                    showLoadingDialog();
//                    find(listepc.get(0).toString());
                }
                clearData();
            }
        });
        Log.e("EPC", "listepc:+ " + listepc);
    }
    private void clearData() {
        // listEPC.removeAll(listEPC);
        // listepc.removeAll(listepc);
        listEPC.clear();
        listepc.clear();
    }
    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);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {


    }

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

    }

    private void setupClickListeners() {
        binding.wc.setOnClickListener(v -> {
            String rfid=epcInput.getText().toString();
            String selectedResult = resultSpinner.getSelectedItem().toString();
            String checkType = checkTypeSpinner.getSelectedItem().toString();
            String remark = remarkInput.getText().toString();
            String mileage = mileageInput.getText().toString().trim();
            String patternDepth = patternDepthInput.getText().toString().trim();
            String tyreNo = tyreNoInput.getText().toString().trim();
            String selfNo = selfNoInput.getText().toString().trim();
            if (rfid == null || rfid.isEmpty() || rfid.equals("等待扫描..."))
            {
                epcLayout.setError("请扫描芯片");
                return;
            }
            if (tyreNo == null || tyreNo.isEmpty())
            {
                tyreNoLayout.setError("请检查胎号数据");
                return;
            }
            if (selfNo == null || selfNo.isEmpty())
            {
                selfNoLayout.setError("请检查自编号数据");
                return;
            }
             showLoadingDialog();
            insert_check_record(rfid,selectedResult,remark,checkType,mileage,patternDepth);
        });

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

    // 防抖延迟时间 (毫秒)
    private static final long DEBOUNCE_DELAY = 500;
    // 用于存储最后一次扫描到的 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();
                performFind(lastScannedEpc);
                lastScannedEpc = null; // 清空，等待下一次扫描
            }
            return true;
        }
    });
    //    基本信息查询
    private void performFind(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) {
                                // 空值处理：若字段为 null 则显示空字符串
                                String TyreNo = safeGetString(baseTyre.getTyreNo());
                                String zb = safeGetString(baseTyre.getSelfNo());
                                tyreNoInput.setText(TyreNo);
                                selfNoInput.setText(zb);
                            }else {
                                new CommonDialog(CheckActivity.this).setMessage("系统无此轮胎！").show();
                                tyreNoInput.setText("");
                                selfNoInput.setText("");
                            }
                        } catch (JsonSyntaxException e) {
                            return;
                        }

                    }
                });
    }
    private String safeGetString(String value) {
        return value == null || "null".equals(value) ? "" : value;
    }
    private void check_spinner() {
        OkGo.<String>post(MyUrl.url + "/system/dict/data/getDictDataList").execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                Gson gson = new Gson();
                hideLoadingDialog();
                CheckInfoSpinnerVo checkInfoSpinnerVo =new CheckInfoSpinnerVo();
                checkInfoSpinnerVo = gson.fromJson(body,CheckInfoSpinnerVo.class);
                List<String> stringList=checkInfoSpinnerVo.getCheckResultList();
                List<String> checkTypeList=checkInfoSpinnerVo.getCheckTypeList();
//                List<String> stringList =new ArrayList<>();
//                stringList = gson.fromJson(body, new TypeToken<List<String>>() {
//                }.getType());
                ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(CheckActivity.this, android.R.layout.simple_list_item_1, stringList);
                resultSpinner.setAdapter(arrayAdapter);
                ArrayAdapter<String> checkTypeAdapter = new ArrayAdapter<>(CheckActivity.this, android.R.layout.simple_list_item_1, checkTypeList);
                checkTypeSpinner.setAdapter(checkTypeAdapter);
            }
        });
//        result.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                //checkresult.setText(parent.getItemAtPosition(position).toString());
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//            }
//        });
//        result.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//            @Override
//            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//               // checktype.setText(parent.getItemAtPosition(position).toString());
//            }
//
//            @Override
//            public void onNothingSelected(AdapterView<?> parent) {
//            }
//        });
    }

    //插质检记录表
    private void insert_check_record(String rfid,String selectedResult,String remark,String checkType,String mileage,String patternDepth){
        OkGo.<String>post(MyUrl.url + "/tyre/check/PdaAddCheck")
                .params("tyreRfid",rfid)
                .params("result",selectedResult)
                .params("remark",remark)
                .params("maintenanceType",checkType)
                .params("mileage",mileage)
                .params("patternDepth",patternDepth)
                .params("CreateBy", SharedPreferencesUtils.getstring("user","admin"))
                .execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                hideLoadingDialog();
                Gson gson = new Gson();
                AjaxResult ajaxResult = gson.fromJson(body, AjaxResult.class);
                handleResponse(ajaxResult);
            }
        });
    }
    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;
        }
    }
}
