package opo.com.simplescalessdk;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import OnePlusOneAndroidSDK.Printer.LabelPrinter;
import OnePlusOneAndroidSDK.Printer.PosPrinter;
import OnePlusOneAndroidSDK.ScalesOS.ScalesSDK;
import OnePlusOneAndroidSDK.ScalesOS.WeightInfo;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "MainActivity";

    static TextView tv_netWeight;
    static TextView tv_tareWeight;
    static TextView tv_grossWeight;
    TextView tv_log;

    Button btn_open;
    Button btn_getWeight;
    Button btn_zero;
    Button btn_tare;
    Button btn_exitTare;
    Button btn_close;

    Button btn_printer_usb2;
    Button btn_printer_serial;

    static TextView tv_mode;
    static TextView tv_status;
    static TextView tv_zero;

    private String stext = "";

    private double nowweight = -9999;
    private int tickcnt = 0;

    // 秤重
    private ScalesSDK mscalessdk;
    // 标签打印机
    private LabelPrinter mlabelprinter;
    // 小票打印机
    private PosPrinter mposprinter;

    private void assetsave(String s) throws IOException {
        int i = 0;
        byte[] b = new byte[1024];
        AssetManager assetManager = getAssets();
        InputStream inputStream = assetManager.open(s);
        FileOutputStream fos = new FileOutputStream(getExternalFilesDir(null).toString() + "/" + s);
        while ((i = inputStream.read(b)) > 0) {
            fos.write(b, 0, i);
        }
        fos.close();
        inputStream.close();
    }
    //
    private static Bitmap getAssetsBitmap(Context context, String path) {
        AssetManager am = context.getAssets();
        InputStream inputStream = null;
        try {
            inputStream = am.open(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        return bitmap;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();

        //  称重
        mscalessdk = ScalesSDK.getInstance(this, new ScalesSDK.WeightChangedListener() {
            @Override
            public void onWeightChanged(final WeightInfo weightInfo) {
                tv_netWeight.setText("净重：" + weightInfo.getNetWeight());
                tv_tareWeight.setText("皮重：" + weightInfo.getTareWeight());
                tv_grossWeight.setText("毛重：" + weightInfo.getGrossWeight());
                tv_mode.setText(weightInfo.getMode());
                tv_status.setText(weightInfo.getStatus());
                if (weightInfo.getZero())
                    tv_zero.setText("零点");
                else tv_zero.setText("非零点");
            }
        });

        //  标签打印
        mlabelprinter = LabelPrinter.getInstance(this);
        if (mlabelprinter.Open()) {
            Log.d(TAG, "Label Printer Open OK");
        } else {
            Log.d(TAG, "Label Printer Open Fail");
        }

        // usb
        mposprinter = PosPrinter.getInstance(this);
        if (mposprinter.Open()) {
            Log.d(TAG, "Pos Printer Open OK");
        } else {
            Log.d(TAG, "Pos Printer Fail");
        }

    }

    private void initView() {

        tv_netWeight = (TextView) findViewById(R.id.tv_netWeight);
        tv_tareWeight = (TextView) findViewById(R.id.tv_tareWeight);
        tv_grossWeight = (TextView) findViewById(R.id.tv_grossWeight);
        tv_mode = (TextView) findViewById(R.id.tv_mode);
        tv_status = (TextView) findViewById(R.id.tv_status);
        tv_zero = (TextView) findViewById(R.id.tv_zero);

        btn_open = (Button) findViewById(R.id.btn_open);
        btn_open.setOnClickListener(this);
        btn_getWeight = (Button) findViewById(R.id.btn_getResult);
        btn_getWeight.setOnClickListener(this);
        btn_zero = (Button) findViewById(R.id.btn_zero);
        btn_zero.setOnClickListener(this);
        btn_tare = (Button) findViewById(R.id.btn_tare);
        btn_tare.setOnClickListener(this);
        btn_exitTare = (Button) findViewById(R.id.btn_exitTare);
        btn_exitTare.setOnClickListener(this);
        btn_close = (Button) findViewById(R.id.btn_close);
        btn_close.setOnClickListener(this);
        tv_log = (TextView) findViewById(R.id.tv_log);
        btn_close.setEnabled(false);
        btn_printer_usb2 = (Button) findViewById(R.id.btn_printer_usb2);
        btn_printer_usb2.setOnClickListener(this);

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

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_open:

                if (mscalessdk.Open(new File("/dev/ttyS0"))) {
                    btn_open.setEnabled(false);
                    btn_close.setEnabled(true);
                    showmsg("串口打开成功");
                }

                break;
            case R.id.btn_getResult:
                String result = mscalessdk.GetResult();
                if (result != null) {
                    showmsg("重量：" + result);
                } else {
                    showmsg("获取重量失败");
                }
                break;
            case R.id.btn_zero:
                int zero = mscalessdk.Zero();
                if (zero == 1) {
                    showmsg("归零成功");
                } else {
                    showmsg("归零失败 " + getErrorInfo(zero));
                }
                break;
            case R.id.btn_tare:
                int tare = mscalessdk.Tare();
                if (tare == 1) {
                    showmsg("去皮成功");
                } else {
                    showmsg("去皮失败 " + getErrorInfo(tare));
                }
                break;
            case R.id.btn_exitTare:
                int i = mscalessdk.ExitTare();
                if (i == 1) {
                    showmsg("退出去皮成功");
                } else {
                    showmsg("退出去皮失败 " + getErrorInfo(i));
                }

                break;
            case R.id.btn_close:
                int close = mscalessdk.Close();
                showmsg("串口关闭成功");
                if (close == 1) {
                    showmsg("串口关闭成功");
                    btn_close.setEnabled(false);
                    btn_open.setEnabled(true);
                } else {
                    showmsg("串口关闭失败 " + getErrorInfo(close));
                }

                break;
            case R.id.btn_printer_serial:

                // 检查打印机状态

                int resserial = mlabelprinter.GetStatus();

                switch (resserial) {
                    case 1:
                        showmsg("打印机缺纸");
                        break;
                    case 2:
                        showmsg("打印机未取纸");
                        break;
                    case 3:
                        showmsg("打印机开盖");
                        break;
                    case 4:
                        showmsg("打印机高温");
                        break;
                    case 5:
                        showmsg("打印机定位异常");
                        break;
                    case 6:
                        showmsg("打印机忙");
                        break;
                    case 7:
                        showmsg("打印机未知异常");
                        break;
                    case 8:
                        showmsg("写入错误、异常开盖");
                        break;
                }

                resserial = 0;
                if (resserial != 0) return; // 打印机状态不正确不允许打印

                boolean resok = mlabelprinter.PrintLabelBitmap(getAssetsBitmap(this, "log.jpg"));

                Log.d(TAG, "PrintLabelBitmap:  " + resok);

                break;
            case R.id.btn_printer_usb2:

                if (!mposprinter.RollPaperStatus()) {
                    Log.d(TAG, "纸张状态不正确，请检查！");
                    return;
                }

                //  小票打印
                ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                try {
                    // 对齐居中
                    buffer.write(ESCUtil.alignCenter());
                    // 打印图片
                    buffer.write(ESCUtil.printBitmap(getAssetsBitmap(MainActivity.this, "opo.jpg")));
                    // 设置字体大小
                    buffer.write(ESCUtil.setTextSize(6));
                    // 字体加粗
                    buffer.write(ESCUtil.boldOn());
                    //
                    buffer.write("测试打印\n".getBytes("GB18030"));
                    // 取消字体加粗
                    buffer.write(ESCUtil.boldOff());
                    // 恢复默认字体大小
                    buffer.write(ESCUtil.setTextSize(0));
                    // 走纸
                    buffer.write(ESCUtil.nextLine(5));
                    // 居左
                    buffer.write(ESCUtil.alignLeft());
                    //
                    String text =
                            " 名称　　　　  单价  数量 金额\n" +
                                    " ------------------------------\n" +
                                    " 西红柿炒蛋　  10.0   10  100.0\n" +
                                    " 肉沫茄子　　  10.0   1   10.0 \n" +
                                    " 肉片汤  　　  100.0  1   100.0\n" +
                                    " 咖喱鸡块  　  100.0  2   200.0\n" +
                                    " 大盘鸡  　　  100.0  1   100.0\n" +
                                    " 鱼蛋粉  　　  15.0   1   15.0 \n" +
                                    " 备注：不要辣\n";
                    buffer.write(text.getBytes("GB18030"));
                    // 对齐居中
                    buffer.write(ESCUtil.alignCenter());
                    // 二维码
                    buffer.write(ESCUtil.getPrintQRCode("www.oneplusone.cc", 8, 0));
                    // 一维码
                    buffer.write(ESCUtil.getPrint128Code("C", "123456789012", 50, 3, 2));
                    // 走纸
                    buffer.write(ESCUtil.nextLine(10));
                    // 开钱箱
                    buffer.write(ESCUtil.openCashdrawer());
                    //
                    boolean res = mposprinter.WriteData(buffer.toByteArray());
                    Log.d(TAG, "run: res " + res);

                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
            default:
                break;
        }
    }

    private void showmsg(String msg) {
        tv_log.setText(msg);
    }

    private void displayError(String error) {
        AlertDialog.Builder b = new AlertDialog.Builder(this);
        b.setTitle("Error");
        b.setMessage(error);
        b.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        b.show();
    }

    private String getErrorInfo(int i) {
        switch (i) {
            case 0x8000:
                return "命令数据不在合法范围内";
            case 0x8100:
                return "重量不稳定";
            case 0x8200:
                return "AD值溢出";
            case 0x8300:
                return "当前在去皮模式";
            case 0x8400:
                return "没有开机归零";
            case 0x8500:
                return "当前在预置去皮模式";
            case 0x8600:
                return "防作弊没有打开，不能设置";
            case 0xFE00:
                return "错误的命令";
        }
        return "";
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mscalessdk != null) {
            mscalessdk.Close();
            mscalessdk = null;
        }
    }
}
