package com.example.displaydemo;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.annotation.ColorInt;

import com.example.displaydemo.base.BaseActivity;
import com.example.displaydemo.utils.ToastUtils;
import com.jrummyapps.android.colorpicker.ColorPanelView;
import com.jrummyapps.android.colorpicker.ColorPickerDialog;
import com.jrummyapps.android.colorpicker.ColorPickerDialogListener;
import com.pavolibrary.commands.Constant;
import com.pavolibrary.commands.DspAPI;
import com.pavolibrary.utils.FileChooseUtils;
import com.pavolibrary.utils.LogUtils;
import com.serialport.api.SerialPortFinder;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;


public class PD500Activity extends BaseActivity implements View.OnClickListener, DspAPI.UploadListener {
    private static final String TAG = "PD500Activity";

    private static final int REQUEST_CHOOSEFILE = 1;

    private Button btn_display;
    private Button btn_display_upperlinescroll;
    private Button btn_display_at;
    private Button btn_restart;
    private Button btn_restore;
    private Button btn_init;
    private Button btn_setlines;
    private Button btn_setbrightness;
    private Button btn_setcommand;
    private Button btn_setcharset;
    private Button btn_setcodepage;
    private Button btn_clearline;
    private Button btn_clearscreen;
    private Button btn_cursorleft;
    private Button btn_cursorright;
    private Button btn_cursordown;
    private Button btn_cursorup;
    private Button btn_cursorendleft;
    private Button btn_cursorendright;
    private Button btn_cursorhome;
    private Button btn_cursorend;
    private Button btn_movecursor;

    private Button btn_setwelmessage;
    private Button btn_setcolor_header;
    private Button btn_setcolor_footer;
    private Button btn_setcolor_central;

    private Button btn_setdisplaystyle;
    private Button btn_setheadertype;
    private Button btn_setbodydefaulttext;

    private Button btn_qrcode;
    private Button btn_qrcodeonpicture;
    private Button btn_uploadpicture;
    private Button btn_selectpicture;
    private Button btn_setplayed;

    private Button btn_showpicture_1;
    private Button btn_showpicture_2;
    private Button btn_showpicture_3;
    private Button btn_showpicture_4;
    private Button btn_showpicture_5;
    private Button btn_showpicture_6;
    private Button btn_showpicture_7;
    private Button btn_showpicture_8;
    private Button btn_showpicture_9;
    private Button btn_showpicture_10;

    private Button btn_setinterval;
    private Button btn_setstandby;

    private Button btn_connect;
    private Button btn_back;

    private Spinner sp_port;
    private Spinner sp_baudrate;
    private Spinner sp_headertype;
    private Spinner sp_displaystyle;
    private Spinner sp_lines;
    private Spinner sp_row;
    private Spinner sp_column;
    private Spinner sp_alignX;
    private Spinner sp_alignY;
    private Spinner sp_alignX_on;
    private Spinner sp_picno;

    private Spinner sp_row_display;
    private Spinner sp_column_display;
    private Spinner sp_brightness;
    private Spinner sp_commands;
    private Spinner sp_charset;
    private Spinner sp_codepage;
    private Spinner sp_picturename;
    private Spinner sp_interval;
    private Spinner sp_standby;

    private CheckBox cb_line2_scroll;

    private CheckBox cb_picture_1;
    private CheckBox cb_picture_2;
    private CheckBox cb_picture_3;
    private CheckBox cb_picture_4;
    private CheckBox cb_picture_5;
    private CheckBox cb_picture_6;
    private CheckBox cb_picture_7;
    private CheckBox cb_picture_8;
    private CheckBox cb_picture_9;
    private CheckBox cb_picture_10;

    private EditText edt_text;
    private EditText edt_welmessage_1;
    private EditText edt_welmessage_2;

    private EditText edt_bodydefaulttext_1;
    private EditText edt_bodydefaulttext_2;
    private EditText edt_bodydefaulttext_3;
    private EditText edt_bodydefaulttext_4;

    private TextView tv_picturefilename;
    private TextView tv_model;
    private TextView tv_firmwareVersion;

    private ColorPanelView color_text_header;
    private ColorPanelView color_text_footer;
    private ColorPanelView color_text_central;
    private ColorPanelView color_background_header;
    private ColorPanelView color_background_footer;
    private ColorPanelView color_background_central;

    private SerialPortFinder mSerialPortFinder;

    private DspAPI mDsp;

    private String serialPort = "USB";  //定义串口号
    private int serialBaudrate = 9600;  //定义波特率
    private int serialFlag = 0;

    private Runnable runnable;
    private ProgressDialog progressDialog;

