package com.phlx.anchorcollect.ui.setting;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Application;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseIntArray;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableArrayList;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableList;

import com.google.gson.Gson;
import com.phlx.anchorcollect.App;
import com.phlx.anchorcollect.BR;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.ble.BluetoothEntity;
import com.phlx.anchorcollect.bt.BtService;
import com.phlx.anchorcollect.data.Repository;
import com.phlx.anchorcollect.db.DbUtil;
import com.phlx.anchorcollect.db.gen.BreedingRecordDetailEntityDao;
import com.phlx.anchorcollect.db.gen.BreedingRecordEntityDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchDetailEntityDao;
import com.phlx.anchorcollect.db.gen.ImmuneBatchEntityDao;
import com.phlx.anchorcollect.db.gen.MedicalRecordEntityDao;
import com.phlx.anchorcollect.db.gen.PerformanceEntityDao;
import com.phlx.anchorcollect.db.gen.WeightManEntityDao;
import com.phlx.anchorcollect.db.interf.DbIDUCallBack;
import com.phlx.anchorcollect.db.interf.DbQueryCallBack;
import com.phlx.anchorcollect.entity.BreedingRecordDetailEntity;
import com.phlx.anchorcollect.entity.BreedingRecordEntity;
import com.phlx.anchorcollect.entity.CattleResumeEntity;
import com.phlx.anchorcollect.entity.ImmuneBatchEntity;
import com.phlx.anchorcollect.entity.ImmuneBatchDetailEntity;
import com.phlx.anchorcollect.entity.MedicalRecordEntity;
import com.phlx.anchorcollect.entity.PerformanceEntity;
import com.phlx.anchorcollect.entity.WeightManEntity;
import com.phlx.anchorcollect.event.EventMsg;
import com.phlx.anchorcollect.event.EventTag;
import com.phlx.anchorcollect.params.CollectResponse;
import com.phlx.anchorcollect.params.ListResponse;
import com.phlx.anchorcollect.rfid.InventoryManger;
import com.phlx.anchorcollect.rfid.ModuleManager;
import com.phlx.anchorcollect.util.BaseImageUtils;
import com.phlx.anchorcollect.util.TextUtil;
import com.uhf.structures.FilterParams;
import com.uhf.structures.InventoryData;
import com.uhf.structures.InventoryParams;
import com.uhf.structures.OnInventoryListener;
import com.uhf.structures.Rfid_Value;

import org.greenrobot.greendao.query.QueryBuilder;

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

