package com.example.tyre;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.tyre.entity.ChangeTyre;
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.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;


import org.w3c.dom.Text;

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.ActivitySwitchBinding;

public class SwitchActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    private ActivitySwitchBinding binding;

    TextView epc1;
    TextView car1;
    TextView lw1;
    TextView epc2;
    TextView car;
    TextView lw2;
    Button ok;
    Button back;
    TextView wth1;
    LinearLayout linearLayout5;
    TextView wth2;
    EditText lc;
    //    @BindView(R.id.czr)
//    TextView czr;
//    @BindView(R.id.spinner)
//    Spinner spinner;
    private MyHandler myHandler;
   // private UHFService mDevice;
    private boolean isStart = true;
    private String epc;
    private UpTyre upTyre;
    private List<UpTyre> list_up;
    Gson gson = new Gson();
    private int site;
    private boolean scaninfo = true;
    ChangeTyre changeTyre;
    private List<ChangeTyre> list_change;
    String userID= SharedPreferencesUtils.getstring("UserID","");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivitySwitchBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        bindViews();
        setupClickListeners();
        myHandler = new MyHandler(this);
        upTyre = new UpTyre();
        changeTyre = new ChangeTyre();
        list_change = new ArrayList<>();
        PlayMusic.init(this);
    }

    private void bindViews() {
        epc1 = binding.epc;
        car1 = binding.car1;
        lw1 = binding.lw1;
        epc2 = binding.epc2;
        car = binding.car;
        lw2 = binding.lw2;
        ok = binding.ok;
        back = binding.back;
        wth1 = binding.wth1;
        linearLayout5 = binding.linearLayout5;
        wth2 = binding.wth2;
        lc = binding.lc;
    }

    private void setupClickListeners() {
        binding.ok.setOnClickListener(v -> {
            changeTyre.setCarnumber(car.getText().toString());
            changeTyre.setTyreEPCOne(epc1.getText().toString());
            changeTyre.setTyreEPCTwo(epc2.getText().toString());
            changeTyre.setSiteNoOneOld(lw1.getText().toString());
            changeTyre.setSiteNoOneNow(lw2.getText().toString());
            changeTyre.setSiteNoTwoOld(lw2.getText().toString());
            changeTyre.setSiteNoTwoNow(lw1.getText().toString());
            list_change.add(changeTyre);
            String json = gson.toJson(list_change);
            Log.e("json", json + wth1.getText().toString() + wth2.getText().toString() + userID);
            if (epc1.getText().toString().equals(epc2.getText().toString())){
                new CommonDialog(SwitchActivity.this).setMessage("轮胎EPC一样").show();
            }
            else if (!car.getText().toString().equals(car1.getText().toString()))
            {
                new CommonDialog(SwitchActivity.this).setMessage("车牌号不一样").show();
            }
            else if (lc.getText().toString().isEmpty()){
                new CommonDialog(SwitchActivity.this).setMessage("换位里程不能为空").show();
            }
            else {
                change(json, wth1.getText().toString(), wth2.getText().toString(), userID,lc.getText().toString());
            }
            list_change.clear();
        });

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

    @Override
    public void onResume() {
        super.onResume();
        isStart = true;
       // ScannerKey.open();
//        mDevice = UHFService.getInstance();
//        // open UHF
//        boolean ret = mDevice.open();
//        if (!ret) {
//            Log.e("aaaa", "扫描服务开启失败");
//        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.e("aaaa", "" + keyCode);
        if (keyCode == 142) {
            Log.e("sca", String.valueOf(scaninfo));
//            if (scaninfo) {
//                EPC epc = new EPC();
//                if (mDevice.inventoryOnce(epc, 100)) {
//                    String id = epc.getId();
//                    Message msg = Message.obtain();
//                    msg.obj = id;
//                    msg.what = 1;
//                    myHandler.handleMessage(msg);
//                }
//            } else {
//                Log.e("aaaa", "tet");
//                EPC epc = new EPC();
//                if (mDevice.inventoryOnce(epc, 100)) {
//                    String id = epc.getId();
//                    Message msg = Message.obtain();
//                    msg.obj = id;
//                    msg.what = 2;
//                    myHandler.handleMessage(msg);
//                }
//            }
            PlayMusic.playSound(this);
        }


        if (keyCode == 4) {
            Intent intent = new Intent(this, HomePageActivity.class);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    public void onPause() {
        super.onPause();
        //ScannerKey.close();
        //mDevice.close();
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//    czr.setText(parent.getItemAtPosition(position).toString());
    }

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

    class MyHandler extends Handler {
        WeakReference weakReference;

        public MyHandler(SwitchActivity activity) {
            weakReference = new WeakReference(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    epc = msg.obj.toString();
                    Log.e("epc", epc);
                    epc1.setText(epc.substring(4));
                    upTyre.setEpc(epc1.getText().toString());
                    find(upTyre.getEpc());
                    break;
                case 2:
                    epc = msg.obj.toString();
                    epc2.setText(epc.substring(4));
                    upTyre.setEpc(epc2.getText().toString());
                    findtwo(upTyre.getEpc());
                    break;
            }
        }
    }

    //判断EPC是否正确以及查询EPC是否在车上
    private void find(String epc) {
        OkGo.<String>post(MyUrl.url + "/find/find").tag(this).params("Epc", epc).params("Code", 3).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                if (body.equals("ERROR")) {
                    new CommonDialog(SwitchActivity.this).setMessage("轮胎EPC错误").show();
                    scaninfo = true;
                } else if (body.equals("meizai")) {
                    new CommonDialog(SwitchActivity.this).setMessage("轮胎没在车上").show();
                    scaninfo = true;
                } else {
                    Gson gson = new Gson();
                    UpTyre upTyre = gson.fromJson(body, UpTyre.class);
                    car1.setText(upTyre.getCarNum());
                    lw1.setText(upTyre.getSitename());
                    wth1.setText(upTyre.getWth());
                    Log.e("sca1", String.valueOf(scaninfo));
                    scaninfo = false;
                    Log.e("sca", String.valueOf(scaninfo));
                }
            }
        });
    }

    //判断EPC是否正确以及查询EPC是否在车上
    private void findtwo(String epc) {
        OkGo.<String>post(MyUrl.url + "/find/find").tag(this).params("Epc", epc).params("Code", 3).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                if (body.equals("ERROR")) {

                    new CommonDialog(SwitchActivity.this).setMessage("轮胎EPC错误").show();
                } else if (body.equals("meizai")) {
                    new CommonDialog(SwitchActivity.this).setMessage("轮胎没在车上").show();
                } else {
                    Gson gson = new Gson();
                    UpTyre upTyre = gson.fromJson(body, UpTyre.class);
                    car.setText(upTyre.getCarNum());
                    wth2.setText(upTyre.getWth());
                    lw2.setText(upTyre.getSitename());
                }
            }
        });
    }

    private void change(String json, String outsideone, String outsidetwo, String user,String Lc) {
        OkGo.<String>post(MyUrl.url + "/insert/changerecord").tag(this).params("Json", json).
                params("OutsideidOne", outsideone)
                .params("OutsideidTwo", outsidetwo)
                .params("User", user)
                .params("LC",Lc).execute(new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                String body = response.body();
                if (body.equals("ERROR")) {
                    new CommonDialog(SwitchActivity.this).setMessage("轮胎换位错误").show();
                }else if (body.equals("fail")){
                    new CommonDialog(SwitchActivity.this).setMessage("填写的换位里程小于或等于起始里程").show();
                }
                else {
                    car.setText("");
                    car1.setText("");
                    epc1.setText("");
                    epc2.setText("");
                    wth1.setText("");
                    wth2.setText("");
                    lw1.setText("");
                    lw2.setText("");
                    lc.setText("");
                    Toast.makeText(SwitchActivity.this, "换位成功", Toast.LENGTH_SHORT).show();
                    scaninfo=true;
                }
            }
        });
    }
}


