package com.printer.demo;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.printer.demo.global.GlobalContants;
import com.printer.demo.utils.CodePageUtils;
import com.printer.demo.utils.PrefUtils;
import com.printer.demo.utils.UriUtils;
import com.printer.demo.utils.XTUtils;
import com.printer.sdk.PrinterInstance;
import com.printer.sdk.utils.XLog;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Locale;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TextPrintActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {

    private static final String TAG = "TextPrintActivity";
    private LinearLayout header;
    private Button btn_send, btn_print_note, btn_print_codepaper, btn_select_file, btn_print_select_file, btn_print_table,btn_print_table_to_bitmap;
    private ToggleButton tb_isHexData;
    private EditText et_input;

    private TextView tv_file_path;
    private boolean isHexData = false;
    private static PrinterInstance mPrinter;
    private String input;
    String path = null;
    private static Context mContext;
    private String textToSend;
    byte[] sendData = new byte[0];
    ExecutorService executor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        XLog.d(TAG, "yxz at TextPrintActivity.java onCreate()");
        setContentView(R.layout.activity_print_text);
        mContext = this;
        init();
        mPrinter = PrinterInstance.mPrinter;
        input = et_input.getText().toString();
        et_input.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                input = et_input.getText().toString();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void init() {

        et_input = (EditText) findViewById(R.id.et_input);
        et_input.setText(R.string.textprintactivty_input_content);
        header = (LinearLayout) findViewById(R.id.ll_headerview_textPrint);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_print_table_to_bitmap = (Button) findViewById(R.id.btn_print_table_to_bitmap);
        btn_print_table_to_bitmap.setOnClickListener(this);
        btn_send.setOnClickListener(this);
        btn_print_note = (Button) findViewById(R.id.btn_print_note);
        btn_print_table = (Button) findViewById(R.id.btn_print_table);
        btn_print_table.setOnClickListener(this);
        btn_print_note.setOnClickListener(this);
        btn_print_codepaper = (Button) findViewById(R.id.btn_print_codepaper);
        btn_print_codepaper.setOnClickListener(this);
        btn_send.setOnClickListener(this);
        tb_isHexData = (ToggleButton) findViewById(R.id.tb_hex_on);
        tb_isHexData.setOnCheckedChangeListener(this);
        isHexData = tb_isHexData.isChecked();
        initHeader();

        btn_select_file = (Button) findViewById(R.id.btn_select_file);
        btn_select_file.setOnClickListener(this);

        btn_print_select_file = (Button) findViewById(R.id.btn_print_select_file);
        btn_print_select_file.setOnClickListener(this);

        tv_file_path = (TextView) findViewById(R.id.tv_file_path);
        // 获取当前设备的CPU核心数
        int cpuCount = Runtime.getRuntime().availableProcessors();
        XLog.d("yxz", "cpuCount:" + cpuCount);
        // 创建一个线程池，包含与CPU核心数相同的线程
        executor = Executors.newScheduledThreadPool(cpuCount);
    }

    /**
     * 初始化标题上的信息
     */
    private void initHeader() {
        setHeaderLeftText(header, getString(R.string.back), new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();

            }
        });
        headerConnecedState.setText(getTitleState());
        setHeaderCenterText(header, getString(R.string.headview_TextPrint));
        setHeaderLeftImage(header, new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void onClick(View view) {
        if (PrinterInstance.mPrinter != null && SettingActivity.isConnected) {
            if (view == btn_send) {

                final String content = et_input.getText().toString();
                Log.i(TAG, content);
                if (content != null || content.length() != 0) {

                    if (isHexData && SettingActivity.isConnected) {
                        byte[] srcData = XTUtils.string2bytes2(content);
                        mPrinter.sendBytesData(srcData);
                    } else if (!isHexData && SettingActivity.isConnected) {
                        // // PrinterInstance.mPrinter.printText(content +
                        // "\r\n");
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                synchronized (this) {
                                    mPrinter.printText(content + "\r\n");
                                    try {
                                        XLog.d("yxz", "str:" + new String(content.getBytes("gbk")
                                                , "gbk"));
                                    } catch (UnsupportedEncodingException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }).start();
//						Locale locale = Locale.getDefault();
//						String language = locale.getLanguage();
//						String country = locale.getCountry();
                    }
                }

            } else if (view == btn_print_note) {
                new Thread(new Runnable() {
                    public void run() {
                        XTUtils.printNote(TextPrintActivity.this.getResources(), mPrinter);
                    }
                }).start();
            } else if (view == btn_print_codepaper) {
                new CodePageUtils().selectCodePage(this, PrinterInstance.mPrinter);
            } else if (view == btn_print_table) {
                //print table
                new Thread(new Runnable() {
                    public void run() {
//                        XTUtils.printLaoLongNameTest(mPrinter);
//                        XTUtils.testLaoTable(mPrinter);
                        XTUtils.printTable1(TextPrintActivity.this.getResources(), mPrinter);
                    }
                }).start();
            }else if (view == btn_print_table_to_bitmap) {
                //print table
                new Thread(new Runnable() {
                    public void run() {
//                        XTUtils.printLaoLongNameTest(mPrinter);
//                        XTUtils.printWeightLongCnTest(mPrinter);
                        XTUtils.printTableToBitmapTest(TextPrintActivity.this.getResources(), mPrinter);

                    }
                }).start();
            }
        } else {
            Toast.makeText(TextPrintActivity.this, getString(R.string.no_connected), 0).show();
        }

        if (PrinterInstance.mPrinter != null && SettingActivity.isConnected) {
            if (view == btn_select_file) {
                //选择文件
                Intent intent2 = new Intent();
                intent2.setType("*/*");
                intent2.addCategory(Intent.CATEGORY_OPENABLE);
                intent2.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent2, 15);
            }


            if (view == btn_print_select_file) {
                //打印选择文件
                if (path == null) {
                    Toast.makeText(this, getString(R.string.toast_please_select_file), 0).show();
                    return;
                }
                int fileType = PrefUtils.getInt(this, GlobalContants.FILE_TYPE, 0);
//            testModel = PrefUtils.getInt(mContext, GlobalContants.TEST_MODEL, 0);
                if (fileType == 0) {
//            sendData = XTUtils.readFromFile(new File(path));
                    sendData = XTUtils.readFile(new File(path));
                    if (sendData != null) {
                        textToSend = hexToString(sendData);
                        XLog.d(TAG, getString(R.string.log_print_file) + textToSend);
                        try {
                            if (isHexData) {
                                //直接是16进制数据
                                mPrinter.sendBytesData(sendData);
                            } else {
                                mPrinter.sendBytesData(textToSend.getBytes("GBK")); // 假设打印机使用GBK编码
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                    }

                } else if (fileType == 1) {
//            String content = Utils.readFromFile(new File(path));
                    String content = XTUtils.readStringFromFile(new File(path));
                    try {
                        sendData = XTUtils.string2bytes2(content);
                    } catch (Exception e) {
                        Toast.makeText(mContext, "数据异常，请检查", Toast.LENGTH_SHORT).show();
                    }
                }
                // 将异步任务提交给线程池执行
                executor.execute(asyncTask);


            }

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 15) {
            mContext.getFilesDir();
            path = data.getData().toString();
            int index = path.indexOf("/storage");
            if (index == -1) {
                try {
                    path = UriUtils.getPath(mContext, data.getData());
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(mContext, getString(R.string.toast_read_file_fail), Toast.LENGTH_SHORT).show();
                }
            } else {
                path = path.substring(index);
            }
            tv_file_path.setText(path);
        }
    }

    // 定义一个异步任务
    Runnable asyncTask = new Runnable() {
        @Override
        public void run() {
            // 在这里执行异步任务的代码
//                    myPrinter.
            try {

//                        int length = myPrinter.sendBytesData(sendData);
                XLog.d(TAG, getString(R.string.log_print_file_start));
                int length = mPrinter.sendBytesData(hexStringToByteArray(textToSend)); // 假设打印机使用GBK编码
//                        int length =  myPrinter.sendBytesData(textToSend.getBytes("GBK")); // 假设打印机使用GBK编码

//                        int length = myPrinter.sendBytesData(sendData);
                if (length > 0) {
                    //success
//                            dialogH.dismiss();
                    runOnUiThread(() -> Toast.makeText(mContext, getString(R.string.toast_print_success), 0).show());
                } else {
                    //fail
//                            dialogH.dismiss();
                    runOnUiThread(() -> Toast.makeText(mContext, getString(R.string.toast_print_fail), 0).show());
                }
            } catch (Exception e) {
                //fail
//                        dialogH.dismiss();
                runOnUiThread(() -> Toast.makeText(mContext, getString(R.string.toast_print_fail) + e.getMessage(), 0).show());
            }
//                    singlePrinterTestTask(devicesAddress);
        }
    };

    public static String hexToString(byte[] hexData) {
        StringBuilder sb = new StringBuilder();
        for (byte b : hexData) {
            sb.append((char) b);
        }
        return sb.toString();
    }

    public static byte[] hexStringToByteArray(String hexString) {
        // 去掉字符串中的空格
        hexString = hexString.replaceAll("\\s+", "");

        // 创建字节数组
        int len = hexString.length();
        byte[] byteArray = new byte[len / 2];

        for (int i = 0; i < len; i += 2) {
            // 将两个字符作为一个16进制字节转换为整数
            byteArray[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return byteArray;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

        if (isChecked) {// 16进制开
            isHexData = true;
            byte[] datas;
            try {
                datas = input.getBytes("GBK");
                et_input.setText(XTUtils.bytesToHexString2(datas, datas.length));
                input = et_input.getText().toString();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        } else {
            isHexData = false;
            if (input == null || input.length() == 0) {
                et_input.setText(R.string.textprintactivty_input_content);
            } else {
                et_input.setText(XTUtils.hexStringToString2(input));
                input = et_input.getText().toString();
            }
        }

    }

}
