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.entity.AjaxResult;
import com.example.tyre.entity.BaseCar;
import com.example.tyre.entity.BaseTyre;
import com.example.tyre.entity.EPC;
import com.example.tyre.entity.UpTyre;
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.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.ActivityDownBinding;

public class DownActivity extends AllBaseActivity  {

    private ActivityDownBinding binding;

    TextView EPC;
    TextView car;
    EditText start;
    TextView azlw;
    Button ok;
    Button back;
    TextView th;
    TextView zbh;
    EditText patternDepth;
    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;
    private  CommonDialog commonDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityDownBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        listEPC = new ArrayList<EPC>();
        Thread thread = new InventoryThread();
        thread.start();
        Util.initSoundPool(this);

    }

    private void bindViews() {
        commonDialog = new CommonDialog(DownActivity.this);
        EPC = binding.epc;
        car = binding.car;
        start = binding.start;
        azlw = binding.azlw;
        ok = binding.ok;
        back = binding.back;
        th = binding.th;
        zbh = binding.zbh;
        patternDepth = binding.patternDepth;
        binding.unloadingReason.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if(position==5){
                    binding.unloadingReasonRemark.setVisibility(View.VISIBLE);
                }else{
                    binding.unloadingReasonRemark.setVisibility(View.GONE);
                }
            }

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

            }
        });
    }

    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 depth = patternDepth.getText().toString();
            if (rfid == null || rfid.isEmpty())
            {
                commonDialog.setMessage("请扫描轮胎！").show();
                return;
            }
            if (carNo == null || carNo.isEmpty())
            {
                commonDialog.setMessage("该轮胎未安装！").show();
                return;
            }
            if (millage == null || millage.isEmpty())
            {
                commonDialog.setMessage("请输入卸胎里程！").show();
                return;
            }
            if (wheel == null || wheel.isEmpty())
            {
                commonDialog.setMessage("该轮胎未安装！").show();
                return;
            }
            showLoadingDialog();
            down_insert(rfid,carNo,millage,wheel,depth);
        });

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

    @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);
                }
            }
        });
        Log.e("EPC", "listepc:+ " + listepc);
        if (listepc != null && !listepc.isEmpty()){
            startFlag = false;
            EPC.setText(listepc.get(0).toString());
            //请求后台
            find(listepc.get(0).toString());
        }
        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 find(String epc) {//查询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();
                try {
                    Gson gson = new Gson();
                    BaseTyre baseTyre = gson.fromJson(body, BaseTyre.class);
                    if (baseTyre != null) {
                        // 空值处理：若字段为 null 则显示空字符串
                        String TyreNo = safeGetString(baseTyre.getTyreNo());
                        String carNo = safeGetString(baseTyre.getCarNo());
                        String wheel = safeGetString(baseTyre.getWheelPostion());
                        String zb = safeGetString(baseTyre.getSelfNo());
                        th.setText(TyreNo);
                        zbh.setText(zb);
                        car.setText(carNo);
                        azlw.setText(wheel);
                    }else {
                        commonDialog.setMessage("系统无此轮胎！").show();
                        th.setText("");
                        zbh.setText("");
                    }
                } catch (JsonSyntaxException e) {
                    return;
                }

            }
        });
    }
    private String safeGetString(String value) {
        return value == null || "null".equals(value) ? "" : value;
    }
    //    删除实时表、卸车记录表
    private void down_insert(String rfid,String carNo,String millage,String wheel,String patternDepth) {
        String reason = binding.unloadingReason.getSelectedItem().toString();
        if (reason.isEmpty()){
            commonDialog.setMessage("请选择卸胎原因！").show();
            return;
        }
        if (reason.equals("自定义")){
            reason=binding.unloadingReasonRemark.getText().toString().trim();
        }

        OkGo.<String>post(MyUrl.url + "/tyre/install/PdaUnInstallTyre").tag(this)
                .params("tyreRfid", rfid)
                .params("mileage", millage)
                .params("carNo", carNo)
                .params("wheelPostion", wheel)
                .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;
        }
    }
}
