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.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.LinearLayout;
import android.widget.Spinner;
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.databinding.ActivityInstorehouseBinding;
import com.example.tyre.entity.AjaxResult;
import com.example.tyre.entity.BaseTyre;
import com.example.tyre.entity.EPC;
import com.example.tyre.entity.InStoreSpinnerVo;
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 java.util.stream.Collectors;

import cn.pda.serialport.Tools;

/**
 * Created by 杨万里 on 2019/12/10.
 */

public class InStoreHouseActivity extends AllBaseActivity implements AdapterView.OnItemSelectedListener {

    Button button;
    TextView scan;
    TextView pinpai;
    TextView xinghao;
    TextView cengji;
    TextView huawen;
    TextView gcts;
    Button back;
    EditText wtbm;
    LinearLayout linearLayout3;
    TextView tyrekind;
    Spinner spinnerkind;
    Spinner spinnerpattern;
    Spinner spinnerlevel;
    Spinner spinnerSize;
    Spinner spinnerBrand;
    Spinner spinnergcts;
    long lastTime;
    long nextTime;
    private ActivityInstorehouseBinding binding;
    // private UHFService mDevice;
//    private MyHandler handler;
    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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityInstorehouseBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        manager = MyApplication.getManager();
        check_spinner();
        showLoadingDialog();
        spinnerkind.setOnItemSelectedListener(this);
        spinnerpattern.setOnItemSelectedListener(this);
        spinnerlevel.setOnItemSelectedListener(this);
        spinnerSize.setOnItemSelectedListener(this);
        spinnerBrand.setOnItemSelectedListener(this);
        spinnergcts.setOnItemSelectedListener(this);
        initView();
        Thread thread = new InventoryThread();
        thread.start();
        com.example.tyre.util.Util.initSoundPool(this);
    }

    private void bindViews() {
        button = binding.button;
        scan = binding.epc;
        pinpai = binding.pinpai;
        xinghao = binding.xinghao;
        cengji = binding.cengji;
        huawen = binding.huawen;
        gcts = binding.gcts;
        back = binding.back;
        wtbm = binding.wtbm;
        linearLayout3 = binding.linearLayout3;
        tyrekind = binding.tyrekind;
        spinnerkind = binding.spinnerkind;
        spinnerpattern = binding.spinnerpattern;
        spinnerlevel = binding.spinnerlevel;
        spinnerSize = binding.spinnerSize;
        spinnerBrand = binding.spinnerBrand;
        spinnergcts = binding.spinnergcts;
        wtbm.requestFocus();
    }

    private void setupClickListeners() {
        binding.button.setOnClickListener(v -> {
            String epc = scan.getText().toString();
            String w = wtbm.getText().toString();
            String p = pinpai.getText().toString();
            String x = xinghao.getText().toString();
            String c = cengji.getText().toString();
            String h = huawen.getText().toString();
            String t = tyrekind.getText().toString();
            String g = gcts.getText().toString();
            if (scan.getText().toString() == "") {
                new CommonDialog(InStoreHouseActivity.this).setMessage("请扫描轮胎芯片！").show();
                return;
            }
            showLoadingDialog();
            insert_inventory(epc, w, p, x, c, h, g, t);
        });

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

    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 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 initView() {
        listEPC = new ArrayList<EPC>();
    }

    // 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);
                    scan.setText(currentEpc);

                }
                clearData();
            }
        });
        Log.e("EPC", "listepc:+ " + listepc);
//        if (listepc != null && !listepc.isEmpty()){
//            startFlag = false;
////            scan.setText("测试");
//            scan.setText(listepc.get(0).toString());
//            //请求后台
//            find(listepc.get(0).toString());
//        }
//        clearData();
    }

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

    //    基本信息查询
    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();
                        Log.e("body", body);
                        try {
                            Gson gson = new Gson();
                            BaseTyre baseTyre = gson.fromJson(body, BaseTyre.class);
                            if (baseTyre != null) {
                                // 空值处理：若字段为 null 则显示空字符串
                                String tyreNo = safeGetString(baseTyre.getTyreNo());
                                wtbm.setText(tyreNo);
                                String brand = safeGetString(baseTyre.getTyreBrand());
                                String model = safeGetString(baseTyre.getTyreModel());
                                String level = safeGetString(baseTyre.getTyreLevel());
                                String pattern = safeGetString(baseTyre.getTyrePattern());
                                String kind = safeGetString(baseTyre.getTyreType());
                                pinpai.setText(brand);
                                xinghao.setText(model);
                                cengji.setText(level);
                                huawen.setText(pattern);
                                tyrekind.setText(kind);
                            }
                        } catch (JsonSyntaxException e) {
                            return;
                        }
                    }
                });
    }

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

    // 添加到库存表
    private void insert_inventory(String epc, String wtbm, String pinpai, String xinghao, String cengji, String huawen, String grooves, String tyrekind) {
        OkGo.<String>post(MyUrl.url + "/tyre/inventory/pdaAddInventory").tag(this)
                .params("tyreRfid", epc)
                .params("tyreEpc", epc)
                .params("tyreOutsideId", wtbm)
                .params("tyreBrand", pinpai)
                .params("tyreModel", xinghao)
                .params("tyreLevel", cengji)
                .params("tyrePattern", huawen)
                .params("grooves", grooves)
                .params("tyreType", tyrekind)
                .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);
                        handleResponse(ajaxResult);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        hideLoadingDialog();
                        Toast.makeText(InStoreHouseActivity.this, "请求失败，请检查网络或重试", Toast.LENGTH_SHORT).show();
                    }
                });
    }

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

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

        int id1 = parent.getId();

