package com.bonait.bnframework.modules.home.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.RelativeLayout;

import com.apkfuns.logutils.LogUtils;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.business.OrderServer;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.helper.I.IThread;
import com.bonait.bnframework.common.helper.MQTT;
import com.bonait.bnframework.common.helper.MediaPlayerHelper;
import com.bonait.bnframework.common.helper.MessageLog;
import com.bonait.bnframework.common.helper.ThreadManager;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
import com.bonait.bnframework.common.modbus.ModbusTcpServer;
import com.bonait.bnframework.common.tabbar.MainNavigateTabBar;
import com.bonait.bnframework.common.utils.NetworkUtils;
import com.bonait.bnframework.modules.home.adapter.FragmentAdapter;
import com.bonait.bnframework.modules.home.fragment.DingDanfragment;
import com.bonait.bnframework.modules.home.fragment.GongnengFragment;
import com.bonait.bnframework.modules.home.fragment.GuanLifragment;
import com.bonait.bnframework.modules.home.fragment.JiaoYanFragment;
import com.bonait.bnframework.modules.home.fragment.MakeGoodFragment;
import com.bonait.bnframework.modules.home.fragment.SheZhifragment;
import com.bonait.bnframework.modules.home.fragment.mode.SerialInter;
import com.bonait.bnframework.modules.home.fragment.mode.SerialManage;
//import com.bonait.bnframework.modules.home.fragment.mode.ShaomaTest;
import com.bonait.bnframework.modules.mine.fragment.MyFragment;
import com.bumptech.glide.Glide;
import com.qmuiteam.qmui.widget.QMUIViewPager;

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

import butterknife.BindView;
import butterknife.ButterKnife;

public class BottomNavigationMainActivity extends BaseActivity{

    @BindView(R.id.mainTabBar)
    MainNavigateTabBar mNavigateTabBar;

    @BindView(R.id.viewpager)
    QMUIViewPager viewPager;



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

        ButterKnife.bind(this);
        MediaPlayerHelper.getInstance().SetConText(getBaseContext());
        mNavigateTabBar.onRestoreInstanceState(savedInstanceState);
        mNavigateTabBar.addTab(null, new MainNavigateTabBar.TabParam(R.mipmap.gongneng, R.mipmap.gongneng_selected, "功能"));
        mNavigateTabBar.addTab(null, new MainNavigateTabBar.TabParam(R.mipmap.dingdan, R.mipmap.dingdan_selected, "订单"));
        mNavigateTabBar.addTab(null, new MainNavigateTabBar.TabParam(0, 0, ""));
        mNavigateTabBar.addTab(null, new MainNavigateTabBar.TabParam(R.mipmap.shezhi, R.mipmap.shezhi_selected, "设置"));
        mNavigateTabBar.addTab(null, new MainNavigateTabBar.TabParam(R.mipmap.comui_tab_person, R.mipmap.comui_tab_person_selected, "我的"));
        mNavigateTabBar.setTabSelectListener(mOnNavigationItemSelectedListener);
        initFragment();
        Init();


