package com.example.beijing_daxing;

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

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.InAdapter;
import com.example.beijing_daxing.base.AdapterClickCall;
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.databinding.ActivityInBinding;
import com.example.beijing_daxing.uitls.HexAscii;
import com.example.beijing_daxing.uitls.SharedPreferencesUtils;
import com.example.beijing_daxing.vm.InStoreVM;
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 InActivity extends BaseActivity implements AdapterClickCall {
    private InStoreVM vm;
    private InAdapter adapter;
    private List<String> epcList;
    private List<String> tagList;
    private ActivityInBinding binding;
    private ObservableBoolean checkState;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_in);
        vm = new InStoreVM();
        binding.setVm(vm);
        initRequest();
        adapter = new InAdapter(this);
        epcList = new ArrayList<>();
        adapter.setList(epcList);
        adapter.setAdapterClickCall(this);
        binding.setAdapter(adapter);
        checkState=new ObservableBoolean();
        binding.setCheckState(checkState);
        tagList=new ArrayList<>();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setPower(SharedPreferencesUtils.getInt("powerIn",33));
    }

    @Override
    public void sanRfid(List<Reader.TAGINFO> epcs) {
        epcs.stream().forEach(t -> {
            var epc = Tools.Bytes2HexString(t.EpcId,t.EpcId.length);
            Log.e("TAG", "sanRfid:" + epc);
            if (!epc.substring(0,8).equals("53574C44")) return;
            if (tagList.contains(epc)) return;
            tagList.add(epc);
            epcList.add(HexAscii.hex2Str(epc));
        });
        vm.setSanLength(epcList.size());
        adapter.notifyDataSetChanged();

    }

    private void initRequest() {
        OkGo.<MyResult>post(url + "/instore/select").tag(this).execute(new MyRecultCall(dialog, this) {
            @Override
            public void onSuccess(Response<MyResult> response) {
                super.onSuccess(response);
                InStoreSelectBody inStoreSelectBody = gson.fromJson(response.body().getData().toString(), InStoreSelectBody.class);
                vm.initSelect(inStoreSelectBody.getBaseLocationList(), inStoreSelectBody.getBaseManufacturerList());
            }
        });
    }

    @Override
    public void clickItem(int index) {
        tagList.remove(HexAscii.str2Hex(epcList.get(index)));
        epcList.remove(index);
        adapter.notifyDataSetChanged();
        vm.setSanLength(epcList.size());
    }

    public void in_submit(View view) {
        String binchCode = vm.getBinchCode();
        if (binchCode == null || epcList.isEmpty()) return;
        vm.setEpcList(epcList);
        vm.setSubmitUser(SharedPreferencesUtils.getstring("user", "test"));
        OkGo.<MyResult>post(url + "/instore/submit")
                .upRequestBody(RequestBody.create(JSON, gson.toJson(vm)))
                .execute(new MyRecultCall(dialog, this) {
                    @Override
                    public void onSuccess(Response<MyResult> response) {
                        super.onSuccess(response);
                        Toast.makeText(InActivity.this, response.body().getMsg(), Toast.LENGTH_SHORT).show();
                        if (response.body().getCode() == 0) {
                            finish();
                        }
                    }
                });
    }


    @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() {
            sanEpc();
            handler.postDelayed(runnable, 10);
        }
    };
    public void instore_check(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);
    }

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