package com.bpa.scalage.pagefragment;

import android.app.AlertDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.bpa.scalage.R;

import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import com.bpa.scalage.config.ConfigName;
import com.bpa.scalage.HBL.Communication.RFIDHelper;
import com.bpa.scalage.helper.T;
import com.bpa.scalage.HBL.Communication.WeightHelper;
import com.pc_rfid.api.PC_API;
import com.pc_rfid.api.PC_COM;
import com.pc_rfid.api.RFdata;

import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 其他页面
 */
public class SystemDebugFragment extends Fragment {
    public SystemDebugFragment() {
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        MainView = inflater.inflate(R.layout.system_debug, container, false);
        Init();
        return MainView;
    }

    //region 界面变量
    //称重
    private Spinner Dishes_Com_Name,Dishes_Com_Port;
    //餐盘感应区
    private Spinner Plate_Com_Name,Plate_Com_Port,Plate_Com_Format;
    //当前界面
    private View MainView;
    private AppCompatActivity Appmain;
    //读卡区域 保存按钮
    private TextView system_open_cp,de_cp_ms,de_cp_data,system_set8n1;
    //称重区域 保存按钮
    private TextView system_open_cpgy,de_cpgy_ms,de_cpgy_data,clear_zl;
    private EditText de_receive;
    //endregion

    //region 串口调试变量
    private PC_API api=new PC_API();
    //刷卡器读取
    private static RFdata rFRead=new RFdata();
    private boolean mCartRunning = false;


private PC_COM mLztek=new PC_COM();
    private boolean mRunning = false;
    private ConcurrentLinkedQueue<Byte> cache = new ConcurrentLinkedQueue<>();
    //endregion

    //region 界面函数
    /**
     * 关闭函数
     */
    public void Close()
    {
        ClickEvent(0,false);
        ClickEvent(1,false);
    }

