package com.icod.yk_printer_test;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.icod.yk_printer_test.utils.UIUtils;
import com.szsicod.print.escpos.PrinterAPI;
import com.szsicod.print.log.Logger;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class ZxingActivity extends ActionBarActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    ImageView ivShow;
    private int width = 0;
    private int height = 0;

    private Spinner sp_code_type;
    private String codeStrings[] = UIUtils.getStringArr(R.array.codeType);
    private int codeType = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zxing);
        sp_code_type = (Spinner) findViewById(R.id.sp_code_type);
        ArrayAdapter<String> codeTypeAdapter = new ArrayAdapter<String>(this, android.R.layout
                .simple_spinner_item,android.R.id.text1, codeStrings);
        sp_code_type.setAdapter(codeTypeAdapter);

        final EditText etText = (EditText) findViewById(R.id.et_text);
        Button btnTransform = (Button) findViewById(R.id.btn_transform);

        ivShow = (ImageView) findViewById(R.id.iv_show);
        final EditText etWidth = (EditText) findViewById(R.id.et_width);
        final EditText etHeight = (EditText) findViewById(R.id.et_height);
        btnTransform.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Bitmap bitmap = encode(etText.getText().toString(), Integer.parseInt
                        (etWidth.getText()
                                .toString()), Integer.parseInt(etHeight.getText().toString()));
                if (bitmap==null){
                    Log.i(TAG,"图片生成异常");
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int i = 0;
                        try {
                            PrinterAPI.getInstance().printRasterBitmap(bitmap,false,2000,
                                    false,false);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        Log.i(TAG, " " + i);
                    }
                }).start();


            }
        });
        findViewById(R.id.btn_cut).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ( PrinterAPI.getInstance().isConnect()){
                    PrinterAPI.getInstance().cutPaper(66,0);
                }

            }
        });

        findViewById(R.id.btn_com).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sp_code_type.setSelection(4);
                Bitmap first = encode("HF86385845107",
                        280, 280);
                Bitmap two=encode("HF86385845107102538400000006d000000720000000080030723FChQDHUTrFhS9iJcor9DmQ==:**********:1:4:0:義大利Bonomi小麥千層餅:1:59.0義大利Bonomi小麥千層餅:1:59.0",
                        280,280);
                Bitmap bitmap = combineBitmap(first, two);
                try {
                    PrinterAPI.getInstance().setAlignMode(1);
                    long start=System.currentTimeMillis();
                    PrinterAPI.getInstance().printRasterBitmap(bitmap);
                    Logger.i("时间差"+(System.currentTimeMillis()-start));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }


    public Bitmap encode(String content, int desiredWidth, int desiredHeight) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        //multiFormatWriter.encode()
        int length = content.length();
        BarcodeFormat barcodeFormat = BarcodeFormat.CODABAR;
        switch (sp_code_type.getSelectedItemPosition()) {
            case 0:
                if (length!=8){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.EAN_8;
                break;
            case 1:
                if (length!=8){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.UPC_E;
                break;
            case 2:
                if (length!=13){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.EAN_13;
                break;
            case 3:
                if (length!=11||length!=12){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.UPC_A;
                break;
            case 4:
                barcodeFormat = BarcodeFormat.QR_CODE;
                break;
            case 5:
                if (length>80){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.CODE_39;
                break;
            case 6:
                if (length>80){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.CODE_93;
                break;
            case 7:
                if (length>80||length<1){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.CODE_128;
                break;
            case 8:
                if (length>80){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.ITF;
                break;
            case 9:
                barcodeFormat = BarcodeFormat.PDF_417;
                break;
            case 10:
                barcodeFormat = BarcodeFormat.CODABAR;
                break;
            case 11:
                if (length>1675){
                    Log.e(TAG,"长度不支持");
                    return null;
                }
                barcodeFormat = BarcodeFormat.DATA_MATRIX;
                break;
            case 12:
                barcodeFormat = BarcodeFormat.AZTEC;
                break;


        }
        try {
            Map<EncodeHintType,Object> hintTypeMap=new HashMap<>();
            hintTypeMap.put(EncodeHintType.MARGIN,0);
            hintTypeMap.put(EncodeHintType.CHARACTER_SET,"utf-8");
            BitMatrix matrix = multiFormatWriter.encode(content, barcodeFormat,
                    desiredWidth, desiredHeight, hintTypeMap);
            int width = matrix.getWidth();
            this.width = width;
            int height = matrix.getHeight();
            this.height = height;
            int[] pixels = new int[width * height];
            Logger.i("width :"+width);
            Logger.i("height :"+height);

            int position = 0;
            for (int y = 0; y < height; y++) {
                for (int x = 0; x < width; x++) {
                    if (matrix.get(x, y)) {
                        pixels[y * width + x] = 0xff000000;
                    } else {
                        pixels[y * width + x] = 0xffffffff;
                    }
                    position++;
                }
            }
            Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
            ivShow.setImageBitmap(bitmap);
            return bitmap;

        }catch (IllegalArgumentException e){
            Log.e( TAG,e.getMessage());
            return null;
         }
        catch (WriterException e) {
            e.printStackTrace();
            return null;
        }
    }

    public Bitmap combineBitmap(Bitmap first,Bitmap two){
        int i = first.getWidth() + two.getWidth() ;
        int width = i>640?640:i;
        int maxHeight=first.getHeight()>two.getHeight()?first.getHeight():two.getHeight();
        Bitmap bitmap = Bitmap.createBitmap(width, maxHeight, Bitmap.Config.RGB_565);
        Canvas canvas=new Canvas(bitmap);
        Paint paint=new Paint();
        canvas.drawBitmap(first,0,0,null);
        canvas.drawBitmap(two,first.getWidth(),0,null);
        return bitmap;

    }
}
