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.view.View;
import android.widget.Toast;

import com.example.beijing_daxing.adapter.OutAdapter;
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.Stock;
import com.example.beijing_daxing.databinding.ActivityFpOutBinding;
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;

public class FpOutActivity extends BaseActivity {
    private ObservableBoolean checkState;
    private List<Stock> list;
    private OutAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActivityFpOutBinding binding= DataBindingUtil. setContentView(this,R.layout.activity_fp_out);
        checkState=new ObservableBoolean();
        binding.setCheckState(checkState);
        adapter = new OutAdapter(this);
        binding.setAdapter(adapter);
        tagList=new ArrayList<>();
        initRequest();
        setPower(SharedPreferencesUtils.getInt("powerScrapOut",33));
    }

    private List<String> tagList;
    @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");
            }
        });
        adapter.notifyDataSetChanged();
    }
    private void initRequest() {
        OkGo.<MyResult>post(url + "/fpout/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());
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(FpOutActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void fp_out_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 fp_out_submit(View view) {
        if (list.stream().anyMatch(t -> t.getState().equals("N"))){
            return;
        }
        handler.removeCallbacks(runnable);

        OkGo.<MyResult>post(url+"/fpout/submit")
                .tag(this)
                .params("user", SharedPreferencesUtils.getstring("user","test"))
                .params("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(FpOutActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(FpOutActivity.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() {
            // 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;
    }


}