    /**
     * 初始化
     */
    public void Init()
    {
        Dishes_Com_Name=MainView.findViewById(R.id.de_cp_com);
        Dishes_Com_Port=MainView.findViewById(R.id.de_cp_port);
        system_open_cp=MainView.findViewById(R.id.system_open_cp);
        de_cp_ms=MainView.findViewById(R.id.de_cp_ms);
        de_cp_data=MainView.findViewById(R.id.de_cp_data);
        de_receive=MainView.findViewById(R.id.de_receive);

        Plate_Com_Name=MainView.findViewById(R.id.de_cpgy_com);
        Plate_Com_Port=MainView.findViewById(R.id.de_cpgy_port);
        Plate_Com_Format=MainView.findViewById(R.id.de_cpgy_jy);
        system_open_cpgy=MainView.findViewById(R.id.system_open_cpgy);
        de_cpgy_ms=MainView.findViewById(R.id.de_cpgy_ms);
        de_cpgy_data=MainView.findViewById(R.id.de_cpgy_data);
        clear_zl=MainView.findViewById(R.id.clear_zl);

        system_set8n1=MainView.findViewById(R.id.system_set8n1);

        //根据配置自动填充下拉项-选中文字
        SetShowText();

        //打开称重串口
        system_open_cp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(system_open_cp.getText().equals("打开串口"))
                {
                    ClickEvent(1,true);
                    if(mRunning)
                    {
                        system_open_cp.setText("关闭串口");
                        system_open_cp.setBackground(getResources().getDrawable(R.drawable.selector_red_corners_start_button));
                    }

                }else
                {
                    system_open_cp.setText("打开串口");
                    system_open_cp.setBackground(getResources().getDrawable(R.drawable.selector_renren_blue_button));
                    ClickEvent(1,false);
                }
            }
        });


        system_set8n1.setOnClickListener((view)->{
            RFIDHelper.set8N1();
        });

        //打开读卡串口
        system_open_cpgy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(system_open_cpgy.getText().equals("打开串口"))
                {
                    ClickEvent(0,true);
                    if(mCartRunning)
                    {
                        system_open_cpgy.setText("关闭串口");
                        system_open_cpgy.setBackground(getResources().getDrawable(R.drawable.selector_red_corners_start_button));
                    }
                }else
                {
                    system_open_cpgy.setText("打开串口");
                    system_open_cpgy.setBackground(getResources().getDrawable(R.drawable.selector_renren_blue_button));
                    ClickEvent(0,false);
                }
            }
        });

        //清除重量
        clear_zl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                WeightHelper.ZeroClear();
            }
        });
    }
    /**
     * 设置界面显示
     */
    public void SetShowText()
    {
        SelectText(Dishes_Com_Name,ConfigName.getInstance().Dishes_Com_Name);
        SelectText(Dishes_Com_Port, Integer.toString(ConfigName.getInstance().Dishes_Com_Port));
        SelectText(Plate_Com_Name,ConfigName.getInstance().Plate_Com_Name);
        SelectText(Plate_Com_Port, Integer.toString(ConfigName.getInstance().Plate_Com_Port));
        SelectText(Plate_Com_Format,ConfigName.getInstance().Plate_Com_Format);
    }

    /**
     * 设置主窗体
     * @param activity
     */
    public void SetMainView(AppCompatActivity activity)
    {
            Appmain=activity;
    }

    /**
     * 选中下拉框
     * @param spinner
     * @param value
     */
    public void SelectText(Spinner spinner,String value)
    {
        SpinnerAdapter apsAdapter= spinner.getAdapter(); //得到SpinnerAdapter对象
        int k= apsAdapter.getCount();
        for(int i=0;i<k;i++){

            if(value.equals(apsAdapter.getItem(i).toString())){
                spinner.setSelection(i,true);// 默认选中项
                break;
            }
        }
    }
    //endregion

    //region 外部调用函数

    /**
     * 根据点击事件完成操作
     * @param i 0 读卡设备 1 称重设备
     * @param b 打开或者关闭
     */
    public void ClickEvent(int i,boolean b)
    {
        switch (i)
        {
            case 0:
                //读卡设备
                if(b)
                {
                    String com=Plate_Com_Name.getSelectedItem().toString();
                    int baud= Integer.valueOf(Plate_Com_Port.getSelectedItem().toString()).intValue();
                    String format =  Plate_Com_Format.getSelectedItem().toString();
                    RFIDHelper.Open(com,baud,format).OnSource(()->{
                        mCartRunning=true;
                        T.show(MainView.getContext(), "打开读卡Cart串口成功!");
                        SetcpMsIck();
                        RFIDHelper.DataUpdate=(s)->{
                            Appmain.runOnUiThread(()->{de_cpgy_data.setText(s);});
                        };
                    }).OnFailed(()->{
                        mCartRunning=false;
                        T.show(MainView.getContext(), "打开读卡Cart串口失败!");
                        SetcpMsIck();
                    });
                }else
                {
                    if(mCartRunning)
                    {
                        mCartRunning=false;
                        RFIDHelper.Close(()->{ SetcpMsIck(); });
                    }
                }
                break;
            case 1:
                //称重设备
                if(b)
                {
                    String com=Dishes_Com_Name.getSelectedItem().toString();
                    int baud= Integer.valueOf(Dishes_Com_Port.getSelectedItem().toString()).intValue();
                    WeightHelper.Open(com,baud,"8N1").OnSource(()->{
                        mRunning = true;
                        WeightHelper.DataUpdate=weight->{
                            Appmain.runOnUiThread(()->{de_cp_data.setText(String.valueOf(weight)+" g");});
                        };
                        T.show(Appmain, "称重模块正在运行!");
                    }).OnFailed(()->{
                        String message = ConfigName.getInstance().Dishes_Com_Name + "[" + ConfigName.getInstance().Dishes_Com_Port + "]" + ", " + ConfigName.getInstance().Dishes_Com_Port + "端口打开失败";
                        AlertDialog.Builder builder = new AlertDialog.Builder(Appmain);
                        builder.setTitle("错误");
                        builder.setMessage(message);
                        builder.setNegativeButton("确定", null);
                        builder.create();
                        builder.show();
                        mRunning = false;
                    });
                    SetcpMsCz();

                }else
                {
                    if(mRunning) {
                        mRunning=false;
                        WeightHelper.Close(()->{
                            SetcpMsCz();
                        });
                    }
                }
                break;
        }
    }

    /**
     * 设置描述显示
     */
    public void SetcpMsIck()
    {
        Appmain.runOnUiThread(()->{
            if(mCartRunning)
            {
                de_cpgy_ms.setText("正在运行");
                de_cpgy_ms.setTextColor(getResources().getColor(R.color.green_weixin));
            }else
            {
                de_cpgy_ms.setText("关闭状态");
                de_cpgy_ms.setTextColor(getResources().getColor(R.color.blue));
            }
            de_cpgy_data.setText("");
        });
    }

    /**
     * 设置描述显示
     */
    public void SetcpMsCz()
    {
        Appmain.runOnUiThread(()->{
            if(mRunning)
            {
                de_cp_ms.setText("正在运行");
                de_cp_ms.setTextColor(getResources().getColor(R.color.green_weixin));
            }else
            {
                de_cp_ms.setText("关闭状态");
                de_cp_ms.setTextColor(getResources().getColor(R.color.blue));
            }
            de_cp_data.setText("");
        });
    }
    //endregion

}