package com.example.beijing_daxing;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.Bindable;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableBoolean;
import androidx.databinding.ObservableInt;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.beijing_daxing.adapter.StoreCheckAdapter;
import com.example.beijing_daxing.base.BaseActivity;
import com.example.beijing_daxing.base.MyRecultCall;
import com.example.beijing_daxing.base.MyResult;
import com.example.beijing_daxing.been.InStoreSelectBody;
import com.example.beijing_daxing.been.Stock;
import com.example.beijing_daxing.databinding.ActivityStoreCheckBinding;
import com.example.beijing_daxing.uitls.HexAscii;
import com.example.beijing_daxing.uitls.SharedPreferencesUtils;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.uhf.api.cls.Reader;

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

import cn.pda.serialport.Tools;
import okhttp3.RequestBody;

public class StoreCheckActivity extends BaseActivity {


    private ObservableBoolean checkState;
    private List<Stock> list;
    private StoreCheckAdapter checkAdapter;
    private int checkNumber;


  private   ActivityStoreCheckBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_store_check);
        checkState = new ObservableBoolean();
        binding.setCheckState(checkState);
        checkAdapter = new StoreCheckAdapter(this);
        binding.setAdapter(checkAdapter);
        initRequest();
        checkNumber=0;
        binding.setCheckNumber(checkNumber);
        setPower(SharedPreferencesUtils.getInt("powerStoreCheck",33));
    }

    private List<String> tagList;

    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void sanRfid(List<Reader.TAGINFO> epcs) {
        if (tagList == null) return;
        epcs.forEach(t -> {
            var epc = Tools.Bytes2HexString(t.EpcId, t.EpcId.length);
            if (tagList.contains(epc)) {
                return;
            }
            tagList.add(epc);
            var stock = new Stock();
            stock.setEpcCode(HexAscii.hex2Str(epc));
            var index = list.indexOf(stock);
            if (index != -1) {
                list.get(index).setState("Y");
                checkNumber--;
                binding.setCheckNumber(checkNumber);
                checkAdapter.notifyDataSetChanged();
            }
        });

    }

    private void initRequest() {
        OkGo.<MyResult>post(url + "/storecheck/select").tag(this).execute(new MyRecultCall(dialog, this) {
            @Override
            public void onSuccess(Response<MyResult> response) {
                super.onSuccess(response);
                var body = response.body();
                if (body.getCode() == 0) {
                    list = gson.fromJson(body.getData().toString(), new TypeToken<List<Stock>>() {
                    }.getType());
                    tagList = new ArrayList<>();
                    checkAdapter.setList(list);
                    checkNumber=list.size();

                    binding.setCheckNumber(checkNumber);
                    binding.setListNumber(checkNumber);
                    checkAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(StoreCheckActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    public void check_read(View view) {
        var b = checkState.get();
        if (b) {
            uhfLongerManager.setGen2session(false);
            uhfLongerManager.asyncStopReading();
            handler.removeCallbacks(runnable);
        } else {
            uhfLongerManager.setGen2session(true);
            uhfLongerManager.asyncStartReading();
            handler.postDelayed(runnable, 0);
        }
        checkState.set(!b);
    }

    public void store_check_submit(View view) {
        handler.removeCallbacks(runnable);
        OkGo.<MyResult>post(url + "/storecheck/submit")
                .tag(this)
                .params("user", SharedPreferencesUtils.getstring("user", "test"))
                .params("json", gson.toJson(list))
                // .upRequestBody(RequestBody.create(JSON, gson.toJson(list)))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        var body = response.body();
                        if (body.getCode() == 0) {
                            finish();
                            Toast.makeText(StoreCheckActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(StoreCheckActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
        }
    };
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            // Log.e("TAG", "发送广播，读取RFID");
            // sendBroadcast(broadcastIntent);
            sanEpc();
            handler.postDelayed(runnable, 10);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(runnable);
        uhfLongerManager.setGen2session(false);
        uhfLongerManager.asyncStopReading();
        handler = null;
        runnable = null;
    }
}