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

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTest;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.base.BaseFragment;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.constant.MessageName;
import com.bonait.bnframework.common.db.mode.BPA_GOODS;
import com.bonait.bnframework.common.db.res.MakeStatus;
import com.bonait.bnframework.common.db.res.StatusMode;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.image.MyBitmapUtils;
import com.bonait.bnframework.common.message.MessageManager;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.bonait.bnframework.common.view.CircleImageView;
import com.bonait.bnframework.modules.home.adapter.gnleft_adapter;
import com.bonait.bnframework.modules.home.fragment.from.Cpxz1Activity;
import com.bonait.bnframework.modules.home.fragment.from.CpxzActivity;
import com.orhanobut.logger.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AutoTestMoreFragment extends BaseFragment {

    //region 变量
    @BindView(R.id.cpfm)
    CircleImageView cpfm;//菜谱封面

    @BindView(R.id.cpmc)
    TextView cpmc;//菜谱名称

    @BindView(R.id.caipu11)
    EditText caipu11;//菜谱循环次数

    @BindView(R.id.kaishixunhuan)
    Button kaishixunhuan;//开始循环

    @BindView(R.id.showbuttomtop)
    RelativeLayout showbuttomtop;//显示弹窗

    @BindView(R.id.xunhuancishu)
    TextView xunhuancishu;//循环次数

    @BindView(R.id.jieshutuichu)
    ImageView jieshutuichu;//结束退出

    @BindView(R.id.miaoshu)
    EditText miaoshu;//

    @BindView(R.id.qingkong)
    Button qingkong;//

    @BindView(R.id.qingkongjishu)
    Button qingkongjishu;//
    //endregion

    //region 界面
    private Context context;

    @Override
    protected View onCreateView() {
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_auto_test_more, null);
        ButterKnife.bind(this, root);
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Logger.d("我的fragment创建");
        context = getContext();
        Init();
        RefreshThread();
    }
    //endregion

    //region 公共

    /**
     * 初始化
     */
    public void Init() {
        RunCount=ConfigName.getInstance().RunCount;
        xunhuancishu.setText(RunCount + "");
        qingkongjishu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RunCount=0;
                ConfigName.getInstance().RunCount          =RunCount         ;
                ConfigData.getInstance().SavePZ();
                xunhuancishu.setText(RunCount + "");
            }
        });
        kaishixunhuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (GetTextInput(caipu11) == 0) {
                    ToastUtils.warning("循环次数不能为0或空!!!");
                    return;
                }

                if (good==null) {
                    ToastUtils.warning("商品不能为空!!!");
                    return;
                }
                showbuttomtop.setVisibility(View.VISIBLE);
                IsRun = true;
                //RunCount = 0;
                RunAllCount = GetTextInput(caipu11);
                ExecuteTheRecipe.StopForcedEnd();
            }
        });
        jieshutuichu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showbuttomtop.setVisibility(View.GONE);
                IsRun = false;
                ExecuteTheRecipe.SetForcedEnd();

                ConfigName.getInstance().RunCount           =RunCount          ;
                ConfigData.getInstance().SavePZ();
            }
        });

        /**
         * 选择菜谱
         */
        cpfm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                skipToActivity(Cpxz1Activity.class);
            }
        });
        qingkong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ClearMiaosShu();
            }
        });
        DataBus.getInstance().mListener1 = new MyClickListener() {
            @Override
            public void clickListener(View v, Object data) {

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        good = (BPA_GOODS) data;
                        cpmc.setText(good.name+"");
                        new MyBitmapUtils().disPlay(cpfm, good.url);
                    }
                });

            }
            @Override
            public void clickListenerNew(View v, int k, Object data) {

            }
        };
    }

    public boolean IsRun = false;
    public int RunCount = 0;
    public int RunAllCount = 0;

    public BPA_GOODS good=null;
    /**
     * 刷新UI线程
     */
    public void RefreshThread() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        if(IsRun)
                        {
                            MakeGood();
                        }
                        Thread.sleep(1000);
                    } catch (Exception ex) {

                    }
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        //故障信息
                        for (StatusMode item: ConfigName.getInstance().statusModes)
                        {
                            if(ExecuteTheRecipe.getConcurrentHash(item.sort))
                            {
                                SetMiaosShu1(item.Name);
                            }
                        }

                        String x1= ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("搅拌电机"));
                        String x2= ConfigName.getInstance().statusModes_电机.get(ExecuteTheRecipe.getConcurrentHash_dj("翻转电机"));
                        if(!x1.equals("无故障"))
                        {
                            SetMiaosShu1("搅拌电机故障代码："+x1);
                        }

                        if(!x2.equals("无故障"))
                        {
                            SetMiaosShu1("翻转电机故障代码："+x2);
                        }
                        Thread.sleep(2000);
                    } catch (Exception ex) {

                    }
                }
            }
        }).start();
    }


    /**
     * 制作商品
     */
    public void MakeGood()
    {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                xunhuancishu.setText(RunCount+"");
            }
        });
        if(RunCount<RunAllCount && !ExecuteTheRecipe.IsForcedEnd)
        {
            //制作商品
            DataBus.getInstance().mListener.clickListener(null, good);
            ExecuteTheRecipe.MakeStatus=false;
            MessageManager.getInstance().sendMessage(MessageName.IsStratMakeGood1, good.id);

            //等待开始
            while (!ExecuteTheRecipe.MakeStatus && !ExecuteTheRecipe.IsForcedEnd)
            {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {

                }
            }

            //等待结束
            while (ExecuteTheRecipe.MakeStatus && !ExecuteTheRecipe.IsForcedEnd)
            {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {

                }
            }
            RunCount++;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    xunhuancishu.setText(RunCount+"");
                }
            });
        }else
        {
            IsRun=false;
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    showbuttomtop.setVisibility(View.GONE);
                }
            });
        }
    }
    //endregion

    //region 私有函数

    /**
     * 获取输入文字
     *
     * @param editText
     * @return
     */
    public int GetTextInput(EditText editText) {
        int res = 0;
        try {
            if (!editText.getText().toString().isEmpty()) {
                res = Integer.parseInt(editText.getText().toString());
            }
        } catch (Exception ex) {
            res = 0;
        }
        return res;
    }
    /**
     * 跳转界面
     */
    private void skipToActivity(Class da) {
        // 跳转到登录页面
        Intent intent = new Intent(context, da);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 不重复
     * @param text
     */
    public void SetMiaosShu1(String text) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String YL=   miaoshu.getText().toString();
                if(!YL.isEmpty() && YL.contains(text))
                {

                }else
                {
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = new Date();
                    String tempMsg =  YL+ formatter.format(date) + "：" + text + "\n";
                    miaoshu.setText(tempMsg);
                    ToastUtils.warning(formatter.format(date) + "：" + text);
                }
            }
        });
    }

    /**
     * 清空显示
     *
     * @param
     */
    public void ClearMiaosShu() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                miaoshu.setText("");
            }
        });
    }
    //endregion
}