package com.phlx.anchorcollect.ui.main;

import android.content.res.Resources;
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.App;
import com.phlx.anchorcollect.BR;
import com.phlx.anchorcollect.Configs;
import com.phlx.anchorcollect.R;
import com.phlx.anchorcollect.data.VMFactory;
import com.phlx.anchorcollect.databinding.ActivityMainBinding;
import com.phlx.anchorcollect.rfid.ConnectManger;
import com.phlx.anchorcollect.rfid.ModuleManager;
import com.phlx.anchorcollect.ui.base.BaseActivity;
import com.phlx.anchorcollect.ui.feedback.FeedbackActivity;
import com.phlx.anchorcollect.ui.fragment.BasicsCollectFragment;
import com.phlx.anchorcollect.ui.fragment.BreedingRecordFragment;
import com.phlx.anchorcollect.ui.fragment.ImmunRecordFragment;
import com.phlx.anchorcollect.ui.fragment.MedicalRecordFragment;
import com.phlx.anchorcollect.ui.fragment.PerformanceFragment;
import com.phlx.anchorcollect.ui.fragment.WeightManFragment;
import com.uhf.structures.DynamicQParams;
import com.uhf.structures.InventoryParams;

import me.goldze.mvvmhabit.utils.SPUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;
import me.jessyan.autosize.AutoSizeCompat;

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();
        if (Configs.isOnLine)
            showTips();
    }

    private void initRFID(){

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

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

        App.getInstance().getLinkage().setRFConnectMode(0);
        if (!ModuleManager.initPower()) {
            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();
        }
        //先看缓存的盘点模式，true普通盘点-多次，false 盘到最多数量的标签-一次
        viewModel.setInventoryStatus();

        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("获取动态算法失败");
        }
    }

    private void showTips() {
        int showTipsCount = SPUtils.getInstance().getInt(Configs.SP_FEEDBACK_COUNT);
        if (showTipsCount < 3) {
            new MaterialDialog.Builder(this).title("各位平台用户")
                    .content("         本平台使用各用户提供的种畜场地址、联系人和联系电话等信息建立账号。本平台将竭力保障各用户信息安全，但由于以上信息的使用必然在个人信息泄露风险。现将该风险进行告知，如有异议请通过反馈进行告知修改，如同意继续使用此信息请点击确认。")
                    .cancelable(false)
                    .canceledOnTouchOutside(false)
                    .positiveText("确定")
                    .negativeText("反馈")
                    .onAny(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (which == DialogAction.POSITIVE) {
                                dialog.dismiss();
                            } else if (which == DialogAction.NEGATIVE) {
                                startActivity(FeedbackActivity.class);
                            }
                        }
                    })
                    .show();
            showTipsCount++;
            SPUtils.getInstance().put(Configs.SP_FEEDBACK_COUNT, showTipsCount);
        }
    }


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

        viewModel.onTabClickEvent.observe(this, new Observer<Integer>() {
            @Override
            public void onChanged(Integer integer) {
                Configs.resumeId = null;
                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();
    }
    @Override
    public Resources getResources() {
        //需要升级到 v1.1.2 及以上版本才能使用 AutoSizeCompat
        AutoSizeCompat.autoConvertDensityOfGlobal(super.getResources());//如果没有自定义需求用这个方法
        // AutoSizeCompat.autoConvertDensity(super.getResources(), 667, false);//如果有自定义需求就用这个方法
        return super.getResources();
    }
}
