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

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.bonait.bnframework.R;
import com.bonait.bnframework.business.ConfigData;
import com.bonait.bnframework.business.ExecuteTheRecipe;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_GOODSTYPE;
import com.bonait.bnframework.common.db.mode.BPA_SILOS;
import com.bonait.bnframework.common.helper.I.MyClickListener;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class add_yijian_controlextends extends LinearLayout {


    @BindView(R.id.quzhizuo)
    Button quzhizuo; //点击按钮

    @BindView(R.id.close_from_good)
    Button close_from_good;//关闭按钮

    @BindView(R.id.image_gz)
    ImageButtonControl image_gz;//显示的image控件

    @BindView(R.id.miaoshutext)
    TextView miaoshutext;//描述文本

    @BindView(R.id.jishiqi)
    RelativeLayout jishiqi;//计时器
    @BindView(R.id.miaoshu)
    RelativeLayout miaoshu;//描述

    @BindView(R.id.liaochang)
    LinearLayout liaochang;//描述
    @BindView(R.id.runtime)
    Chronometer runtime;



    @BindView(R.id.editsp_fl)
    Spinner editsp_fl;

    @BindView(R.id.edittext1)
    EditText edittext1;

    @BindView(R.id.edittext2)
    EditText edittext2;
    public ArrayList<BPA_SILOS> siloslist=new ArrayList<>();
    /**
     * 点击事件
     */
    public MyClickListener mListener = null;
    private View root;

    private Context contextMian;

    public add_yijian_controlextends(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        contextMian=context;
        root = LayoutInflater.from(context).inflate(R.layout.dialog_add_yijian, this);
        ButterKnife.bind(this, root);
        Init();
    }


    public void Init() {
        //初始化界面控件的事件
        initEvent();
    }
     public  int zongliang=0;
    Map<String,String> map_fl = new LinkedHashMap<>();
    private void initData() {
        //2.填充规则数据，查询所有属性大类
        siloslist= QueryDB.GetSilosALL();


        zongliang=0;
        for (BPA_SILOS item:siloslist) {
            if (!item.name.equals("果糖仓") && !item.name.equals("粉料仓"))
            {
                zongliang++;
            }
        }
        switch (ShowType)
        {
            case 1://一键满管
                image_gz.SetShowImage(R.mipmap.silos1);
                miaoshutext.setText("请将桶放置出料口后执行该操作,此操作将会全仓满管");
                quzhizuo.setText("一键满管");
                jishiqi.setVisibility(View.GONE);
                image_gz.setVisibility(View.VISIBLE);
                liaochang.setVisibility(View.GONE);
                miaoshu.setVisibility(View.VISIBLE);
                break;
            case 2://一键加满
                image_gz.SetShowImage(R.mipmap.silos2);
                miaoshutext.setText("一键加满操作，请确认所有原料补充完毕后点击此操作");
                quzhizuo.setText("一键加满所有通道");
                jishiqi.setVisibility(View.GONE);
                image_gz.setVisibility(View.VISIBLE);
                liaochang.setVisibility(View.GONE);
                miaoshu.setVisibility(View.VISIBLE);
                break;
            case 3://一键清洗
                image_gz.SetShowImage(R.mipmap.silos3);
                miaoshutext.setText("此操作会清洗管道和料仓，请确认清洗");
                quzhizuo.setText("一键清洗");
                jishiqi.setVisibility(View.GONE);
                image_gz.setVisibility(View.VISIBLE);
                liaochang.setVisibility(View.GONE);
                miaoshu.setVisibility(View.VISIBLE);

                break;
            case 4://一键设置
                image_gz.setVisibility(View.GONE);
                image_gz.SetShowImage(R.mipmap.silos4);
                miaoshutext.setText("");
                quzhizuo.setText("一键设置所有通道");
                jishiqi.setVisibility(View.GONE);
                liaochang.setVisibility(View.VISIBLE);
                miaoshu.setVisibility(View.GONE);
                //设置仓
                map_fl.clear();
                BPA_SILOS name=null;
                for (BPA_SILOS item:siloslist)
                {
                    if(!map_fl.containsKey(item.name))
                    {
                        map_fl.put(item.name,item.id);
                        if(name==null)
                        {
                            name=item;
                        }
                    }
                }

                if(name!=null)
                {
                    edittext1.setText(name.siloszl+"");
                    edittext2.setText(name.warningValue+"");
                }
                SetAdapter(editsp_fl,map_fl);
                break;
        }
    }
    public void SetAdapter(Spinner spinner, Map<String,String> map)
    {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(getContext(), R.layout.spinner_text_item, new ArrayList<>(map.keySet()));
        adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        spinner.setAdapter(adapter);
    }
    /**
     * 1 一键满管
     * 2 一键加满
     * 3 一键清洗
     * 4 一键设置
     */
    public int ShowType=1;
    /**
     * 设置数据
     *
     * @param
     */
    public void SetData(int type) {
        try {
            ShowType=type;
            initData();
        } catch (Exception ex) {

        }
    }


    private void initEvent() {
        quzhizuo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SaveData();
                if (mListener != null) {
                    mListener.clickListenerNew(view, ShowType, null);
                }
            }
        });
        close_from_good.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mListener != null) {
                    mListener.clickListenerNew(v, 0, null);
                }
            }
        });

        //为Chronomter绑定事件监听器,超过一小时自动日内告知
        runtime.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
            @Override
            public void onChronometerTick(Chronometer chronometer) {
                //如果计时到现在超过了一小时秒 10s
                if (SystemClock.elapsedRealtime() - runtime.getBase() > 120 * 1000) {
                    StopTime();
                }
            }
        });
        editsp_fl.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String type= editsp_fl.getSelectedItem().toString();
                BPA_SILOS name=null;
                for (BPA_SILOS item:siloslist)
                {
                    if(name==null && item.name.equals(type))
                    {
                        name=item;
                    }
                }

                if(name!=null)
                {
                    edittext1.setText(name.siloszl+"");
                    edittext2.setText(name.warningValue+"");
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    if(i>=zongliang)
                    {
                        StopTime();
                        ToastUtils.info("料仓满管完成！");
                    }
                    break;
                case 1:

                    break;
                case 2:

                    break;
            }

        }
    };



    //region 计时器操作
    int i=0;
    /**
     * 保存数据
     */
    public void SaveData() {
        switch (ShowType)
        {
            case 1://一键满管
                i=0;
                ToastUtils.info("料仓满管开始！");
                StartTime();
                ExecuteTheRecipe.WritePLC("手自切换", false, null);
                for (BPA_SILOS item:siloslist)
                {
                    if(!item.name.equals("果糖仓") &&  !item.name.equals("粉料仓") )
                    {
                        int time=item.bValue<=0?5:item.bValue;//默认5秒
                        ExecuteTheRecipe.WritePLC("手动控制"+item.num,true,null);
                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                ExecuteTheRecipe.WritePLC("手动控制"+item.num,false,null);
                                mHandler.sendEmptyMessage(0);
                                i++;
                            }
                        }, time * 1000);
                    }
                }
                break;
            case 2://一键加满
                for (BPA_SILOS item:siloslist)
                {
                    QueryDB.UpdateYL(item.id,item.siloszl);
                }

                ToastUtils.info("料仓加满完成！");
                break;
            case 3://一键清洗
                ToastUtils.info("功能开发中...");
                break;
            case 4://一键设置
                String type= editsp_fl.getSelectedItem().toString();
                String zl= edittext1.getText().toString();
                if(zl==null || zl.isEmpty())
                {
                    ToastUtils.warning("料仓容量不能为空!");
                    return;
                }
                String bjz= edittext2.getText().toString();
                if(bjz==null || bjz.isEmpty())
                {
                    ToastUtils.warning("报警值不能为空!");
                    return;
                }

                int zl_int=0;
                int bj_int=0;

                try {
                    zl_int=Integer.parseInt(zl);
                    bj_int=Integer.parseInt(bjz);
                }catch (Exception ex)
                {

                }

                if(bj_int>zl_int)
                {
                    ToastUtils.warning("报警值不能大于料仓容量!");
                    return;
                }

                for (BPA_SILOS item:siloslist)
                {
                    if(item.name.equals(type))
                    {
                        QueryDB.UpdateSilosZL(item.id,zl_int);
                        QueryDB.UpdateSilosBJZ(item.id,bj_int);
                    }
                }
                ToastUtils.info("一键设置完成！");
                break;
        }


    }


    /**
     * 启动定时器
     */
    public void StartTime() {
        jishiqi.setVisibility(View.VISIBLE);
        miaoshu.setVisibility(View.GONE);
        runtime.setBase(SystemClock.elapsedRealtime());
        runtime.start();
    }

    /**
     * 停止定时器
     */
    public int StopTime() {
        jishiqi.setVisibility(View.GONE);
        miaoshu.setVisibility(View.VISIBLE);
        long elapsedMillis = SystemClock.elapsedRealtime() - runtime.getBase();
        runtime.stop();
        int time=(int) (elapsedMillis / 1000);
        return  time;//当前点击多少秒
    }
    //endregion

    public void destroy(){
        if(mHandler!=null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        siloslist.clear();
        siloslist = null;
        mListener = null;
        map_fl.clear();
        map_fl = null;
        editsp_fl = null;
    }
}