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

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.business.MainInit;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.DataBus;
import com.bonait.bnframework.common.db.res.SilosLsjyMode;
import com.bonait.bnframework.common.db.res.wdszMode;
import com.bonait.bnframework.common.helper.I.IRun;
import com.bonait.bnframework.common.helper.I.IWriteCallBack;
import com.bonait.bnframework.common.helper.InputFilterMinMax;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.suke.widget.SwitchButton;

import java.util.List;

public class wdsz_adapter  extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final LayoutInflater mLayoutInflater;

    private Context context;

    public List<wdszMode> wdszModes = DataBus.getInstance().wdszModes;

    public wdsz_adapter(Context context) {
        this.context = context;
        mLayoutInflater = LayoutInflater.from(context);
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View inflate = mLayoutInflater.inflate(R.layout.wdsz_item, parent, false);
        return new WDSZViewHolder(inflate);

    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        try {
            if (holder instanceof WDSZViewHolder) {
                WDSZViewHolder myViewHolder = (WDSZViewHolder) holder;
                wdszMode goodsMake= wdszModes.get(position);

                myViewHolder.name.setText(goodsMake.name+"");
                myViewHolder.edittext_sx.setText(goodsMake.tempup+"");
                myViewHolder.zdbs3.setVisibility(View.GONE);
                myViewHolder.control_switch_bs.setChecked(false);
                if(goodsMake.name.equals("水池温度"))
                {

                    myViewHolder.zdbs1.setVisibility(View.VISIBLE);
                    myViewHolder.zdbs2.setVisibility(View.VISIBLE);

                    myViewHolder.edittext_sx.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "45")});

                    myViewHolder.control_switch_bs.setChecked(ConfigName.getInstance().AutomaticWaterRefill);
                    myViewHolder.zdbs3.setVisibility(ConfigName.getInstance().AutomaticWaterRefill==false?View.VISIBLE:View.GONE);

                    myViewHolder.edittext_ycsj.setText(ConfigName.getInstance().AutomaticWaterRefillTime);
                } else if (goodsMake.name.equals("果糖左温度")) {
                    myViewHolder.zdbs1.setVisibility(View.GONE);
                    myViewHolder.zdbs2.setVisibility(View.GONE);

                    myViewHolder.edittext_sx.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "60")});
                }else if (goodsMake.name.equals("果糖右温度")) {
                    myViewHolder.zdbs1.setVisibility(View.GONE);
                    myViewHolder.zdbs2.setVisibility(View.GONE);
                    myViewHolder.edittext_sx.setFilters(new InputFilter[]{ new InputFilterMinMax("0", "60")});
                }else if(goodsMake.name.contains("保温"))
                {
                    myViewHolder.zdbs1.setVisibility(View.GONE);
                    myViewHolder.zdbs2.setVisibility(View.GONE);
                    myViewHolder.show_wd.setVisibility(View.GONE);
                    myViewHolder.show_wdsz.setVisibility(View.GONE);
                    myViewHolder.save_value.setVisibility(View.GONE);
                }
                myViewHolder.temp.setText(goodsMake.temp+"");
                myViewHolder.control_switch.setChecked(goodsMake.autoheat);

                Handler mHandler = new Handler() {
                    public void handleMessage(Message msg) {
                        switch (msg.what) {
                            case 0:
                                if(goodsMake.name.equals("水池温度"))
                                {
                                    myViewHolder.temp.setText(ExecuteTheRecipe.WaterTemp+"");
                                } else if (goodsMake.name.equals("果糖左温度")) {
                                    myViewHolder.temp.setText(ExecuteTheRecipe.SugarTempLeft+"");
                                }else if (goodsMake.name.equals("果糖右温度")) {
                                    myViewHolder.temp.setText(ExecuteTheRecipe.SugarTempRight+"");
                                }
                                break;
                            case 1:

                                break;
                            case 2:

                                break;
                        }

                    }
                };
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        while (true) {
                            try {
                                mHandler.sendEmptyMessage(0);
                                Thread.sleep(200);
                            } catch (Exception ex) {
                                ToastUtils.error("异常信息:" + ex.getMessage());
                            }
                        }
                    }
                }).start();

                //
                myViewHolder.control_switch_bs.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                        //设置
                        ConfigName.getInstance().AutomaticWaterRefill=isChecked;
                        ConfigData.getInstance().SavePZ();
                        myViewHolder.zdbs3.setVisibility(ConfigName.getInstance().AutomaticWaterRefill==false?View.VISIBLE:View.GONE);
                        if(!isChecked) //关闭
                        {
                            ExecuteTheRecipe.WritePLC("水池进水阀",false,null);
                        }
                    }
                });

                myViewHolder.control_switch_ps.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                        //设置
                        if (ConfigName.getInstance().versionSelectionEnum.equals("配料吧台"))
                        {
                            if(isChecked) //关闭
                            {
                                ExecuteTheRecipe.WritePLC("水池排水阀-开",true,null);
                            }else
                            {
                                ExecuteTheRecipe.WritePLC("水池排水阀-关",false,null);
                            }
                        }else
                        {
                            if(isChecked) //关闭
                            {
                                ExecuteTheRecipe.WritePLC("水池排水阀-开",true,null);
                            }else
                            {
                                ExecuteTheRecipe.WritePLC("水池排水阀-关",true,null);
                            }
                        }
                    }
                });

                myViewHolder.control_switch.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                        //设置
                        goodsMake.autoheat=isChecked;
                        if(goodsMake.name.contains("保温"))
                        {
                            ExecuteTheRecipe.WritePLC(goodsMake.name,isChecked,null);
                        }else
                        {
                            if(goodsMake.name.equals("水池温度"))
                            {
                                ConfigName.getInstance().AutomaticHeating=goodsMake.autoheat;
                            } else if (goodsMake.name.equals("果糖左温度")) {
                                ConfigName.getInstance().GT1_AutomaticHeating=goodsMake.autoheat;
                            }else if (goodsMake.name.equals("果糖右温度")) {
                                ConfigName.getInstance().GT2_AutomaticHeating=goodsMake.autoheat;
                            }
                            ConfigData.getInstance().SavePZ();

                            if(!isChecked) //关闭加热
                            {
                                ExecuteTheRecipe.WritePLC(goodsMake.name+"加热",false,null);
                            }
                        }
                    }
                });

                myViewHolder.save_value.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int up = Integer.parseInt((myViewHolder.edittext_sx.getText().toString().isEmpty() ? "0" : myViewHolder.edittext_sx.getText().toString()));
                        if (up <= 0) {
                            ToastUtils.error("温度不能小于0!请调整后重试.");
                            return;
                        }

                        ExecuteTheRecipe.WritePLC(goodsMake.name + "设置", up, new IWriteCallBack() {
                            @Override
                            public void onSuccess() {
                                ToastUtils.info(goodsMake.name+"保存成功！");
                            }

                            @Override
                            public void onFailure(String ErrorMsg) {
                                ToastUtils.error(goodsMake.name+"保存失败！");
                            }
                        });

                        if(DataIs("延迟时间",myViewHolder.edittext_ycsj.getText().toString()))
                        {
                            ConfigName.getInstance().AutomaticWaterRefillTime=myViewHolder.edittext_ycsj.getText().toString();
                            ConfigData.getInstance().SavePZ();

                            int ftime = 0;
                            try {
                                ftime = (int) Math.round((Double.parseDouble(myViewHolder.edittext_ycsj.getText().toString()) * 10));
                            } catch (Exception e) {
                                ToastUtils.error("校准基准时间异常！" + e.getMessage());
                                return;
                            }
                            ExecuteTheRecipe.WritePLC("自动补水延迟时间", (short) ftime, null);
                            ToastUtils.info("保存成功！");
                        }
                    }
                });


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

    public boolean DataIs(String name,String data)
    {
        try
        {
            if(data==null || data.isEmpty())
            {
                ToastUtils.error(name+"不能为空！");
                return false;
            }

            Double.parseDouble(data);
            return true;
        }catch (Exception ex)
        {
            ToastUtils.error(name+"数据不合法！");
            return false;
        }
    }
    private Activity findActivity(@NonNull Context context) {
        if (context instanceof Activity) {
            return (Activity) context;
        } else if (context instanceof ContextWrapper) {
            return findActivity(((ContextWrapper) context).getBaseContext());
        } else {
            return null;
        }
    }
    /**
     * 刷新
     * @param
     */
    public void refresh(){
        Activity activity= findActivity(context);
        if(activity!=null)
        {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        notifyDataSetChanged();
                    } catch (Exception e) {

                    }
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return wdszModes.size();
    }

    public static class WDSZViewHolder extends RecyclerView.ViewHolder {
        /**
         * 名称
         */
        TextView name;
        /**
         * 温度上限
         */
        EditText edittext_sx,edittext_ycsj;
        /**
         * 当前温度
         */
        TextView temp;
        /**
         * 自动加热
         */
        SwitchButton control_switch,control_switch_bs,control_switch_ps;
        /**
         * 保存值
         */
        Button save_value;
        /**
         * 父容器
         */
        RelativeLayout root;

        RelativeLayout zdbs1,zdbs2,zdbs3,show_wdsz,show_wd;
        public WDSZViewHolder(View view) {
            super(view);
            name = (TextView) view.findViewById(R.id.name);
            edittext_sx=(EditText) view.findViewById(R.id.edittext_sx);
            edittext_ycsj=(EditText) view.findViewById(R.id.edittext_ycsj);
            temp = (TextView) view.findViewById(R.id.temp);
            control_switch = (SwitchButton)view.findViewById(R.id.control_switch);
            control_switch_bs= (SwitchButton)view.findViewById(R.id.control_switch_bs);
            control_switch_ps= (SwitchButton)view.findViewById(R.id.control_switch_ps);

            save_value=(Button) view.findViewById(R.id.save_value);

            zdbs1=view.findViewById(R.id.zdbs1);
            zdbs2=view.findViewById(R.id.zdbs2);
            zdbs3=view.findViewById(R.id.zdbs3);
            show_wdsz=view.findViewById(R.id.show_wdsz);
            show_wd=view.findViewById(R.id.show_wd);
        }
    }
}