//            case R.id.spinner:
//                czy.setText(parent.getItemAtPosition(position).toString());
//                break;
        if (id1 == R.id.spinnerkind) {
            tyrekind.setText(parent.getItemAtPosition(position).toString());
        } else if (id1 == R.id.spinnerpattern) {
            huawen.setText(parent.getItemAtPosition(position).toString());
        } else if (id1 == R.id.spinnerlevel) {
            cengji.setText(parent.getItemAtPosition(position).toString());
        } else if (id1 == R.id.spinnerSize) {
            xinghao.setText(parent.getItemAtPosition(position).toString());
        } else if (id1 == R.id.spinnerBrand) {
            pinpai.setText(parent.getItemAtPosition(position).toString());
        } else if (id1 == R.id.spinnergcts) {
            gcts.setText(parent.getItemAtPosition(position).toString());
        }
    }

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

    }

    private void check_spinner() {
        OkGo.<String>post(MyUrl.url + "/system/dict/data/tyreTypeList")
                .execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                hideLoadingDialog();
                String body = response.body();
                Gson gson = new Gson();
                InStoreSpinnerVo inStoreSpinnerVo ;
                inStoreSpinnerVo = gson.fromJson(body, InStoreSpinnerVo.class);
                List<String> stringList = inStoreSpinnerVo.getKindList();
                List<String> patternList = inStoreSpinnerVo.getPatternList();
                List<String> patternLevel = inStoreSpinnerVo.getLevelList();
                List<String> patternSize = inStoreSpinnerVo.getTyreSizeList().stream().map(InStoreSpinnerVo.labelvalue::getLabel).collect(Collectors.toList());
                List<String> patternBrand = inStoreSpinnerVo.getTyreBrandList();
                List<String> patternGcts = inStoreSpinnerVo.getGctsList();
                ArrayAdapter<String> arrayAdapter =
                        new ArrayAdapter<>(InStoreHouseActivity.this, android.R.layout.simple_list_item_1, stringList);
                ArrayAdapter<String> arrayAdapterPattern =
                        new ArrayAdapter<>(InStoreHouseActivity.this, android.R.layout.simple_list_item_1, patternList);
                ArrayAdapter<String> arrayAdapterLevel =
                        new ArrayAdapter<>(InStoreHouseActivity.this, android.R.layout.simple_list_item_1, patternLevel);
                ArrayAdapter<String> arrayAdapterSize =
                        new ArrayAdapter<>(InStoreHouseActivity.this, android.R.layout.simple_list_item_1, patternSize);
                ArrayAdapter<String> arrayAdapterBrand =
                        new ArrayAdapter<>(InStoreHouseActivity.this, android.R.layout.simple_list_item_1, patternBrand);
                ArrayAdapter<String> arrayAdapterGcts =
                        new ArrayAdapter<>(InStoreHouseActivity.this, android.R.layout.simple_list_item_1, patternGcts);
                spinnerkind.setAdapter(arrayAdapter);
                spinnerpattern.setAdapter(arrayAdapterPattern);
                spinnerlevel.setAdapter(arrayAdapterLevel);
                spinnerSize.setAdapter(arrayAdapterSize);
                spinnerBrand.setAdapter(arrayAdapterBrand);
                spinnergcts.setAdapter(arrayAdapterGcts);
            }
        });
        spinnerkind.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tyrekind.setText(parent.getItemAtPosition(position).toString());
            }

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

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

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

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

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

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

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

    /**
     * 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 = "";
//								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(InStoreHouseActivity.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;
                }
            }
        }
    }
}

