package com.phlx.anchorcollect_p.ui.main;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.KeyEvent;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.phlx.anchorcollect_p.App;
import com.phlx.anchorcollect_p.BR;
import com.phlx.anchorcollect_p.Configs;
import com.phlx.anchorcollect_p.R;
import com.phlx.anchorcollect_p.data.VMFactory;
import com.phlx.anchorcollect_p.databinding.ActivityMainBinding;
import com.phlx.anchorcollect_p.rfid.ConnectManger;
import com.phlx.anchorcollect_p.rfid.ModuleManager;
import com.phlx.anchorcollect_p.ui.base.BaseActivity;
import com.phlx.anchorcollect_p.ui.fragment.BasicsCollectFragment;
import com.phlx.anchorcollect_p.ui.fragment.BreedingRecordFragment;
import com.phlx.anchorcollect_p.ui.fragment.ImmunRecordFragment;
import com.phlx.anchorcollect_p.ui.fragment.MedicalRecordFragment;
import com.phlx.anchorcollect_p.ui.fragment.PerformanceFragment;
import com.phlx.anchorcollect_p.ui.fragment.WeightManFragment;
import com.uhf.structures.DynamicQParams;
import com.uhf.structures.InventoryParams;

import me.goldze.mvvmhabit.utils.ToastUtils;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainVM> {

    private String collectType = "";


    private ConnectManger connectManger;

    private FragmentTransaction transaction;

    private BasicsCollectFragment _basicsCollectFragment;
    private PerformanceFragment _performanceFragment;
    private WeightManFragment _weightManFragment;
    private MedicalRecordFragment _medicalRecordFragment;
    private ImmunRecordFragment _immunRecordFragment;
    private BreedingRecordFragment _breedingRecordFragment;

    private Drawable drwCattleOn;
    private Drawable drwCattleOff;
    private Drawable drwPerformanceOn;
    private Drawable drwPerformanceOff;
    private Drawable drwWeightManOn;
    private Drawable drwWeightManOff;
    private Drawable drwMedicalOn;
    private Drawable drwMedicalOff;
    private Drawable drwImmuneOn;
    private Drawable drwImmuneOff;
    private Drawable drwBreedingOn;
    private Drawable drwBreedingOff;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public void initParam() {
        super.initParam();

        Bundle mBundle = getIntent().getExtras();
        if (mBundle != null) {
            collectType = mBundle.getString("COLLECT_TYPT");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        labelSwitching(Configs.mainPosition);
    }

    @Override
    public MainVM initViewModel() {
        VMFactory factory = VMFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MainVM.class);
    }

    @Override
    public void initData() {
        super.initData();

        viewModel.init();

        drwCattleOn = getResources().getDrawable(R.mipmap.jichuxinxi2);
        drwCattleOff = getResources().getDrawable(R.mipmap.jichuxinxi1);
        drwPerformanceOn = getResources().getDrawable(R.mipmap.xingnengceding2);
        drwPerformanceOff = getResources().getDrawable(R.mipmap.xingnengceding1);
        drwWeightManOn = getResources().getDrawable(R.mipmap.chengzhong2);
        drwWeightManOff = getResources().getDrawable(R.mipmap.chengzhong1);
        drwMedicalOn = getResources().getDrawable(R.mipmap.zhenliaojilu2);
        drwMedicalOff = getResources().getDrawable(R.mipmap.zhenliaojilu1);
        drwImmuneOn = getResources().getDrawable(R.mipmap.mianyijilu2);
        drwImmuneOff = getResources().getDrawable(R.mipmap.mianyijilu1);
        drwBreedingOn = getResources().getDrawable(R.mipmap.peizhong2);
        drwBreedingOff = getResources().getDrawable(R.mipmap.peizhong1);

        drwCattleOn.setBounds(0, 0, drwCattleOn.getMinimumWidth(), drwCattleOn.getMinimumHeight());
        drwCattleOff.setBounds(0, 0, drwCattleOff.getMinimumWidth(), drwCattleOff.getMinimumHeight());
        drwPerformanceOn.setBounds(0, 0, drwPerformanceOn.getMinimumWidth(), drwPerformanceOn.getMinimumHeight());
        drwPerformanceOff.setBounds(0, 0, drwPerformanceOff.getMinimumWidth(), drwPerformanceOff.getMinimumHeight());
        drwWeightManOn.setBounds(0, 0, drwWeightManOn.getMinimumWidth(), drwWeightManOn.getMinimumHeight());
        drwWeightManOff.setBounds(0, 0, drwWeightManOff.getMinimumWidth(), drwWeightManOff.getMinimumHeight());
        drwMedicalOn.setBounds(0, 0, drwMedicalOn.getMinimumWidth(), drwMedicalOn.getMinimumHeight());
        drwMedicalOff.setBounds(0, 0, drwMedicalOff.getMinimumWidth(), drwMedicalOff.getMinimumHeight());
        drwImmuneOn.setBounds(0, 0, drwImmuneOn.getMinimumWidth(), drwImmuneOn.getMinimumHeight());
        drwImmuneOff.setBounds(0, 0, drwImmuneOff.getMinimumWidth(), drwImmuneOff.getMinimumHeight());
        drwBreedingOn.setBounds(0, 0, drwBreedingOn.getMinimumWidth(), drwBreedingOn.getMinimumHeight());
        drwBreedingOff.setBounds(0, 0, drwBreedingOff.getMinimumWidth(), drwBreedingOff.getMinimumHeight());

        //初始化标题
//        viewModel.initToolbar(getTitleName());
        //初始化Fragment
        initFragment();

        initRFID();
    }

    private void initRFID(){

        connectManger = ConnectManger.from();
        //默认设置R2000连接
//        connectManger.setModuleR2000();`

        App.getInstance().getLinkage().stopInventory();
        SystemClock.sleep(200);
        //下电
        ModuleManager.powerOff();

        App.getInstance().getLinkage().setRFConnectMode(0);
        App.getInstance().getLinkage().setRFModuleType(3);//R2000 0,R2000plus 3
        if (ModuleManager.openCom() != 0 || ModuleManager.powerOn() != 0) {
            new MaterialDialog.Builder(this).title("系统提示").content("串口打开失败，无法工作，请检查设备").cancelable(false).canceledOnTouchOutside(false).positiveText("退出").onAny(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        finishRFID();
                        finish();
//                            android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }
            }).show();
        } else {
            App.getInstance().getLinkage().stopInventory();
        }

        ToastUtils.showShort(connectManger.getModuleVersion());
        //设置盘点内容：Epc + Tid
        InventoryParams inventoryParams = new InventoryParams();
        inventoryParams.address = 0;
        inventoryParams.inventoryArea = 2;
        inventoryParams.len = 6;
        App.getInstance().getLinkage().Radio_SetInventoryParams(inventoryParams);

        setAlgorithm();
    }

    /**
     * 获取算法
     */
    private void setAlgorithm() {

        DynamicQParams dynamicQParams = new DynamicQParams();
        int dynamic_state =
                App.getInstance().getLinkage().Radio_GetSingulationAlgorithmDyParameters(dynamicQParams);
        if (dynamic_state == 0) {
            dynamicQParams.thresholdMultiplier = 4;
            int dynamicResult =
                    App.getInstance().getLinkage().Radio_SetSingulationAlgorithmDyParameters(dynamicQParams);

            if (dynamicResult == 0) {
//                ToastUtils.showShort("设置动态算法成功");
//                int saveStatue = App.getInstance().getLinkage().saveR2000Setting();
//                if (saveStatue == 0) {
////                    ToastUtils.showShort("参数保存成功");
//                } else {
//                    ToastUtils.showShort("参数保存失败");
//                }
            } else {
                ToastUtils.showShort("设置动态算法失败");
            }
//            ToastUtils.showShort("获取动态算法成功");
        }else {
            ToastUtils.showShort("获取动态算法失败");
        }
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();

        viewModel.onTabClickEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                labelSwitching(integer);

                Configs.mainPosition = integer;
            }
        });
    }

    private void initFragment() {

        transaction = getSupportFragmentManager().beginTransaction();

        _basicsCollectFragment = BasicsCollectFragment.getInstance();
        _performanceFragment = PerformanceFragment.getInstance();
        _weightManFragment = WeightManFragment.getInstance();
        _medicalRecordFragment = MedicalRecordFragment.getInstance();
        _immunRecordFragment = ImmunRecordFragment.getInstance();
        _breedingRecordFragment = BreedingRecordFragment.getInstance();
        transaction.add(R.id.frameLayout, _basicsCollectFragment);
        transaction.add(R.id.frameLayout, _performanceFragment);
        transaction.add(R.id.frameLayout, _weightManFragment);
        transaction.add(R.id.frameLayout, _medicalRecordFragment);
        transaction.add(R.id.frameLayout, _immunRecordFragment);
        transaction.add(R.id.frameLayout, _breedingRecordFragment);
        transaction.commit();
        labelSwitching(Configs.mainPosition);
    }

    public void labelSwitching(int position) {

        transaction = getSupportFragmentManager().beginTransaction();
        transaction.hide(_basicsCollectFragment);
        transaction.hide(_performanceFragment);
        transaction.hide(_weightManFragment);
        transaction.hide(_medicalRecordFragment);
        transaction.hide(_immunRecordFragment);
        transaction.hide(_breedingRecordFragment);
        binding.tvTab0.setTextColor(getResources().getColor(R.color.color_font_non_focus));
        binding.tvTab1.setTextColor(getResources().getColor(R.color.color_font_non_focus));
        binding.tvTab2.setTextColor(getResources().getColor(R.color.color_font_non_focus));
        binding.tvTab3.setTextColor(getResources().getColor(R.color.color_font_non_focus));
        binding.tvTab4.setTextColor(getResources().getColor(R.color.color_font_non_focus));
        binding.tvTab5.setTextColor(getResources().getColor(R.color.color_font_non_focus));

        binding.tvTab0.setCompoundDrawables(null, drwCattleOff, null, null);
        binding.tvTab1.setCompoundDrawables(null, drwPerformanceOff, null, null);
        binding.tvTab2.setCompoundDrawables(null, drwWeightManOff, null, null);
        binding.tvTab3.setCompoundDrawables(null, drwMedicalOff, null, null);
        binding.tvTab4.setCompoundDrawables(null, drwImmuneOff, null, null);
        binding.tvTab5.setCompoundDrawables(null, drwBreedingOff, null, null);

        switch (position) {
            case 0:
                transaction.show(_basicsCollectFragment);
                binding.tvTab0.setTextColor(getResources().getColor(R.color.white));
                binding.tvTab0.setCompoundDrawables(null, drwCattleOn, null, null);
                break;
            case 1:
                Bundle args = new Bundle();
                args.putString("id", "-1");
                transaction.show(_performanceFragment);
                binding.tvTab1.setTextColor(getResources().getColor(R.color.white));
                binding.tvTab1.setCompoundDrawables(null, drwPerformanceOn, null, null);
                break;
            case 2:
                transaction.show(_weightManFragment);
                binding.tvTab2.setTextColor(getResources().getColor(R.color.white));
                binding.tvTab2.setCompoundDrawables(null,  drwWeightManOn,null, null);
                break;
            case 3:
                transaction.show(_medicalRecordFragment);
                binding.tvTab3.setTextColor(getResources().getColor(R.color.white));
                binding.tvTab3.setCompoundDrawables(null, drwMedicalOn, null, null);
                break;
            case 4:
                transaction.show(_immunRecordFragment);
                binding.tvTab4.setTextColor(getResources().getColor(R.color.white));
                binding.tvTab4.setCompoundDrawables(null, drwImmuneOn, null, null);
                break;
            case 5:
                transaction.show(_breedingRecordFragment);
                binding.tvTab5.setTextColor(getResources().getColor(R.color.white));
                binding.tvTab5.setCompoundDrawables(null, drwBreedingOn, null, null);
                break;
        }

        transaction.commit();
    }

    /**
     * 监听Back键按下事件
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            MessageDialog.show("系统提示", "是否退出程序?", "确定", "取消")
//                    .setOkButton(new OnDialogButtonClickListener<MessageDialog>() {
//                        @Override
//                        public boolean onClick(MessageDialog baseDialog, View v) {
//                            ModuleManager.destroyLibSO();
//                            finish();
//                            android.os.Process.killProcess(android.os.Process.myPid());
//                            return false;
//                        }
//                    })
//            .setCancelButton(new OnDialogButtonClickListener<MessageDialog>() {
//                @Override
//                public boolean onClick(MessageDialog baseDialog, View v) {
//                    return false;
//                }
//            })
//            ;

            new MaterialDialog.Builder(this).title("系统提示").content("是否退出程序?").positiveText("确定").negativeText("取消").onAny(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    if (which == DialogAction.POSITIVE) {
                        ModuleManager.destroyLibSO();
                        finish();
                        android.os.Process.killProcess(android.os.Process.myPid());
                    }
                }
            }).show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void finishRFID() {
        ModuleManager.destroyLibSO();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finishRFID();
    }
}