       /* shaoma_Text.requestFocus();
        shaoma_Text.setInputType(InputType.TYPE_NULL);
        shaoma_Text.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    shaoma_Text.setInputType(InputType.TYPE_NULL);
                } else {
                    shaoma_Text.clearFocus();
                    shaoma_Text.requestFocus();
                }
            }
        });
        shaoma_Text.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (shaoma_Text.getText() != null && shaoma_Text.getText().toString() != "") {
                        String msg = shaoma_Text.getText().toString();
                        msg = msg.replace("\\n", "");
                        if (fragmentList.size()>2){
                            MakeGoodFragment makeGoodFragment=(MakeGoodFragment) fragmentList.get(2);
                            makeGoodFragment.RecipeRun(msg);
                        }
                    }
                    shaoma_Text.setText("");
                    shaoma_Text.clearFocus();
                    shaoma_Text.setInputType(InputType.TYPE_CLASS_TEXT);
                    shaoma_Text.requestFocus();

                }
                return false;
            }
        });
        InputMethodManager im = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        shaoma_Text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                im.hideSoftInputFromWindow(shaoma_Text.getWindowToken(), 0);
            }
        });*/


    }


    @Override
    protected void onDestroy() {
        //关闭PLC连接
        ConfigData.getInstance().ColsePLC();
        MediaPlayerHelper.getInstance().Release();
        MQTT.get().ConnMqttBroken(false);//释放mqtt
        ThreadManager.Get().Stop("PLC断线重连线程");
        ThreadManager.Get().Stop("心跳服务");
        ExecuteTheRecipe.releaseListening();
        super.onDestroy();

        Glide.get(this).clearMemory();
    }

    private List<Fragment> fragmentList = new ArrayList<Fragment>();

    /**
     * viewPager里添加fragment
     */
    private void initFragment() {

        fragmentList = new ArrayList<>();
        fragmentList.add(new GongnengFragment());
        fragmentList.add(new DingDanfragment());
        fragmentList.add(new MakeGoodFragment(viewPager));
        fragmentList.add(new SheZhifragment());
        fragmentList.add(new MyFragment());
        ConfigName.getInstance().fragmentAdapter = new FragmentAdapter(getSupportFragmentManager(), fragmentList);
        viewPager.setAdapter(ConfigName.getInstance().fragmentAdapter);
        ConfigName.getInstance().fragmentAdapter.SetViewPage(viewPager);
        //手指滑动
        viewPager.addOnPageChangeListener(pageChangeListener);
        // 设置viewPager缓存多少个fragment
        viewPager.setOffscreenPageLimit(5);
        // 再来一单
        viewPager.setCurrentItem(2);
    }

    /**
     * 初始化
     */
    public void Init() {
        //1.同步时间
        NetworkUtils.SynchronizationTime();
        //主持
//        ConfigData.getInstance().GetOrganize(this);
        //判断连接环境
        ConfigData.getInstance().ToggleEnvironment();
        //2.初始化PLC
        ReconnectModbus();
        //MQTT数据监听
        OrderServer.Get().MqttInit();

    }

    /**
     * 重新连接plc
     */
    public void ReconnectModbus() {
        try {

            ThreadManager.Get().StartLong("PLC断线重连线程", true, new IThread() {
                @Override
                public void Run() throws InterruptedException {
                    LogUtils.d("ReconnectModbus PLC断线重连线程");
                    try {
                        if (ConfigName.getInstance().PlcIsConnect) {
                            //ping 不通
                            boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
                            if (!status) //ping 不通 连接
                            {
                                MessageLog.ShowInfo("PLC状态断开,尝试连接...");
                                ConfigName.getInstance().PlcIsConnect = false;
                            }
                        } else {
                            boolean status = ModbusTcpServer.ping2(ConfigName.getInstance().Address, 1, 1);
                            if (status) {
                                MessageLog.ShowInfo("设备 " + ConfigName.getInstance().Address + " PLC通讯正常,准备连接！");
                                ModbusTcpServer.ConnectPLC();
                            } else {
                                MessageLog.ShowInfo("PLC状态断开,尝试连接...");
                                ConfigName.getInstance().PlcIsConnect = false;
                            }
                        }

                        LocalCacheUtils.Get().RunCPUOrMemory();

                        Thread.sleep(5000);
                    } catch (Exception e) {
                        Log.i("PLC", "PLC重连接失败!" + e.getMessage());
                    }
                }

                @Override
                public void RunComplete() throws InterruptedException {
                }
            });
        } catch (Exception e) {
            MessageLog.ShowInfo("重新连接Modbus异常，" + e.getMessage());
        }
    }


    /**
     * 配置bottom底部菜单栏监听器，手指点击底部菜单监听
     */
    private MainNavigateTabBar.OnTabSelectedListener mOnNavigationItemSelectedListener
            = new MainNavigateTabBar.OnTabSelectedListener() {
        @Override
        public void onTabSelected(MainNavigateTabBar.ViewHolder holder) {
            int _postion = 2;
            switch (holder.tag) {
                case "功能":
                    _postion = 0;
                    break;
                case "订单":
                    _postion = 1;
                    break;
                case "设置":
                    _postion = 3;
                    break;
                case "我的":
                    _postion = 4;
                    break;
                case "":
                    _postion = 2;
                    break;
            }
            viewPager.setCurrentItem(_postion);
        }
    };
    /**
     * 配置ViewPager监听器，手指滑动监听
     */
    private ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            mNavigateTabBar.setCurrentSelectedTab(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    };
}