package com.example.jinyu_rfid;

import androidx.databinding.DataBindingUtil;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.example.jinyu_rfid.adapter.ResultAdapter;
import com.example.jinyu_rfid.base.BaseActivity;
import com.example.jinyu_rfid.base.MyRecultCall;
import com.example.jinyu_rfid.base.MyResult;
import com.example.jinyu_rfid.been.ConfigurationTable;
import com.example.jinyu_rfid.been.ReadTyreNoResult;
import com.example.jinyu_rfid.broadcast.ScanERCodeReceiver;
import com.example.jinyu_rfid.callback.DataReturnCall;
import com.example.jinyu_rfid.databinding.ActivityWriteUserBinding;
import com.example.jinyu_rfid.rfid.C5106Device;
import com.example.jinyu_rfid.rfid.RFIDModel;
import com.example.jinyu_rfid.uitls.ASCIIUtil;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import org.litepal.LitePal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import okhttp3.RequestBody;

public class WriteUserActivity extends BaseActivity implements DataReturnCall {
    private Intent intent1;
    private Intent intent2;
    private RFIDModel rfidModel;
    private ActivityWriteUserBinding binding;
    private ResultAdapter adapter;
    private List<ReadTyreNoResult> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_write_user);
        binding.setTitle(getString(R.string.activity_name_configuration));
        rfidModel = new C5106Device(this);
        intent1 = new Intent(this, ConfigurationTableActivity.class);
        intent2 = new Intent(this, ConfigurationTableActivity.class);
        ScanERCodeReceiver scanERCodeReceiver = new ScanERCodeReceiver(this);
        registerReceiver(scanERCodeReceiver, new IntentFilter("com.rfid.SCAN"));
        adapter = new ResultAdapter(this);
        binding.setAdapter(adapter);

    }


    public void writeReadEPC(View view) {
        rfidModel.sanEpc(6);
    }

    private boolean writeUserState = false;

    // 写入
    public void writeUser(View view) {
       /* if (list == null || list.isEmpty()) return;
        var epcStr = binding.writeEpcCode.getText().toString();
        if (epcStr.isEmpty()) return;
        //     EPC编码~胎号~品牌~规格~花纹~层级~轮胎名称~速度级别~负荷指数~轮辋直径~扁平比~销售区域
        List<ConfigurationTable> tagList = LitePal.findAll(ConfigurationTable.class);
        StringBuilder tagUserStr = new StringBuilder(tagList.get(0).isState() ? epcStr : "_");
        for (int i = 1; i < 12; i++) {
            var configuration = tagList.get(i);
            var state = configuration.isState();
            tagUserStr.append("~");
   *//*         if (state) {
                Optional<ReadTyreNoResult> optionalResult = Optional.ofNullable(list.get(i-1));
                String propertyContent = optionalResult.map(ReadTyreNoResult::getPropertyContent).orElse("_");
                tagUserStr.append(propertyContent);
            } else {
                tagUserStr.append("_");
            }*//*
            if (state) {
                try {
                    var result = list.get(i - 1);
                    var propertyContent = result.getPropertyContent();
                    tagUserStr.append(propertyContent == null ? "_" : propertyContent);
                } catch (IndexOutOfBoundsException e) {
                    tagUserStr.append("_");
                }
            } else {
                tagUserStr.append("_");
            }
        }
        String user = ASCIIUtil.str2Hex(tagUserStr.toString());
        Log.e("TAG", "writeUser:" + user);
        Log.e("TAG", "writeUser:" + user.length());*/
        if (!writeUserState) {
            Log.e("TAG", "writeUser:" + 1);
            // writeUserState = rfidModel.writeUser(user, epcStr);
            writeUserState = true;
            Toast.makeText(context, getString(writeUserState ? R.string.write_success : R.string.write_failed), Toast.LENGTH_SHORT).show();
        }

        if (writeUserState) {
            Map<String ,String> map=new HashMap<>();

            map.put("EpcCode","1231");
            map.put("TyreNo","1231");
            map.put("token","123456");

            Log.e("TAG", "writeUser:" + 2);
            OkGo.<MyResult>post(url + "/write")
                    .upRequestBody(RequestBody.create(JSON, gson.toJson(map))).execute(new MyRecultCall(dialog, this) {
                    });

        }
        // writeUserState=false;
    }

}


    public void writeGoRead(View view) {
        startActivity(intent1);
    }

    public void writeGoConfiguration(View view) {
        startActivity(intent2);
    }

    @Override
    public void readEpcCodeInfo(String info, boolean state, String stateInfo) {
        if (state) {
            binding.writeEpcCode.setText(info);
            super.music.start();
            return;
        }
        binding.writeEpcCode.setText(null);
        // Log.e("TAG", "读取状态:" + stateInfo);
    }

    @Override
    public void readUserInfo(String user) {

    }

    @Override
    public void readerCodeInfo(String erCode) {
        binding.writeTire.setText(erCode);
        Map<String, String> map = new HashMap<>();
        map.put("TyreNo", erCode);
        map.put("token", "123456");
        OkGo.<MyResult>post(url + "/readTyreNo").upRequestBody(RequestBody.create(JSON, gson.toJson(map))).execute(new MyRecultCall(dialog, this) {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void onSuccess(Response<MyResult> response) {
                super.onSuccess(response);
                var body = response.body();
                if (body.getResultFlag().equals("1")) {

                    list = gson.fromJson(body.getJson(), new TypeToken<List<ReadTyreNoResult>>() {
                    }.getType());
                    list.remove(0);
                    adapter.setList(list);
                    adapter.notifyDataSetChanged();
                    return;
                }
                Toast.makeText(WriteUserActivity.this, body.getResultData().toString(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}