    @Override
    public int getContentViewId() {
        return R.layout.activity_pd500;
    }

    @Override
    public void initView() {
        btn_display = findViewById(R.id.btn_display);
        btn_display_upperlinescroll = findViewById(R.id.btn_display_upperlinescroll);
        btn_display_at = findViewById(R.id.btn_display_at);
        btn_restart = findViewById(R.id.btn_restart);
        btn_restore = findViewById(R.id.btn_restore);
        btn_init = findViewById(R.id.btn_init);
        btn_clearline = findViewById(R.id.btn_clearline);
        btn_clearscreen = findViewById(R.id.btn_clearscreen);
        btn_cursorleft = findViewById(R.id.btn_cursorleft);
        btn_cursorright = findViewById(R.id.btn_cursorright);
        btn_cursordown = findViewById(R.id.btn_cursordown);
        btn_cursorup = findViewById(R.id.btn_cursorup);
        btn_cursorendleft = findViewById(R.id.btn_cursorendleft);
        btn_cursorendright = findViewById(R.id.btn_cursorendright);
        btn_cursorhome = findViewById(R.id.btn_cursorhome);
        btn_cursorend = findViewById(R.id.btn_cursorend);
        btn_movecursor = findViewById(R.id.btn_movecursor);
        btn_setlines = findViewById(R.id.btn_setlines);
        btn_setbrightness = findViewById(R.id.btn_SetBrightness);
        btn_setcommand = findViewById(R.id.btn_SetCommand);
        btn_setcharset = findViewById(R.id.btn_setcharset);
        btn_setcodepage = findViewById(R.id.btn_setcodepage);

        btn_setwelmessage = findViewById(R.id.btn_setwelmessage);
        btn_setcolor_header = findViewById(R.id.btn_setcolor_header);
        btn_setcolor_footer = findViewById(R.id.btn_setcolor_footer);
        btn_setcolor_central = findViewById(R.id.btn_setcolor_central);

        btn_setdisplaystyle = findViewById(R.id.btn_setdisplaystyle);
        btn_setheadertype = findViewById(R.id.btn_setheadertype);
        btn_setbodydefaulttext = findViewById(R.id.btn_setbodydefaulttext);

        btn_qrcode = findViewById(R.id.btn_qrCode);
        btn_qrcodeonpicture = findViewById(R.id.btn_qrCodeOnPicture);

        btn_uploadpicture = findViewById(R.id.btn_uploadpicture);
        btn_selectpicture = findViewById(R.id.btn_selectpicture);
        btn_setplayed = findViewById(R.id.btn_setplayed);
        btn_showpicture_1 = findViewById(R.id.btn_showpicture_1);
        btn_showpicture_2 = findViewById(R.id.btn_showpicture_2);
        btn_showpicture_3 = findViewById(R.id.btn_showpicture_3);
        btn_showpicture_4 = findViewById(R.id.btn_showpicture_4);
        btn_showpicture_5 = findViewById(R.id.btn_showpicture_5);
        btn_showpicture_6 = findViewById(R.id.btn_showpicture_6);
        btn_showpicture_7 = findViewById(R.id.btn_showpicture_7);
        btn_showpicture_8 = findViewById(R.id.btn_showpicture_8);
        btn_showpicture_9 = findViewById(R.id.btn_showpicture_9);
        btn_showpicture_10 = findViewById(R.id.btn_showpicture_10);
        btn_setinterval = findViewById(R.id.btn_SetPlayInterval);
        btn_setstandby = findViewById(R.id.btn_SetPlayStandBy);

        btn_connect = findViewById(R.id.btn_connect);
        btn_back = findViewById(R.id.btn_back);

        cb_line2_scroll = findViewById(R.id.cb_line2_scroll);

        cb_picture_1 = findViewById(R.id.cb_picture1);
        cb_picture_2 = findViewById(R.id.cb_picture2);
        cb_picture_3 = findViewById(R.id.cb_picture3);
        cb_picture_4 = findViewById(R.id.cb_picture4);
        cb_picture_5 = findViewById(R.id.cb_picture5);
        cb_picture_6 = findViewById(R.id.cb_picture6);
        cb_picture_7 = findViewById(R.id.cb_picture7);
        cb_picture_8 = findViewById(R.id.cb_picture8);
        cb_picture_9 = findViewById(R.id.cb_picture9);
        cb_picture_10 = findViewById(R.id.cb_picture10);

        sp_headertype = findViewById(R.id.spinner_headertype);
        sp_displaystyle = findViewById(R.id.spinner_displaystyle);
        sp_lines = findViewById(R.id.spinner_lines);
        sp_row = findViewById(R.id.spinner_row);
        sp_column = findViewById(R.id.spinner_column);
        sp_row_display = findViewById(R.id.spinner_row_display);
        sp_column_display = findViewById(R.id.spinner_column_display);
        sp_alignX = findViewById(R.id.spinner_alignX);
        sp_alignY = findViewById(R.id.spinner_alignY);
        sp_alignX_on = findViewById(R.id.spinner_alignX_On);
        sp_picno = findViewById(R.id.spinner_picNo);
        sp_picturename = findViewById(R.id.spinner_picturename);
        sp_brightness = findViewById(R.id.spinner_Brightness);
        sp_commands = findViewById(R.id.spinner_Commands);
        sp_charset = findViewById(R.id.spinner_charset);
        sp_codepage = findViewById(R.id.spinner_codepage);
        sp_interval = findViewById(R.id.spinner_interval);
        sp_standby = findViewById(R.id.spinner_standby);

        edt_text = findViewById(R.id.edt_text);
        edt_welmessage_1 = findViewById(R.id.edt_welmessage_1);
        edt_welmessage_2 = findViewById(R.id.edt_welmessage_2);

        edt_bodydefaulttext_1 = findViewById(R.id.edt_bodydefaulttext_1);
        edt_bodydefaulttext_2 = findViewById(R.id.edt_bodydefaulttext_2);
        edt_bodydefaulttext_3 = findViewById(R.id.edt_bodydefaulttext_3);
        edt_bodydefaulttext_4 = findViewById(R.id.edt_bodydefaulttext_4);

        tv_picturefilename = findViewById(R.id.textPictureFileName);
        tv_model = findViewById(R.id.textModel);
        tv_firmwareVersion = findViewById(R.id.textFirmwareVersion);

        sp_port = findViewById(R.id.spinner_port);
        sp_baudrate = findViewById(R.id.spinner_baudrate);

        color_text_header = findViewById(R.id.cpv_color_text_header);
        color_text_footer = findViewById(R.id.cpv_color_text_footer);
        color_text_central = findViewById(R.id.cpv_color_text_central);
        color_background_header = findViewById(R.id.cpv_color_background_header);
        color_background_footer = findViewById(R.id.cpv_color_background_footer);
        color_background_central = findViewById(R.id.cpv_color_background_central);

        //serial port list
        mSerialPortFinder = new SerialPortFinder();
        String[] entryValues = mSerialPortFinder.getAllDevicesPath();
        List<String> allDevices = new ArrayList<String>();
        allDevices.add("USB");
        for (int i = 0; i < entryValues.length; i++) {
            allDevices.add(entryValues[i]);
        }
        ArrayAdapter<String> aspnDevices = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allDevices);
        aspnDevices.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_port.setAdapter(aspnDevices);

