package xn.hxp.weidith;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.rc.httpcore.bean.ChemistryBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

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

import xn.hxp.R;
import xn.hxp.comm.Constants;
import xn.hxp.receiver.OnSerialScanListener;
import xn.hxp.receiver.PortScanHelper;
import xn.hxp.receiver.UhfRfidManager;
import xn.hxp.receiver.UsbReceiver;
import xn.hxp.ui.adapter.UsageLabelDialogAdapter;
import xn.hxp.utils.BigDecimalUtils;

public class UsageLabelDialog extends Dialog {
    private final Activity ac;
    private final boolean isLcok;
    private final String cabinet;
    private final IIneSwipeLin lint;

    private UsbReceiver mUsbReceiver;
    private boolean mHandleScanEvent = false;
    private UsageLabelDialogAdapter mAdapter;
    private int mCounter = 0;
    private Button butClos;
    private PortScanHelper mPortScanHelper;
    private Handler mCountDownHandler;

    public UsageLabelDialog(Activity ac, boolean isLcok, String cabinet, IIneSwipeLin lint) {
        super(ac);
        this.ac = ac;
        this.isLcok = isLcok;
        this.cabinet = cabinet;
        this.lint = lint;

        // 初始化适配器
        mAdapter = new UsageLabelDialogAdapter(ac);
        initCountDownHandler();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.usage_label_dialog);
        setCanceledOnTouchOutside(false);

        if (isLcok) {
            findViewById(R.id.butOpen).setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.butOpen).setVisibility(View.GONE);
        }

        ((TextView) findViewById(R.id.cabinet)).setText(cabinet);
        butClos = findViewById(R.id.butClos);
        butClos.setOnClickListener(v -> dismiss());

        findViewById(R.id.cloe).setOnClickListener(v -> {
            lint.onCloses();
            dismiss();
        });

        findViewById(R.id.useEn).setOnClickListener(v -> {
            if (mAdapter.getData() != null && mAdapter.getData().size() > 0) {
                boolean hasDuplicateCodes = hasDuplicateCodes(mAdapter.getData());
                LogUtils.i("========hasDuplicateCodes  " + hasDuplicateCodes);
                if (!hasDuplicateCodes) {
                    lint.onUseClick(mAdapter.getData());
                    dismiss();
                } else {
                    LogUtils.i("===========2");
                    Toast.makeText(ActivityUtils.getTopActivity(), "不能重复领用", Toast.LENGTH_SHORT).show();
                }
            }
        });

        findViewById(R.id.butOpen).setOnClickListener(v -> {
            dismiss();
            lint.openLock();
        });

        RecyclerView reView = findViewById(R.id.reView);
        reView.setLayoutManager(new LinearLayoutManager(ac));
        reView.setAdapter(mAdapter);

        mPortScanHelper = new PortScanHelper(ac, new OnSerialScanListener() {
            @Override
            public void dispatchScanEvent(OnSerialScanListener.ScanType type, String content) {
                lint.onTimerReply();
                mCounter = 0;
                if (!mHandleScanEvent) {
                    if (content != null && !content.isEmpty()) {
                        LogUtils.i("========a==当前usb返回参数" + content);
                        mHandleScanEvent = true;
                        if (content.startsWith("http")) {
                            try {
                                String currentDateTimeString = BigDecimalUtils.INSTANCE.extractParameterValue(content, "code");
                                LogUtils.i("=======ce  " + currentDateTimeString);
                                lint.onCardInContent(currentDateTimeString);
                            } catch (Exception e) {
                                mHandleScanEvent = false;
                                LogUtils.i("刷卡异常了");
                                showToast("未获取到二维码信息，请重新扫描", 3000);
                            }
                        } else {
                            lint.onCardInContent(content);
                        }
                    }
                }
            }
        });

        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            if (view.getId() == R.id.imgDelete) {
                lint.onPositions(position, mAdapter);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
        registerUsbBroadcast();
    }

    @Override
    protected void onStop() {
        super.onStop();
        ac.unregisterReceiver(mUsbReceiver);
        EventBus.getDefault().unregister(this);
    }

    private boolean hasDuplicateCodes(List<ChemistryBean> list) {
        List<String> codes = new ArrayList<>();
        for (ChemistryBean bean : list) {
            codes.add(bean.getCode());
        }
        return codes.size() != list.size();
    }

    public interface IIneSwipeLin {
        void onCardInContent(String cont);

        void onUseClick(List<ChemistryBean> data);

        void onCloses();

        void openLock();

        void onPositions(int position, UsageLabelDialogAdapter mData);

        void onTimerReply();
    }

    @Override
    public boolean dispatchKeyEvent(@NonNull KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        // 消费掉外置RFID读卡器的输入
        if (UhfRfidManager.INSTANCE.isEnabled(ac) && UhfRfidManager.INSTANCE.isUhfRfidEvent(ac, event)) {
            return true;
        }
        mPortScanHelper.dispatchKeyEvent(event);
        return super.dispatchKeyEvent(event);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUpdateEventEvent(KeyEvent event) {
        // 事件总线处理方法
    }

    private void showToast(String message, int duration) {
        Toast.makeText(ac, message, duration).show();
    }

    private void registerUsbBroadcast() {
        if (mUsbReceiver == null) {
            IntentFilter filter = new IntentFilter();
            filter.addAction(UsbReceiver.ACTION_USB_PERMISSION);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
            filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
            filter.addAction(UsbReceiver.ACTION_USB_STATE);
            mUsbReceiver = new UsbReceiver();
            ac.registerReceiver(mUsbReceiver, filter);
        }
    }

    public void setMessage(String message, List<ChemistryBean> dataList) {
        LogUtils.i("====================数据过来了");
        mHandleScanEvent = false;
        findViewById(R.id.img).setVisibility(View.GONE);
        butClos.setVisibility(View.GONE);
        findViewById(R.id.linTow).setVisibility(View.VISIBLE);
        findViewById(R.id.reView).setVisibility(View.VISIBLE);
        mAdapter.setNewInstance(new ArrayList<>(dataList));
    }

    public void notifyData(List<ChemistryBean> chemistryBeans) {
        mHandleScanEvent = false;
        mAdapter.setNewInstance(chemistryBeans);
        mAdapter.notifyDataSetChanged();
    }

    public void notifyData() {
        mHandleScanEvent = false;
    }

    @Override
    public boolean dispatchTouchEvent(@NonNull MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                onUserInteraction();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    private void initCountDownHandler() {
        mCountDownHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == Constants.INSTANCE.getWHAT_COUNT_DOWN_TWO()) {
                    // 倒计时处理逻辑
                }
            }
        };
    }

    public void onUserInteraction() {
        LogUtils.i("=========弹框触发了");
        lint.onTimerReply();
        mCounter = 0;
        mCountDownHandler.removeMessages(Constants.INSTANCE.getWHAT_COUNT_DOWN_TWO());
        mCountDownHandler.sendEmptyMessageDelayed(Constants.INSTANCE.getWHAT_COUNT_DOWN_TWO(), 5000);
    }
}