package com.example.beijing_daxing;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableBoolean;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.example.beijing_daxing.adapter.CheckAdapter;
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.Stock;
import com.example.beijing_daxing.databinding.ActivityCheckBinding;
import com.example.beijing_daxing.dialog.InPutDialog;
import com.example.beijing_daxing.dialog.TakePictureDialog;
import com.example.beijing_daxing.uitls.CustomWatermarkTransformation;
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.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.pda.serialport.Tools;


public class CheckActivity extends BaseActivity implements AdapterClickCall, InPutDialog.InPutDialogCall, TakePictureDialog.dialogReturnListSizeCall {
    private ActivityCheckBinding binding;
    private CheckAdapter adapter;
    private List<Stock> list;
    private List<Stock> list1;
    private List<String> selectList;
    private ObservableBoolean state;
    private ObservableBoolean checkState;
    private InPutDialog inputDialog;
    private TakePictureDialog takeDialog;
    private long id;
    private long inspectionId;
    private int backIndex;
    private String code;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_check);
        adapter = new CheckAdapter(this, this);
        state = new ObservableBoolean();
        checkState = new ObservableBoolean();
        binding.setAdapter(adapter);
        binding.setState(state);
        binding.setCheckState(checkState);
        /*selectList = Arrays.asList(getResources().getStringArray(R.array.check_item));
        binding.checkItemSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                var selectItem = selectList.get(position);
                state.set(selectItem.equals("正常"));
            }

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

            }
        });*/
        Intent intent = getIntent();
        id = intent.getLongExtra("id", 0);
        backIndex = intent.getIntExtra("backIndex", 0);
        inspectionId = intent.getLongExtra("inspectionId", 0);

        code = intent.getStringExtra("code");
        initRequest(code);
        inputDialog = new InPutDialog(this);
        inputDialog.setInPutDialogCall(this);
        tagList = new ArrayList<>();
        takeDialog = new TakePictureDialog(this);
        takeDialog.setCall(this);
    }

    // 初始化数据
    private void initRequest(String code) {
        OkGo.<MyResult>post(url + "/inspection/select").params("code", code).execute(new MyRecultCall(dialog, this) {
            @SuppressLint("NotifyDataSetChanged")
            @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());
                  /*  if (list == null || list.isEmpty()) {
                        Toast.makeText(CheckActivity.this, "没有维护巡检区域", Toast.LENGTH_SHORT).show();
                        return;
                    }*/
                    list1 = new ArrayList<>();
                    adapter.setList(list1);
                    // adapter.notifyDataSetChanged();
                    return;
                }
                Toast.makeText(CheckActivity.this, body.getMsg(), Toast.LENGTH_SHORT).show();
            }
        });
    }

    private List<String> tagList;
    private int subIndex = -1;

    // 扫描到返回数据
    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void sanRfid(List<Reader.TAGINFO> epcs) {
        epcs.forEach(t -> {
            var epc = Tools.Bytes2HexString(t.EpcId, t.EpcId.length);
            try {
                if (!epc.substring(0,8).equals("53574C44")) return;
            }catch (Exception e){
                return;
            }

            if (tagList.contains(epc)) {
                return;
            }
            tagList.add(epc);
            String s = HexAscii.hex2Str(epc);
            var stock = new Stock();
            stock.setEpcCode(s);
            stock.setLocationCode(code);
            stock.setState("正常");
            list1.add(stock);

            // var stock = new Stock();
            // stock.setEpcCode(HexAscii.hex2Str(epc));
            // var index = list.indexOf(stock);
            // if (index != -1) {
            //     list.get(index).setState("正常");
            // }
        });
        adapter.notifyDataSetChanged();

    }

    // 完成巡检，提交数据
    public void check_submit(View view) {
        // var type = list.stream().anyMatch(t -> t.getState().equals("未检"));
        // if (type) {
        if (list.size()>list1.size()) {
            Toast.makeText(this, "未检完全部轮挡，不允许提交", Toast.LENGTH_SHORT).show();
            return;
        }
        OkGo.<MyResult>post(url + "/xj/submit").tag(this).params("tableId", id)
                .params("json", gson.toJson(list1))
                .params("inspectionId", inspectionId)
                .params("user", SharedPreferencesUtils.getstring("user", ""))
                .addFileParams("files", files).execute(new MyRecultCall(dialog, this) {
            @Override
            public void onSuccess(Response<MyResult> response) {
                super.onSuccess(response);
                Toast.makeText(CheckActivity.this, "提交成功", Toast.LENGTH_SHORT).show();
                Intent resultIntent = new Intent();
                resultIntent.putExtra("backIndex", backIndex);
                files.forEach(File::delete);
                setResult(RESULT_OK, resultIntent);
                finish();
            }
        });
    }
    // 一条数据保存
    // public void check_stock(View view) {
    //     if (subIndex == -1) return;
    //     var stock = list.get(subIndex);
    //     stock.setState(binding.checkItemSelect.getSelectedItem().toString());
    //     stock.setRemark(binding.checkRemark.getText().toString());
    //     adapter.notifyItemChanged(subIndex);
    //     binding.checkRemark.setText(null);
    //     binding.checkEpc.setText(null);
    // }

    private int tag;

    @Override
    public void clickItem(int index) {
        tag = index;
        inputDialog.show();
    }


    @SuppressLint("NotifyDataSetChanged")
    @Override
    public void inPutDialogReculi(String name) {
        var stock = list.get(tag);
        stock.setState("跳过");
        stock.setRemark(name);
        inputDialog.dismiss();
        adapter.notifyDataSetChanged();
    }

    // 持续扫描按钮
    public void offCheckRead(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);
    }

    @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);
        }
    };

    // 拍照
    public void check_tackPhoto(View view) {
        takePhoto(true, code);
    }

    // 显示拍的照片
    public void check_showPhoto(View view) {
        takeDialog.setBitmaps(bitmaps, files);
        takeDialog.show();
    }

    private List<File> files = new ArrayList<>();
    private List<Bitmap> bitmaps = new ArrayList<>();

    @Override
    public void takePhotoCall(File outputImage, Bitmap bitmap) {

        // Glide.with(this)
        //         .load(outputImage.getPath())
        //         .apply(RequestOptions.bitmapTransform(new CustomWatermarkTransformation()))
        //         .into(imageView);
        files.add(outputImage);
        bitmaps.add(bitmap);
        binding.confirmPictureNumber2.setText(bitmaps.size() + "");
    }

    @Override
    public void returnListSize(int size) {
        binding.confirmPictureNumber2.setText(bitmaps.size() + "");
    }

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