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.util.Log;
import android.view.MenuItem;
import android.widget.RelativeLayout;

import com.bonait.bnframework.HBL.Logs.MessageLog;
import com.bonait.bnframework.HBL.Thread.IThread;
import com.bonait.bnframework.HBL.Thread.ThreadManager;
import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
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.MQTT;
import com.bonait.bnframework.common.helper.MediaPlayerHelper;
import com.bonait.bnframework.common.helper.ModbusHelper;
import com.bonait.bnframework.common.image.utils.LocalCacheUtils;
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.mine.fragment.MyFragment;
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();


    }

    @Override
    protected void onDestroy() {
        //关闭PLC连接
        ConfigData.getInstance().ColsePLC();
        MediaPlayerHelper.getInstance().Release();
        MQTT.get().ConnMqttBroken(false);//释放mqtt
        super.onDestroy();
    }

    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());
        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
        ModbusHelper.get().RtuInit("/dev/ttyCOM0",9600);
//        ReconnectModbus();
        //MQTT数据监听
        OrderServer.Get().MqttInit();
    }



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



//            ThreadManager.get().StartLong("PLC断线重连线程", true, new IThread() {
//                @Override
//                public void Run() throws InterruptedException {
//                    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());
//                    }
//                }
//
//
//            });
        } 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) {
        }
    };
}