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.SystemClock;
import android.util.Log;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.databinding.ObservableBoolean;

import com.android.hdhe.uhf.reader.UhfReader;
import com.android.hdhe.uhf.readerInterface.TagModel;
import com.example.tyre.databinding.ActivityOutStoreHouseBinding;
import com.example.tyre.entity.AjaxResult;
import com.example.tyre.entity.BaseTyre;
import com.example.tyre.entity.EPC;
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.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.List;

import cn.pda.serialport.Tools;

public class OutStoreHouseActivity extends AppCompatActivity {

    TextView scan;
    TextView pinpai;
    TextView xinghao;
    TextView cengji;
    TextView huawen;
    TextView wtbm;
    TextView ltlb;

    long lastTime;
    long nextTime;
    private ActivityOutStoreHouseBinding binding;

    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 KeyReceiver keyReceiver;
    private ObservableBoolean aType;
    private static final int STATE_IDLE = 0;      // 空闲状态，可扫描
    private static final int STATE_LOCKED = 1;    // 锁定状态，禁止下拉
    private int currentSpinnerState = STATE_IDLE;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityOutStoreHouseBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        listEPC = new ArrayList<EPC>();
        Thread thread = new InventoryThread();
        thread.start();
        Util.initSoundPool(this);
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        binding.outTitle.setText(title);
        aType = new ObservableBoolean();
        aType.set(title.equals("轮胎出库"));
        binding.setAType(aType);
    }

    private void bindViews() {
        scan = binding.epc;
        pinpai = binding.pinpai;
        xinghao = binding.xinghao;
        cengji = binding.cengji;
        huawen = binding.huawen;
        wtbm = binding.wtbm;
        ltlb = binding.ltlb;
    }

    private void setupClickListeners() {
        binding.button.setOnClickListener(v -> {
            showLoadingDialog();
            out_inventory(scan.getText().toString(), SharedPreferencesUtils.getstring("user", "admin"));
        });

        binding.back.setOnClickListener(v -> {
            finish();
        });
    }


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

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

    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);
                }
                hideLoadingDialog();
                Log.e("EPC", "listepc:+ " + listepc);
                if (listepc != null && !listepc.isEmpty()) {
                    startFlag = false;
                    scan.setText(listepc.get(0).toString());
                    showLoadingDialog();
                    find(listepc.get(0).toString());
                }
                clearData();
            }
        });

    }

    private void clearData() {
        listEPC.removeAll(listEPC);
        listepc.removeAll(listepc);
    }

    //   基本信息查询
    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) {
                                // 空值处理：若字段为 null 则显示空字符串
                                String brand = safeGetString(baseTyre.getTyreBrand());
                                String tyreno = safeGetString(baseTyre.getTyreNo());
//                        String zb = safeGetString(baseTyre.getSelfNo());
                                String size = safeGetString(baseTyre.getTyreModel());
                                String level = safeGetString(baseTyre.getTyreLevel());
                                String pattern = safeGetString(baseTyre.getTyrePattern());
                                String kind = getTyreType(safeGetString(baseTyre.getTyreType()));
                                String deptId = safeGetString(baseTyre.getDeptId());
                                pinpai.setText(brand);
                                wtbm.setText(tyreno);
//                        zbh.setText(zb);
                                xinghao.setText(size);
                                cengji.setText(level);
                                huawen.setText(pattern);
                                ltlb.setText(kind);
                                String deptNameFromServer = safeGetString(baseTyre.getDeptName()); // 或者 getFactorySite()
                                String[] siteArray = getResources().getStringArray(R.array.zxzd);
                                String tag = null;
                                for (int i = 0; i < siteArray.length; i++) {
                                    tag = siteArray[i];
                                    if (tag.equals(deptNameFromServer)) {
                                        break;
                                    }
                                }
                                binding.outStoreSiteNow.setText(tag);
                                binding.outStoreSiteNow.setBackground(ContextCompat.getDrawable(OutStoreHouseActivity.this, R.drawable.bg_textview_plain));
                                binding.outStoreSiteNow.setEnabled(false);
                                currentSpinnerState = STATE_LOCKED;
                            } else {
                                new CommonDialog(OutStoreHouseActivity.this).setMessage("轮胎不存在！").show();
                            }
                        } catch (JsonSyntaxException e) {
                            // 处理 JSON 解析错误
                            new CommonDialog(OutStoreHouseActivity.this).setMessage("扫描出错！").show();
                            return;
                        }
                    }
                });
    }

    private String safeGetString(String value) {
        return value == null || "null".equals(value) ? "" : value;
    }
    // 出库提交
    private void out_inventory(String epc, String createBy) {

        OkGo.<String>post(MyUrl.url + "/tyre/inventory/pdaOutInventory").tag(this)
                .params("tyreRfid", epc)
                .params("createBy", createBy)
                .params("outType", (aType.get() ? "0" : "1"))
                .params("team",binding.outStoreSite.getSelectedItem().toString())
                .params("deptId", getDeptId(binding.outStoreSite.getSelectedItem().toString()))
                .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);
                        new CommonDialog(OutStoreHouseActivity.this).setMessage(ajaxResult.getMsg()).show();
                    }
                });
    }

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

    public int getDeptId(String name) {
        if (name.equals("光明修理厂")) {
            return 200;
        } else if (name.equals("石岩修理厂")) {
            return 201;
        }else if (name.equals("运维部门")) {
            return 107;
        }
        return 229;
    }
    public String getTyreType(String type) {
        if (type.equals("circulating")) {
            return "周转胎";
        }
        else if (type.equals("renovate")) {
            return "翻新胎";
        }
        else if (type.equals("experimental")) {
            return "实验胎";
        }
        else if (type.equals("scrap")) {
            return "报废胎";
        }
        return "全新胎";
    }
    /**
     * Inventory EPC Thread
     */
    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 = "";
                                addToList(listEPC, epcStr, (byte) -1);
                            } else {
                                String epcStr =
                                        Tools.Bytes2HexString(tag.getmEpcBytes(), tag.getmEpcBytes().length);
                                byte rssi = tag.getmRssi();
                                addToList(listEPC, epcStr, rssi);
                            }
                        }
                    }
                    tagList = null;
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {

                        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 && (keyCode == 135 || keyCode == 136)) {
                startFlag = true;
            }
        }
    }
}
