package com.bpa.scalage.pagefragment;

import android.app.AlertDialog;
import android.os.Bundle;
import android.util.Log;
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.MainActivity;
import com.bpa.scalage.R;

import android.os.Bundle;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.SpinnerAdapter;
import android.widget.TextView;

import androidx.annotation.Nullable;
        import androidx.fragment.app.Fragment;
        import com.bpa.scalage.R;
import com.bpa.scalage.config.ConfigName;
import com.bpa.scalage.data.DataBus;
import com.bpa.scalage.helper.ByteHelper;
import com.bpa.scalage.helper.T;
import com.bpa.scalage.message.MessageManager;
import com.lztek.toolkit.SerialPort;
import com.pc_rfid.api.PC_API;
import com.pc_rfid.api.PC_COMM;
import com.pc_rfid.api.RFdata;

import java.io.OutputStream;
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;
    //称重区域 保存按钮
    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 com.lztek.toolkit.Lztek mLztek;
    private SerialPort mSerialPort;
    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);
        //根据配置自动填充下拉项-选中文字
        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_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) {
                WriteData();
            }
        });
    }
    /**
     * 设置界面显示
     */
    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;
        mLztek = com.lztek.toolkit.Lztek.create(Appmain);
    }

    /**
     * 选中下拉框
     * @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)
                {
                    if(api.PC_OpenCOM(Plate_Com_Name.getSelectedItem().toString(),
                            Integer.valueOf(Plate_Com_Port.getSelectedItem().toString()).intValue(),
                            Plate_Com_Format.getSelectedItem().toString())){
                        api.PC_OpenDevice(rFRead);
                        if(api.PC_OpenAnt_One(rFRead, (byte) 1))
                        {
                            mCartRunning=true;
                            rFRead.clear();
                            T.show(MainView.getContext(), "打开读卡Cart串口成功!");
                            SetcpMsIck();
                        }else
                            T.show(MainView.getContext(), "打开读卡Cart串口失败!");
                    }else
                    {
                        mCartRunning=false;
                        T.show(MainView.getContext(), "打开读卡Cart串口失败!");
                        SetcpMsIck();
                    }
                    ReadCraK();
                }else
                {
                    if(mCartRunning)
                    {
                        mCartRunning=false;
                        api.PC_Close();
                    }
                    SetcpMsIck();
                    de_cpgy_data.setText("");
                }
                break;
            case 1:
                //称重设备
                if(b)
                {
                    if (null == (mSerialPort = mLztek.openSerialPort(
                            Dishes_Com_Name.getSelectedItem().toString(),
                            Integer.valueOf(Dishes_Com_Port.getSelectedItem().toString()).intValue(), 8, 0, 1, 0))) {
                        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;
                    } else {
                        mRunning = true;
                        runRead();
                        processData();
                        T.show(Appmain, "称重模块正在运行!");
                    }
                    SetcpMsCz();
                }else
                {
                    if(mRunning)
                    {
                        mRunning=false;
                        mSerialPort.close();
                    }
                    SetcpMsCz();
                    de_cp_data.setText("");
                }
                break;
        }
    }

    /**
     * 设置描述显示
     */
    public void SetcpMsIck()
    {
        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));
        }
    }

    /**
     * 设置描述显示
     */
    public void SetcpMsCz()
    {
        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));
        }
    }
    //endregion

    //region 循环读卡流程
    private void ReadCraK()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mCartRunning) {
                    try {
                        Appmain.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if(mCartRunning)
                                {
                                    String CartHao="";
                                    api.PC_InventoryTag(rFRead,(byte)4);//循环读取卡片信息
                                    String Value=rFRead.getReceiveData();
                                    if(Value.length()==51)
                                    {
                                        try
                                        {
                                            CartHao= Value.replace(" ","").substring(14, 30);
                                        } catch (Exception e) {
                                            throw new RuntimeException(e);
                                        }
                                    }
                                    de_cpgy_data.setText(CartHao);
                                }
                            }
                        });
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }
    //endregion

    //region 称重数据处理

    /**
     * 清零
     */
    public void WriteData()
    {
        if(mSerialPort!=null)
        {
            OutputStream mOutputStream = mSerialPort.getOutputStream();
            byte[] bytes=new byte[5];//字符转成byte数组
            bytes[0] = 0x01;
            bytes[1] = 0x03;
            bytes[2] = 0x54;
            bytes[3] = 0x21;
            bytes[4] = 0x0f;
            try {
                mOutputStream.write(bytes);//通过输出流写入数据
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 串口处理函数
     */
    private void runRead() {
        if (null == mSerialPort) {
            mRunning = false;
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (mRunning) {
                    final byte[] data = null != mSerialPort ? read() : null;
                    if (null == data) continue;
                    for (int i = 0; i < data.length; i++)
                        cache.add(data[i]);
                    try {
                        Thread.sleep(50);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }).start();
    }

    private byte[] read() {
        if (null == mSerialPort) {
            return null;
        }

        java.io.InputStream input = null;
        try {
            input = mSerialPort.getInputStream();
            byte[] buffer = new byte[1024];
            int len = input.read(buffer);
            return len > 0 ? java.util.Arrays.copyOfRange(buffer, 0, len) : null;
        } catch (Exception e) {
            android.util.Log.d("#ERROR#", "[COM]Read Faild: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 数据解析函数
     */
    private void processData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                byte[] temp = new byte[12];
                while (mRunning) {
                    while (cache.size() >= 12) {
                        byte flag = cache.poll();
                        if (flag != 0x01) continue;
                        byte cmd = cache.poll();
                        if (cmd != 0x03) continue;
                        temp[0] = 0x01;
                        temp[1] = 0x03;
                        for (int i = 2; i < 12; i++) {
                            temp[i] = cache.poll();
                        }
                        //  01 03 2B 30 30 31 2E 30 30 30 23 9D
                        //模块功能  +  0  0  1  .  0  0  0  校验
                        //1KG显示+001.000ASCII代码编写
                        //+代表2B -2E
                        //0代表30
                        //1代表31
                        //.小数点代表2E

                        //取前10位 计算校验码
                        byte[] validateTemp = new byte[10];
                        System.arraycopy(temp, 0, validateTemp, 0, 10);
                        int res = ByteHelper.getCRC2(validateTemp);
                        //取后两位校验码
                        byte[] rawCode = new byte[4];
                        System.arraycopy(temp, 10, rawCode, 2, 2);
                        int raw = ByteHelper.byteToInt(rawCode);
                        if (raw == res) //校验成功
                        {
                            //+001.000 heavy[2]==0x2B
                            final byte[] heavy = new byte[7];
                            System.arraycopy(temp, 3, heavy, 0, 7);
                            String text = new String(heavy);
                            int zl=0;
                            if(temp[2]==0x2B)//如果是正数
                            {
                                int k= (int) (Double.parseDouble(text)*1000);
                                zl=k;
                            }
                            final int finalZl = zl;
                            Appmain.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    de_cp_data.setText(String.valueOf(finalZl));
                                }
                            });
                        }
                    }
                }
            }
        }).start();
    }
    //endregion
}