package com.ycgis.macall.personalcenter.v.fragment;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.rs.macall.androidx.basemodel.callback.CustomClickListener;
import com.rs.macall.androidx.basemodel.callback.SimpleListClickListener;
import com.rs.macall.androidx.basemodel.decoration.MyDividerItemDecoration;
import com.rs.macall.androidx.basemodel.utils.DimensionConvert;
import com.rs.macall.androidx.basemodel.utils.StringUtil;
import com.rs.macall.androidx.basemodel.utils.ToastUtil;
import com.ycgis.macall.personalcenter.R;
import com.ycgis.macall.personalcenter.databinding.FragmendDialogBluetoothBinding;
import com.ycgis.macall.personalcenter.p.callback.BluetoothFragmentListener;
import com.ycgis.macall.personalcenter.util.BluetoothManage;
import com.ycgis.macall.personalcenter.v.adapter.BluetoothListAdapter;
import com.ycgis.zpSDK.BluetoothSocket;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * created by:   Macall
 * create time:  2025/5/30 16:34
 * copyright:    @ruansee.com
 * Describe:
 */
public class BluetoothDialogFragment extends DialogFragment {
    private FragmendDialogBluetoothBinding viewBinding;

    public String TAG = "zpSDK";
    public BluetoothAdapter btAdapter = null;
    private BluetoothListAdapter listAdapter1, listAdapter2;
    private List<BluetoothDevice> pdDataList = new ArrayList<>(), searchDataList = new ArrayList<>();
    private BluetoothFragmentListener bluetoothFragmentListener;

    public void setBluetoothFragmentListener(BluetoothFragmentListener bluetoothFragmentListener) {
        this.bluetoothFragmentListener = bluetoothFragmentListener;
    }

    @Override
    public void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @org.jetbrains.annotations.Nullable
    @Override
    public View onCreateView(@NonNull @NotNull LayoutInflater inflater, @Nullable @org.jetbrains.annotations.Nullable ViewGroup container, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        viewBinding = FragmendDialogBluetoothBinding.inflate(getLayoutInflater());
        initView();
        startPage();
        return viewBinding.getRoot();
    }

    private void initView() {
        viewBinding.rvSearchList.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.rvSearchList.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        viewBinding.rvYpd.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        viewBinding.rvYpd.addItemDecoration(new MyDividerItemDecoration(getContext(), LinearLayoutManager.VERTICAL));
        viewBinding.btnSearch.setVisibility(View.VISIBLE);
        viewBinding.searchProgress.setVisibility(View.GONE);
        viewBinding.btnSearch.setOnClickListener(customClickListener);
    }

    private void startPage() {
        boolean init = BluetoothManage.getInstance().init();
        if (!init) {
            ToastUtil.centered(getContext(), "当前设备不支持蓝牙！");
            if (bluetoothFragmentListener!=null) bluetoothFragmentListener.onError(-1,"当前设备不支持蓝牙");
            dismiss();
            return;
        }
        if (!BluetoothManage.getInstance().isBluetoothOpen(getActivity(), true)) {
            ToastUtil.centered(getContext(), "请先打开蓝牙！");
            if (bluetoothFragmentListener!=null) bluetoothFragmentListener.onError(-2,"蓝牙未打卡");
            dismiss();
            return;
        }
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        BluetoothDevice remoteDevice = BluetoothSocket.getInstance().getRemoteDevice();
        if (remoteDevice != null){
            viewBinding.tvPrinters.setText("已连接|"+remoteDevice.getName());
        }else {
            viewBinding.tvPrinters.setText("未连接打印机");
        }

        bonded_devices_get();

        //register broadcast receiver
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_FOUND);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        getActivity().registerReceiver(mBroadcastReceiver, filter);
    }

    private void onBindView(int viewId){
        if (viewId == R.id.btn_search) {
            discovry_do();
        }
    }

    private CustomClickListener customClickListener = new CustomClickListener() {
        @Override
        public void onSingleClick(View v) {
            onBindView(v.getId());
        }
    };

    @Override
    public void onStart() {
        super.onStart();
        // 设置Dialog宽度
        if (getDialog() != null && getDialog().getWindow() != null) {
            getDialog().getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                    DimensionConvert.dip2px(getContext(),680));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //获取蓝牙设备，并开始搜索设备
        if (btAdapter.isDiscovering()) {
            Log.d("BT", "-----------btAdapter.cancelDiscovery()---------");
            btAdapter.cancelDiscovery();
        }
        getActivity().unregisterReceiver(mBroadcastReceiver);
//        BluetoothSocket.getInstance().disconnect();
    }


    //get the Bonded devices
    //获取配对列表
    private void bonded_devices_get() {
        pdDataList.clear();
        Set<BluetoothDevice> PairedDevices = btAdapter.getBondedDevices();
        if (PairedDevices.size() > 0) {
            for (BluetoothDevice device : PairedDevices) {
                if (device == null)continue;
                if (StringUtil.isNullOrEmpty(device.getAddress()))continue;
//                String device_info = device.getName()+"\n"+device.getAddress();
                pdDataList.add(device);
            }
        }
        initDataPd();
    }

    private void initDataPd() {
        if (listAdapter1 == null) {
            listAdapter1 = new BluetoothListAdapter(getContext(), pdDataList);
            viewBinding.rvYpd.setAdapter(listAdapter1);
            listAdapter1.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (bluetoothFragmentListener != null){
                        bluetoothFragmentListener.onClickBluetoothDevice(listAdapter1.getDataItem(pointer));
                    }
                    dismiss();
//                    lk(listAdapter1.getDataItem(pointer));
                }
            });
        } else {
            listAdapter1.upData(pdDataList);
        }
    }

    /*
     * 获取蓝牙设备，并开始搜索设备
     */
    //search BlueTooth devices
    private void discovry_do() {
        Log.d("BT", "-----------discovry_do---------");
        if (!btAdapter.isEnabled()) {
            btAdapter.enable();
            while (btAdapter.getState() != BluetoothAdapter.STATE_ON) ;
        }
        //获取蓝牙设备，并开始搜索设备
        if (btAdapter.isDiscovering()) {
            Log.d("BT", "-----------btAdapter.cancelDiscovery()---------");
            btAdapter.cancelDiscovery();
        }
        Log.d("BT", "-----------btAdapter.startDiscovery()---------");
        btAdapter.startDiscovery();
        Log.d("BT", "-----------btAdapter.startDiscovery()+END---------");

        viewBinding.btnSearch.setVisibility(View.GONE);
        viewBinding.searchProgress.setVisibility(View.VISIBLE);
    }



    private void initSearch(BluetoothDevice device) {
        if (StringUtil.isNullOrEmpty(device.getAddress()))return;
        if (listAdapter2 == null) {
            searchDataList.add(device);
            listAdapter2 = new BluetoothListAdapter(getContext(), searchDataList);
            viewBinding.rvSearchList.setAdapter(listAdapter2);
            listAdapter2.setListClickListener(new SimpleListClickListener() {
                @Override
                public void onSingleClick(View v, int pointer) {
                    if (bluetoothFragmentListener != null){
                        bluetoothFragmentListener.onClickBluetoothDevice(listAdapter2.getDataItem(pointer));
                    }
                    dismiss();
                }
            });
        } else {
            listAdapter2.addItem(device);
        }
    }

    BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            Log.d("BT", "----------onReceive----------" + action);
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    initSearch(device);
                }
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                viewBinding.btnSearch.setVisibility(View.VISIBLE);
                viewBinding.searchProgress.setVisibility(View.GONE);
            }
        }
    };

}
