package com.bonait.bnframework.modules.home.fragment.from;

import static com.bonait.bnframework.MainApplication.getContext;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseActivity;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_SUGAR;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.WrapContentLinearLayoutManager;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.modules.home.adapter.zdqxchid_adapter;
import com.orhanobut.logger.Logger;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ZdqxActivity extends BaseActivity {

    @BindView(R.id.topbar)
    QMUITopBarLayout mTopBar;
    @BindView(R.id.bt_start)
    Button bt_start;//开始清洗

    @BindView(R.id.Recy_zdqx)
    RecyclerView Recy_zdqx;//自动清洗流程

    private Context context;

    public Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zdqx);
        ButterKnife.bind(this);
        context = getContext();
        activity = this;
        initTopBar();
        InitView();
    }

    private void initTopBar() {
        mTopBar.setTitle("清洗料仓");
        mTopBar.addLeftImageButton(R.mipmap.fanhui, R.id.topbar).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    /**
     * 初始化界面
     */
    public void InitView() {
        Initdata();
    }

    @OnClick({R.id.bt_add_zdqx, R.id.bt_start})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_add_zdqx://增加流程
                BPA_SUGAR sugar = new BPA_SUGAR();
                sugar.plcvar = "0.0|0.0|0";
                QueryDB.AddSugar(sugar);
                DataBus.getInstance().GetZDQXChid();
                ToastUtils.info("增加成功！");
                break;
            case R.id.bt_start://开始清洗


                if (DataBus.getInstance().ZDQX_IsStart) {

                    String title = "温馨提示！";
                    String message = "客官确定要强制停止清洗吗？";
                    AlertDialogUtils.showDialog(context, title, message, new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Speak(R.raw.qxksqsh);
                                    ExecuteTheRecipe.WritePLC("清洗模式", false, null);
                                    ExecuteTheRecipe.WritePLC("自动清洗开始", false, null);
                                    DataBus.getInstance().ZDQX_IsStart = false;
                                    bt_start.setText("开始清洗");
                                    bt_start.setBackgroundResource(R.drawable.sz_bj);

                                    for (BPA_SUGAR item :
                                            DataBus.getInstance().zdqx) {
                                        item.exp = null;
                                    }
                                    DataBus.getInstance().zdqxchidAdapter.refresh();
                                }
                            });
                            dialog.dismiss();
                        }
                    });
                    return;
                }
                ExecuteTheRecipe.WritePLC("清洗模式", true, new IWriteCallBack() {
                    @Override
                    public void onSuccess() {
                        DataBus.getInstance().ZDQX_IsStart = true;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                bt_start.setText("正在清洗");
                                bt_start.setBackgroundResource(R.drawable.cp_bj);
                            }
                        });

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {

                                    if (DataBus.getInstance().ZDQX_IsStart) {
                                        ExecuteTheRecipe.WritePLC("管道自动排水完成", false, null);
                                        ExecuteTheRecipe.WritePLC("管道自动排水", true, null);
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                ToastUtils.warning("管道自动排水中,请稍后...");
                                                bt_start.setText("管道排水中");
                                            }
                                        });
                                        final boolean[] IsStopPS = {false};
                                        while (DataBus.getInstance().ZDQX_IsStart && !IsStopPS[0]) {
                                            Object iswanc = ExecuteTheRecipe.ReadPLC("管道自动排水完成");
                                            if (iswanc != null && (boolean) iswanc) {
                                                IsStopPS[0] = true;
                                            }
                                        }

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                bt_start.setText("正在清洗");
                                            }
                                        });
                                        for (BPA_SUGAR item :
                                                DataBus.getInstance().zdqx) {
                                            ExecuteTheRecipe.WritePLC("自动清洗完成", false, null);
                                            Thread.sleep(100);//10 *6
                                            if (DataBus.getInstance().ZDQX_IsStart) {
                                                item.exp = "执行中";
                                                DataBus.getInstance().zdqxchidAdapter.refresh();
                                            }
                                            final boolean[] IsStop = {false};
                                            ExecuteTheRecipe.CleaningComplete = new IRun() {
                                                @Override
                                                public void Run() {
                                                    IsStop[0] = true;
                                                }
                                            };

                                            while (DataBus.getInstance().ZDQX_IsStart && !IsStop[0]) {
                                                Thread.sleep(100);//10 *6
                                            }
                                            if (DataBus.getInstance().ZDQX_IsStart) {
                                                item.exp = "执行完成";
                                                DataBus.getInstance().zdqxchidAdapter.refresh();
                                            }
                                        }

                                        ExecuteTheRecipe.WritePLC("管道自动排水完成", false, null);
                                        ExecuteTheRecipe.WritePLC("管道自动排水", true, null);

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                ToastUtils.warning("管道自动排水中,请稍后...");
                                                bt_start.setText("管道排水中");
                                            }
                                        });
                                        IsStopPS[0] = false;
                                        while (DataBus.getInstance().ZDQX_IsStart && !IsStopPS[0]) {
                                            Object iswanc = ExecuteTheRecipe.ReadPLC("管道自动排水完成");
                                            if (iswanc != null && (boolean) iswanc) {
                                                IsStopPS[0] = true;
                                            }
                                        }

                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                ToastUtils.warning("清洗完成！");
                                                DataBus.getInstance().ZDQX_IsStart = false;
                                                bt_start.setText("开始清洗");
                                                bt_start.setBackgroundResource(R.drawable.sz_bj);

                                                for (BPA_SUGAR item :
                                                        DataBus.getInstance().zdqx) {
                                                    item.exp = null;
                                                }
                                                DataBus.getInstance().zdqxchidAdapter.refresh();
                                            }
                                        });

                                        Speak(R.raw.qxwc);
                                    }

                                } catch (Exception e) {
                                }

                            }
                        }).start();
                    }

                    @Override
                    public void onFailure(String ErrorMsg) {
                        ToastUtils.error("启动失败！");
                    }
                });
                break;
        }
    }

    //region 数据加载

    /**
     * 初始化数据加载
     */
    public void Initdata() {
        try {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        DataBus.getInstance().GetZDQXChid();
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Recy_zdqx.setLayoutManager(new WrapContentLinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
                                DataBus.getInstance().zdqxchidAdapter = new zdqxchid_adapter(getContext(), activity);
                                Recy_zdqx.setAdapter(DataBus.getInstance().zdqxchidAdapter);
                            }
                        });

                    } catch (Exception e) {

                    }
                }
            }).start();
        } catch (Exception e) {

        }
    }
    //endregion
    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.d("我的fragment销毁");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    ExecuteTheRecipe.WritePLC("清洗模式", false, null);
                } catch (Exception e) {

                }
            }
        }).start();
    }

    /**
     * 当在activity设置viewPager + BottomNavigation + fragment时，
     * 为防止viewPager左滑动切换界面，与fragment左滑返回上一界面冲突引起闪退问题，
     * 必须加上此方法，禁止fragment左滑返回上一界面。
     * <p>
     * 切记！切记！切记！否则会闪退！
     * <p>
     * 当在fragment设置viewPager + BottomNavigation + fragment时，则不会出现这个问题。
     */
    @Override
    protected boolean canDragBack() {
        return false;
    }
}