        //charset list
        List<String> allCharset_names = new ArrayList<String>();
        for (int i = 0; i < Constant.international_name.length; i++) {
            allCharset_names.add(Constant.international_name[i]);
        }
        ArrayAdapter<String> aspnCharset_names = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allCharset_names);
        aspnCharset_names.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_charset.setAdapter(aspnCharset_names);

        //code page list
        List<String> allCodepage_names = new ArrayList<String>();
        for (int i = 0; i < Constant.codepage_name.length; i++) {
            allCodepage_names.add(Constant.codepage_name[i]);
        }
        ArrayAdapter<String> aspnCodepage_names = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allCodepage_names);
        aspnCodepage_names.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_codepage.setAdapter(aspnCodepage_names);

        //picture list
        List<String> allPicture_names = new ArrayList<String>();
        for (int i = 0; i < Constant.picture_name.length; i++) {
            allPicture_names.add(Constant.picture_name[i]);
        }
        ArrayAdapter<String> aspnPicture_names = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, allPicture_names);
        aspnPicture_names.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        sp_picturename.setAdapter(aspnPicture_names);

        //command default Epson
        sp_commands.setSelection(1);

        color_text_header.setColor(Color.WHITE);
        color_background_header.setColor(Color.BLUE);
        color_text_footer.setColor(Color.BLUE);
        color_background_footer.setColor(Color.WHITE);
        color_text_central.setColor(Color.parseColor("#00FCF8"));
        color_background_central.setColor(Color.BLACK);
    }

    @Override
    public void initData() {
        mDsp = new DspAPI(this);

        btn_display.setEnabled(false);
        btn_display_upperlinescroll.setEnabled(false);
        btn_display_at.setEnabled(false);
        btn_restart.setEnabled(false);
        btn_restore.setEnabled(false);
        btn_init.setEnabled(false);
        btn_clearline.setEnabled(false);
        btn_clearscreen.setEnabled(false);
        btn_cursorleft.setEnabled(false);
        btn_cursorright.setEnabled(false);
        btn_cursordown.setEnabled(false);
        btn_cursorup.setEnabled(false);
        btn_cursorendleft.setEnabled(false);
        btn_cursorendright.setEnabled(false);
        btn_cursorhome.setEnabled(false);
        btn_cursorend.setEnabled(false);
        btn_movecursor.setEnabled(false);

        btn_setwelmessage.setEnabled(false);
        btn_setcolor_header.setEnabled(false);
        btn_setcolor_footer.setEnabled(false);
        btn_setcolor_central.setEnabled(false);

        btn_setdisplaystyle.setEnabled(false);
        btn_setheadertype.setEnabled(false);
        btn_setbodydefaulttext.setEnabled(false);

        btn_qrcode.setEnabled(false);
        btn_qrcodeonpicture.setEnabled(false);

        btn_setlines.setEnabled(false);
        btn_setbrightness.setEnabled(false);
        btn_setcommand.setEnabled(false);
        btn_setcharset.setEnabled(false);
        btn_setcodepage.setEnabled(false);
        btn_uploadpicture.setEnabled(false);
        btn_selectpicture.setEnabled(false);
        btn_setplayed.setEnabled(false);
        btn_showpicture_1.setEnabled(false);
        btn_showpicture_2.setEnabled(false);
        btn_showpicture_3.setEnabled(false);
        btn_showpicture_4.setEnabled(false);
        btn_showpicture_5.setEnabled(false);
        btn_showpicture_6.setEnabled(false);
        btn_showpicture_7.setEnabled(false);
        btn_showpicture_8.setEnabled(false);
        btn_showpicture_9.setEnabled(false);
        btn_showpicture_10.setEnabled(false);
        btn_setinterval.setEnabled(false);
        btn_setstandby.setEnabled(false);
    }

    @Override
    protected void initListener() {
        btn_display.setOnClickListener(this);
        btn_display_upperlinescroll.setOnClickListener(this);
        btn_display_at.setOnClickListener(this);
        btn_restart.setOnClickListener(this);
        btn_restore.setOnClickListener(this);
        btn_init.setOnClickListener(this);
        btn_clearline.setOnClickListener(this);
        btn_clearscreen.setOnClickListener(this);
        btn_cursorleft.setOnClickListener(this);
        btn_cursorright.setOnClickListener(this);
        btn_cursordown.setOnClickListener(this);
        btn_cursorup.setOnClickListener(this);
        btn_cursorendleft.setOnClickListener(this);
        btn_cursorendright.setOnClickListener(this);
        btn_cursorhome.setOnClickListener(this);
        btn_cursorend.setOnClickListener(this);
        btn_movecursor.setOnClickListener(this);

        btn_setwelmessage.setOnClickListener(this);
        btn_setcolor_header.setOnClickListener(this);
        btn_setcolor_footer.setOnClickListener(this);
        btn_setcolor_central.setOnClickListener(this);

        btn_setdisplaystyle.setOnClickListener(this);
        btn_setheadertype.setOnClickListener(this);
        btn_setbodydefaulttext.setOnClickListener(this);

        btn_qrcode.setOnClickListener(this);
        btn_qrcodeonpicture.setOnClickListener(this);

        btn_setlines.setOnClickListener(this);
        btn_setbrightness.setOnClickListener(this);
        btn_setcommand.setOnClickListener(this);
        btn_setcharset.setOnClickListener(this);
        btn_setcodepage.setOnClickListener(this);
        btn_uploadpicture.setOnClickListener(this);
        btn_selectpicture.setOnClickListener(this);
        btn_setplayed.setOnClickListener(this);
        btn_showpicture_1.setOnClickListener(this);
        btn_showpicture_2.setOnClickListener(this);
        btn_showpicture_3.setOnClickListener(this);
        btn_showpicture_4.setOnClickListener(this);
        btn_showpicture_5.setOnClickListener(this);
        btn_showpicture_6.setOnClickListener(this);
        btn_showpicture_7.setOnClickListener(this);
        btn_showpicture_8.setOnClickListener(this);
        btn_showpicture_9.setOnClickListener(this);
        btn_showpicture_10.setOnClickListener(this);
        btn_setinterval.setOnClickListener(this);
        btn_setstandby.setOnClickListener(this);

        btn_connect.setOnClickListener(this);
        btn_back.setOnClickListener(this);

        color_text_header.setOnClickListener(this);
        color_text_footer.setOnClickListener(this);
        color_text_central.setOnClickListener(this);
        color_background_header.setOnClickListener(this);
        color_background_footer.setOnClickListener(this);
        color_background_central.setOnClickListener(this);

        mDsp.setUploadListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDsp != null) {
            mDsp.disconnect();
            mDsp = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_display:
                String text1 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !text1.isEmpty()) {
                    mDsp.DSP_Dispay(text1,
                            "cp936");
                }
                break;
            case R.id.btn_display_upperlinescroll:
                String text2 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !text2.isEmpty()) {
                    mDsp.DSP_Dispay_UpperLineScroll(text2,
                            "cp936");
                }
                break;
            case R.id.btn_display_at:
                String text3 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !text3.isEmpty()) {
                    mDsp.DSP_Dispay_At(text3,
                            "cp936",
                            sp_row_display.getSelectedItemPosition() + 1,
                            sp_column_display.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_restart:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_Restart();
                }
                break;
            case R.id.btn_restore:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_Restore();
                }
                break;
            case R.id.btn_init:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_Init();
                }
                break;
            case R.id.btn_clearline:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ClearLine();
                }
                break;
            case R.id.btn_clearscreen:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ClearScreen();
                }
                break;
            case R.id.btn_cursorleft:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorLeft();
                }
                break;
            case R.id.btn_cursorright:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorRight();
                }
                break;
            case R.id.btn_cursordown:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorDown();
                }
                break;
            case R.id.btn_cursorup:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorUp();
                }
                break;
            case R.id.btn_cursorendleft:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorEndLeft();
                }
                break;
            case R.id.btn_cursorendright:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorEndRight();
                }
                break;
            case R.id.btn_cursorend:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorEnd();
                }
                break;
            case R.id.btn_cursorhome:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursorHome();
                }
                break;
            case R.id.btn_movecursor:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_MoveCursor(sp_row.getSelectedItemPosition() + 1,
                            sp_column.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_setlines:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetLines(sp_lines.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_setheadertype:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetHeaderType(sp_headertype.getSelectedItemPosition());
                }
                break;
            case R.id.btn_setdisplaystyle:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetDisplayStyle(sp_displaystyle.getSelectedItemPosition());
                }
                break;
            case R.id.btn_setbodydefaulttext:
                String d_line1_text = edt_bodydefaulttext_1.getText().toString().trim();
                String d_line2_text = edt_bodydefaulttext_2.getText().toString().trim();
                String d_line3_text = edt_bodydefaulttext_3.getText().toString().trim();
                String d_line4_text = edt_bodydefaulttext_4.getText().toString().trim();

                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetBodyDefaultText(d_line1_text, d_line2_text, d_line3_text, d_line4_text, "cp936");
                }
                break;
            case R.id.btn_SetBrightness:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetBrightness(sp_brightness.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_SetCommand:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetCommandSet(sp_commands.getSelectedItemPosition());
                }
                break;
            case R.id.btn_setcharset:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = sp_charset.getSelectedItemPosition();
                    mDsp.DSP_SetCharset(Constant.international_no[i]);
                }
                break;
            case R.id.btn_setcodepage:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = sp_codepage.getSelectedItemPosition();
                    mDsp.DSP_SetCodepage(Constant.codepage_no[i]);
                }
                break;
            case R.id.btn_setwelmessage:
                String line1_text = edt_welmessage_1.getText().toString().trim();
                String line2_text = edt_welmessage_2.getText().toString().trim();

                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetWelMessage_1(line1_text, "cp936");
                    delay(1000);
                    mDsp.DSP_SetWelMessage_2(line2_text, "cp936");
                    delay(1000);
                    mDsp.DSP_SetWelMessage_2_Scroll(cb_line2_scroll.isChecked());
                }

                break;
            case R.id.btn_setcolor_header:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetTextColor_Header(color_text_header.getColor());
                    mDsp.DSP_SetBackGroundColor_Header(color_background_header.getColor());
                }
                break;
            case R.id.btn_setcolor_footer:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetTextColor_Footer(color_text_footer.getColor());
                    mDsp.DSP_SetBackGroundColor_Footer(color_background_footer.getColor());
                }
                break;
            case R.id.btn_setcolor_central:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_SetTextColor_Central(color_text_central.getColor());
                    mDsp.DSP_SetBackGroundColor_Central(color_background_central.getColor());
                }
                break;
            case R.id.cpv_color_text_header:
                openColorPickerDialog(1);
                break;
            case R.id.cpv_color_text_footer:
                openColorPickerDialog(2);
                break;
            case R.id.cpv_color_text_central:
                openColorPickerDialog(3);
                break;
            case R.id.cpv_color_background_header:
                openColorPickerDialog(4);
                break;
            case R.id.cpv_color_background_footer:
                openColorPickerDialog(5);
                break;
            case R.id.cpv_color_background_central:
                openColorPickerDialog(6);
                break;

            case R.id.btn_qrCode:
                String qrtext = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !qrtext.isEmpty()) {
                    mDsp.DSP_DisplayQrCode(qrtext,
                            sp_alignX.getSelectedItemPosition() + 1,
                            sp_alignY.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_qrCodeOnPicture:
                String qrtext1 = edt_text.getText().toString().trim();
                if (mDsp != null && mDsp.isConnect() && !qrtext1.isEmpty()) {
                    mDsp.DSP_DisplayQrCodeOnPicture(qrtext1,
                            sp_alignX_on.getSelectedItemPosition() + 1,
                            sp_picno.getSelectedItemPosition() + 1);
                }
                break;
            case R.id.btn_setplayed:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = 0;
                    if (cb_picture_1.isChecked()) i = i | (1 << 0);
                    if (cb_picture_2.isChecked()) i = i | (1 << 1);
                    if (cb_picture_3.isChecked()) i = i | (1 << 2);
                    if (cb_picture_4.isChecked()) i = i | (1 << 3);
                    if (cb_picture_5.isChecked()) i = i | (1 << 4);
                    if (cb_picture_6.isChecked()) i = i | (1 << 5);
                    if (cb_picture_7.isChecked()) i = i | (1 << 6);
                    if (cb_picture_8.isChecked()) i = i | (1 << 7);
                    if (cb_picture_9.isChecked()) i = i | (1 << 8);
                    if (cb_picture_10.isChecked()) i = i | (1 << 9);
                    mDsp.DSP_SetPlayed(i);
                }
                break;
            case R.id.btn_SetPlayInterval:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = sp_interval.getSelectedItemPosition() + 1;
                    mDsp.DSP_SetPlayInterval(i);
                }
                break;
            case R.id.btn_SetPlayStandBy:
                if (mDsp != null && mDsp.isConnect()) {
                    int i = sp_standby.getSelectedItemPosition();
                    mDsp.DSP_SetStandbyTime(i);
                }
                break;
            case R.id.btn_showpicture_1:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(1);
                }
                break;
            case R.id.btn_showpicture_2:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(2);
                }
                break;
            case R.id.btn_showpicture_3:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(3);
                }
                break;
            case R.id.btn_showpicture_4:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(4);
                }
                break;
            case R.id.btn_showpicture_5:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(5);
                }
                break;
            case R.id.btn_showpicture_6:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(6);
                }
                break;
            case R.id.btn_showpicture_7:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(7);
                }
                break;
            case R.id.btn_showpicture_8:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(8);
                }
                break;
            case R.id.btn_showpicture_9:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(9);
                }
                break;
            case R.id.btn_showpicture_10:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.DSP_ShowPicture(10);
                }
                break;
            case R.id.btn_selectpicture:
                //选择文件【调用系统的文件管理】
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                //intent.setType("image/*");//选择图片
                //intent.setType("audio/*"); //选择音频
                //intent.setType("video/*"); //选择视频 （mp4 3gp 是android支持的视频格式）
                //intent.setType("video/*;image/*");//同时选择视频和图片
                intent.setType("*/*");//无类型限制
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                startActivityForResult(intent, REQUEST_CHOOSEFILE);
                break;
            case R.id.btn_uploadpicture:
                if (tv_picturefilename.getText().toString().isEmpty()) return;
                if (mDsp != null && mDsp.isConnect()) {
                    progressUpdate();
                    runnable = new Runnable() {
                        @Override
                        public void run() {
                            mDsp.DSP_UploadPicture(
                                    sp_picturename.getSelectedItem().toString(),
                                    tv_picturefilename.getText().toString(),
                                    Constant.picture_width[sp_picturename.getSelectedItemPosition()],
                                    Constant.picture_height[sp_picturename.getSelectedItemPosition()]
                            );
                        }
                    };
                    new Thread(runnable).start();
                }
                break;
            case R.id.btn_connect:
                this.serialPort = sp_port.getSelectedItem().toString();
                this.serialBaudrate = Integer.parseInt(sp_baudrate.getSelectedItem().toString());
                connect();
                break;
            case R.id.btn_back:
                if (mDsp != null && mDsp.isConnect()) {
                    mDsp.disconnect();
                }
                mDsp = null;
                this.finish();
                break;
        }
    }

    /**
     * 连接
     */
    private void connect() {
        if (mDsp != null) {
            mDsp.clearbuffer();
            mDsp.disconnect();
        }
        runnable = new Runnable() {
            @Override
            public void run() {

                if (mDsp.SUCCESS == mDsp.connect(serialPort, serialBaudrate, serialFlag)) {
                    showHandler.sendEmptyMessage(0);
                } else {
                    showHandler.sendEmptyMessage(1);
                }
            }
        };
        new Thread(runnable).start();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {//选择文件返回
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CHOOSEFILE:
                    Uri uri = data.getData();
                    String chooseFilePath = FileChooseUtils.getInstance(this).getChooseFileResultPath(uri);
                    LogUtils.i(TAG, "选择文件返回：" + chooseFilePath);
                    tv_picturefilename.setText(chooseFilePath);
                    break;
            }
        }
    }

    private void progressRun(String title, String message) {
        progressDialog = new ProgressDialog(PD500Activity.this);
        progressDialog.setTitle(title);
        progressDialog.setMessage(message);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置进度条对话框//样式（旋转）
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    private void progressUpdate() {
        progressDialog = new ProgressDialog(PD500Activity.this);
        progressDialog.setTitle("Upload File");
        progressDialog.setMessage("Uploading...");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 设置进度条对话框//样式（水平）
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    public void onUpload(int progress, int code) {
        if (code == 0) {
            if (progressDialog.isShowing())
                progressDialog.setProgress(progress);
            if (progress == 100) {
                if (progressDialog.isShowing())
                    progressDialog.dismiss();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showToast("Upload Complete");
                    }
                });
            }
        } else if (code == -1) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast("Upload failed (Read Error)");
                }
            });
        } else if (code == -2) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast("Upload failed (Write Error)");
                }
            });
        } else if (code == -3) {
            if (progressDialog.isShowing())
                progressDialog.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showToast("Upload failed (CRC Error)");
                }
            });
        }
    }

    private static class NoLeakHandler extends Handler {
        WeakReference<PD500Activity> wf;

        private NoLeakHandler(PD500Activity activity) {
            wf = new WeakReference(activity);
        }
    }

    @SuppressLint("HandlerLeak")
    Handler showHandler = new NoLeakHandler(PD500Activity.this) {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    ToastUtils.showToast(serialPort + " Connect successful");

                    String model = mDsp.DSP_GetModel();
                    int version = mDsp.DSP_GetFirmwareVersion();
                    if (!model.isEmpty())
                        tv_model.setText("Model: " + model);
                    else
                        tv_model.setText("Model: unknown");

                    if (version > 0)
                        tv_firmwareVersion.setText("Firmware Version: " + version);
                    else
                        tv_firmwareVersion.setText("Firmware Version: unknown");

                    btn_display.setEnabled(true);
                    btn_display_upperlinescroll.setEnabled(true);
                    btn_display_at.setEnabled(true);
                    btn_restart.setEnabled(true);
                    btn_restore.setEnabled(true);
                    btn_init.setEnabled(true);
                    btn_clearline.setEnabled(true);
                    btn_clearscreen.setEnabled(true);
                    btn_cursorleft.setEnabled(true);
                    btn_cursorright.setEnabled(true);
                    btn_cursordown.setEnabled(true);
                    btn_cursorup.setEnabled(true);
                    btn_cursorendleft.setEnabled(true);
                    btn_cursorendright.setEnabled(true);
                    btn_cursorhome.setEnabled(true);
                    btn_cursorend.setEnabled(true);
                    btn_movecursor.setEnabled(true);

                    btn_setwelmessage.setEnabled(true);
                    btn_setcolor_header.setEnabled(true);
                    btn_setcolor_footer.setEnabled(true);
                    btn_setcolor_central.setEnabled(true);

                    btn_setdisplaystyle.setEnabled(true);
                    btn_setheadertype.setEnabled(true);
                    btn_setbodydefaulttext.setEnabled(true);

                    btn_qrcode.setEnabled(true);
                    btn_qrcodeonpicture.setEnabled(true);

                    btn_setlines.setEnabled(true);
                    btn_setbrightness.setEnabled(true);
                    btn_setcommand.setEnabled(true);
                    btn_setcharset.setEnabled(true);
                    btn_setcodepage.setEnabled(true);
                    btn_uploadpicture.setEnabled(true);
                    btn_selectpicture.setEnabled(true);
                    btn_setplayed.setEnabled(true);
                    btn_showpicture_1.setEnabled(true);
                    btn_showpicture_2.setEnabled(true);
                    btn_showpicture_3.setEnabled(true);
                    btn_showpicture_4.setEnabled(true);
                    btn_showpicture_5.setEnabled(true);
                    btn_showpicture_6.setEnabled(true);
                    btn_showpicture_7.setEnabled(true);
                    btn_showpicture_8.setEnabled(true);
                    btn_showpicture_9.setEnabled(true);
                    btn_showpicture_10.setEnabled(true);
                    btn_setinterval.setEnabled(true);
                    btn_setstandby.setEnabled(true);
                    break;
                case 1:
                    ToastUtils.showToast(serialPort + " Connect failed");

                    btn_display.setEnabled(false);
                    btn_display_at.setEnabled(false);
                    btn_restart.setEnabled(false);
                    btn_restore.setEnabled(false);
                    btn_init.setEnabled(false);
                    btn_clearline.setEnabled(false);
                    btn_clearscreen.setEnabled(false);
                    btn_cursorleft.setEnabled(false);
                    btn_cursorright.setEnabled(false);
                    btn_cursordown.setEnabled(false);
                    btn_cursorup.setEnabled(false);
                    btn_cursorendleft.setEnabled(false);
                    btn_cursorendright.setEnabled(false);
                    btn_cursorhome.setEnabled(false);
                    btn_cursorend.setEnabled(false);
                    btn_movecursor.setEnabled(false);

                    btn_setwelmessage.setEnabled(false);
                    btn_setcolor_header.setEnabled(false);
                    btn_setcolor_footer.setEnabled(false);
                    btn_setcolor_central.setEnabled(false);

                    btn_setdisplaystyle.setEnabled(false);
                    btn_setheadertype.setEnabled(false);
                    btn_setbodydefaulttext.setEnabled(false);

                    btn_qrcode.setEnabled(false);
                    btn_qrcodeonpicture.setEnabled(false);

                    btn_setlines.setEnabled(false);
                    btn_setbrightness.setEnabled(false);
                    btn_setcommand.setEnabled(false);
                    btn_setcharset.setEnabled(false);
                    btn_setcodepage.setEnabled(false);
                    btn_uploadpicture.setEnabled(false);
                    btn_selectpicture.setEnabled(false);
                    btn_setplayed.setEnabled(false);
                    btn_showpicture_1.setEnabled(false);
                    btn_showpicture_2.setEnabled(false);
                    btn_showpicture_3.setEnabled(false);
                    btn_showpicture_4.setEnabled(false);
                    btn_showpicture_5.setEnabled(false);
                    btn_showpicture_6.setEnabled(false);
                    btn_showpicture_7.setEnabled(false);
                    btn_showpicture_8.setEnabled(false);
                    btn_showpicture_9.setEnabled(false);
                    btn_showpicture_10.setEnabled(false);
                    btn_setinterval.setEnabled(false);
                    btn_setstandby.setEnabled(false);
                    break;
            }
        }
    };

    private void openColorPickerDialog(int DIALGE_ID) {
        int color = 0;
        switch (DIALGE_ID) {
            case 1:
                color = color_text_header.getColor();
                break;
            case 2:
                color = color_text_footer.getColor();
                break;
            case 3:
                color = color_text_central.getColor();
                break;
            case 4:
                color = color_background_header.getColor();
                break;
            case 5:
                color = color_background_footer.getColor();
                break;
            case 6:
                color = color_background_central.getColor();
                break;
        }

        //传入的默认color
        ColorPickerDialog colorPickerDialog = ColorPickerDialog.newBuilder().setColor(color)
                //设置dialog标题
                .setDialogTitle(R.string.color_picker)

                //设置为自定义模式
                .setDialogType(ColorPickerDialog.TYPE_CUSTOM)

                //设置有透明度模式，默认没有透明度
                .setShowAlphaSlider(true)

                //设置Id,回调时传回用于判断
                .setDialogId(DIALGE_ID)

                //不显示预知模式
                .setAllowPresets(false)

                //Buider创建
                .create();

        //设置回调，用于获取选择的颜色
        colorPickerDialog.setColorPickerDialogListener(pickerDialogListener);

        colorPickerDialog.show(getFragmentManager(), "color-picker-dialog");
    }

    private ColorPickerDialogListener pickerDialogListener = new ColorPickerDialogListener() {
        @Override
        public void onColorSelected(int dialogId, @ColorInt int color) {
            switch (dialogId) {
                case 1:
                    color_text_header.setColor(color);
                    break;
                case 2:
                    color_text_footer.setColor(color);
                    break;
                case 3:
                    color_text_central.setColor(color);
                    break;
                case 4:
                    color_background_header.setColor(color);
                    break;
                case 5:
                    color_background_footer.setColor(color);
                    break;
                case 6:
                    color_background_central.setColor(color);
                    break;
            }
        }

        @Override
        public void onDialogDismissed(int dialogId) {

        }
    };
}