import cn.wandersnail.ble.Device;
import cn.wandersnail.bluetooth.BTManager;
import cn.wandersnail.bluetooth.DiscoveryListener;
import cn.wandersnail.commons.util.ToastUtils;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.RxBus;
import me.goldze.mvvmhabit.bus.RxSubscriptions;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.http.ResponseThrowable;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.RxUtils;
import me.goldze.mvvmhabit.utils.SPUtils;
import me.tatarka.bindingcollectionadapter2.ItemBinding;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class SettingVM extends BaseViewModel<Repository> implements DiscoveryListener {


    //给RecyclerView添加ObservableList
    public ObservableList<BLEItem> observableList = new ObservableArrayList<>();
    //给RecyclerView添加ItemBinding
    public ItemBinding<BLEItem> itemBinding = ItemBinding.of(BR.viewModel, R.layout.item_ble);

    private Device curDevice;


    //选中的蓝牙设备信息
    public static BluetoothEntity bluetoothEntity;

    //当前蓝牙搜索集合
    private List<BluetoothEntity> bluetoothList;

    public SingleLiveEvent<Integer> btRequestEvent = new SingleLiveEvent<>();
    public SingleLiveEvent<Boolean> btParamEvent = new SingleLiveEvent<>();

    //错误提示
    public SingleLiveEvent<String> errorEvent = new SingleLiveEvent<>();
    //关闭页面
    public SingleLiveEvent<String> closeEvent = new SingleLiveEvent<>();

    //功率
    public ObservableField<String> power = new ObservableField<>("");
    public ObservableField<Boolean> inventoryTypeStatus = new ObservableField<>(false);


    private Disposable weightBus;

    public SettingVM(@NonNull Application application, Repository model) {
        super(application, model);

        initData();

    }


    private void initData() {
        inventoryTypeStatus.set(SPUtils.getInstance().getBoolean(Configs.SP_INVENTORY_STATUS, false));
    }

    //获取功率
    public BindingCommand getPowerOnClick = new BindingCommand(this::getAntennaPower);
    //设置功率
    public BindingCommand setPowerOnClick = new BindingCommand(this::setAntennaPower);


    /**
     * 获取天线功率
     */
    private void getAntennaPower() {
        if (ModuleManager.powerOn() != 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("模块连接失败");
            ModuleManager.powerOff();
            return;
        }
        Rfid_Value power_value = new Rfid_Value();
        int powerStatue =
                App.getInstance().getLinkage().Radio_GetAntennaPower(power_value);
        if (powerStatue == 0) {
            String value = String.valueOf((power_value.value) / 10);
            power.set(value);
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("获取天线功率成功");
        } else {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("获取天线功率失败");
        }

    }

    /**
     * 设置天线功率
     */
    private void setAntennaPower() {
        if (ModuleManager.powerOn() != 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("模块连接失败");
            ModuleManager.powerOff();
            return;
        }
        if (TextUtil.isSpace(power.get())) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("功率不能为空");
            return;
        }
        int status_power;
        int iu32 = (int) (Double.parseDouble(power.get()) * 10);
        if (iu32 < 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("参数不可用");
            return;
        }
        status_power = App.getInstance().getLinkage().Radio_SetAntennaPower(iu32);

        if (status_power == 0) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("功率修改成功");

        } else if (status_power == -1000) {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("正在盘点");
        } else {
            me.goldze.mvvmhabit.utils.ToastUtils.showShort("设置功率失败");
        }
    }

    public void initBt(Context context) {

        bluetoothList = new ArrayList<>();
        BTManager.isDebugMode = true;
        BTManager.getInstance().addDiscoveryListener(this);
        btParamEvent.call();
    }

    public BindingCommand OnRefreshClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            BTManager.getInstance().stopDiscovery();
            doStartDiscovery();
        }
    });

    private void doStartDiscovery() {
        observableList.clear();
        bluetoothList.clear();
        BTManager.getInstance().startDiscovery();
    }

    public BindingCommand OnStopClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            BTManager.getInstance().stopDiscovery();
        }
    });

    public BindingCommand OnConnectionClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

        }
    });

    public BindingCommand OnDisconnectionClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //断开指定连接
            stopBtService();
            if (bluetoothEntity != null)
                BTManager.getInstance().disconnectConnection(bluetoothEntity.getBluetoothDevice());
        }
    });

    public BindingCommand inventoryTypeChoiceOnClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            Configs.inventoryStatus = inventoryTypeStatus.get();
            if (inventoryTypeStatus.get()) {
                setGeneralInventoryFilter();
            } else {
                setSpecialInventoryFilter();
            }
            SPUtils.getInstance().put(Configs.SP_INVENTORY_STATUS, Configs.inventoryStatus);
        }
    });


    public void itemOnClick(BluetoothEntity btEntity) {
        BTManager.getInstance().stopDiscovery();
        stopBtService();
        bluetoothEntity = btEntity;

        showDialog("正在链接蓝牙...");

        Intent intent = new Intent(getApplication(), BtService.class);
        intent.putExtra("device", bluetoothEntity.getBluetoothDevice());
        if (!isServiceRunning(getApplication()))
            getApplication().startService(intent);
    }


    @Override
    public void onDiscoveryStart() {

    }

    @Override
    public void onDiscoveryStop() {

    }

    @Override
    public void onDeviceFound(@NonNull BluetoothDevice device, int rssi) {
        if (!TextUtils.isEmpty(device.getName())) {
            BluetoothEntity entity = new BluetoothEntity();
            entity.setName(device.getName());
            entity.setAddress(device.getAddress());
            entity.setRssi(rssi);
            entity.setBluetoothDevice(device);
            if (!bluetoothList.contains(entity)) {
                bluetoothList.add(entity);
                BLEItem bleItem = new BLEItem(this, entity);
                observableList.add(bleItem);
            }
        }
    }

    /**
     * 设置为标签最多的盘点
     *
     * @return
     */
    private int setSpecialInventoryFilter() {
        int tsh = 10;
        int maxRepeat = 1;
        int cacheTime = 0;
        int maxMonitorTagInRangeTimeMs = 400;
        int maxMonitorTagOutRangeTimeMs = 200;
        int filterMode = 2;
        maxRepeat |= (filterMode << 14);
        return setInventoryFilter(tsh, maxRepeat, cacheTime, maxMonitorTagInRangeTimeMs, maxMonitorTagOutRangeTimeMs);
    }

    /**
     * 设置为普通盘点
     *
     * @return
     */
    private int setGeneralInventoryFilter() {
        int tsh = 0;
        int maxRepeat = 1;
        int cacheTime = 0;
        int maxMonitorTagInRangeTimeMs = 0;
        int maxMonitorTagOutRangeTimeMs = 0;
        int filterMode = 0;
        maxRepeat |= (filterMode << 14);
        return setInventoryFilter(tsh, maxRepeat, cacheTime, maxMonitorTagInRangeTimeMs, maxMonitorTagOutRangeTimeMs);
    }

    /**
     * 设置盘点过滤门限值
     *
     * @param threshold      过滤门限，最大值为 10
     * @param maxRepeatTimes 最大上报次数
     * @param maxCacheTimeMs 最大缓存时间(ms)
     * @return 0--成功 非零--失败
     */
    public int setInventoryFilter(int threshold, int maxRepeatTimes, int maxCacheTimeMs, int maxMonitorTagInRangeTimeMs, int maxMonitorTagOutRangeTimeMs) {
        FilterParams filterParams = new FilterParams();
        filterParams.setThreshold(threshold);
        filterParams.setFilerFlag(maxRepeatTimes);
        filterParams.setMaxCacheTimeMs(maxCacheTimeMs);
        filterParams.setMaxMonitorTagInRangeTimeMs(maxMonitorTagInRangeTimeMs);
        filterParams.setMaxMonitorTagOutRangeTimeMs(maxMonitorTagOutRangeTimeMs);
        return App.getInstance().getLinkage().setInventoryFilter(filterParams);
    }


    @Override
    public void onDiscoveryError(int errorCode, @NonNull String errorMsg) {
        switch (errorCode) {
            case DiscoveryListener.ERROR_LACK_LOCATION_PERMISSION://缺少定位权限
                ToastUtils.showShort("搜索出错：缺少定位权限" + errorCode);
                break;
            case DiscoveryListener.ERROR_LOCATION_SERVICE_CLOSED://位置服务未开启
                ToastUtils.showShort("搜索出错：位置服务未开启" + errorCode);
                break;
            case DiscoveryListener.ERROR_LACK_SCAN_PERMISSION://缺少搜索权限
                ToastUtils.showShort("搜索出错：缺少搜索权限" + errorCode);
                break;
            case DiscoveryListener.ERROR_SCAN_FAILED://搜索失败
                ToastUtils.showShort("搜索出错：" + errorCode);
                break;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (BTManager.getInstance().isInitialized()) {
            BTManager.getInstance().stopDiscovery();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        Log.d("Main", "onResume");
        if (BTManager.getInstance().isInitialized()) {
            if (BTManager.getInstance().isBluetoothOn()) {
//                doStartDiscovery();
            } else {
                //未开启蓝牙
                btRequestEvent.call();
            }
        }
    }

    /**
     * 判断服务是否在运行中
     *
     * @param context 即为Context对象
     * @return 是否在运行中
     */
    private boolean isServiceRunning(Context context) {
        if (context != null) {
            ActivityManager activityManager
                    = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            ArrayList<ActivityManager.RunningServiceInfo> runningServiceInfoList
                    =
                    (ArrayList<ActivityManager.RunningServiceInfo>) activityManager.getRunningServices(100);
            for (ActivityManager.RunningServiceInfo runningServiceInfo : runningServiceInfoList) {
                if ("BtService".equals(runningServiceInfo.service.getClassName())) {
                    return true;
                }
            }
        } else {
            return false;
        }
        return false;
    }


    public void stopBtService() {
        if (isServiceRunning(getApplication())) {
            Intent intent = new Intent(getApplication(), BtService.class);
            getApplication().stopService(intent);
        }
    }


    @Override
    public void registerRxBus() {
        super.registerRxBus();
        weightBus =
                RxBus.getDefault().toObservable(EventMsg.class).subscribe(eventType -> {
                    if (eventType.getAction().equals(EventTag.EVENT_BT_SUCC)) {
                        ToastUtils.showShort("蓝牙链接成功");
                        myHandler.sendEmptyMessage(0);
//                        closeEvent.call();
                    } else if (eventType.getAction().equals(EventTag.EVENT_BT_FAIL)) {
                        ToastUtils.showShort("蓝牙链接失败");
                    }
                });
        RxSubscriptions.add(weightBus);
    }

    @Override
    public void removeRxBus() {
        super.removeRxBus();
        RxSubscriptions.remove(weightBus);
    }
    @SuppressLint("HandlerLeak")
    private  Handler myHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            dismissDialog();
            finish();
        }
    };


}
