package com.apiprintdemo;
/** 微打机芯 （78M）API调用演示
 * @author YLiang
 * @date 2014 04 23
 */

import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
//微打机芯 API使用方法：加载jar。
//加载jar流程：菜单Project->Properties->Java Build Path->Libraries->Add JAEs->选择libs目录下的文件JmPrinter_78M.jar
//并且在Order and Export界面选中使用。
import com.jolimark.Data_Bmp;
import com.jolimark.JmPrinter;  //引用微打机芯 控制类

public class MainActivity extends Activity {

		protected static final int LENGTH_SHORT = 0;
		private Button backButton,feedkButton,exitProgram,initDevElock,btnPrinttext,btnPrintGraph;	
		private Button  BIDSet,setPrinterSpeed,setBlackCheckEnabled,checkSelf;
		private Button  getBlackOffset,btnSetBlackOffset,btnSetAutoFeedMode,btnSetOther;
		private Button  checkBlack ,setBidValue , setPrintPaparClass,  initPrinterAll; 	
		private JmPrinter mPrinter;  //定义78M打印机对象
		private MyClass mMyClass;    //提示框

	    int setAutoSign;             //自动进纸有效 按键次数标记
		@Override  
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_main);
			
			mPrinter = new JmPrinter();           //创建78M打印机机对象
			
			setAutoSign =1;		
		    //从布局文件中获取绑定控件;
			backButton = (Button) this.findViewById(R.id.btn_backPaper);
			feedkButton = (Button) this.findViewById(R.id.btn_feedkButton);		
			exitProgram = (Button) this.findViewById(R.id.btn_Kill);	
			BIDSet   = (Button) this.findViewById(R.id.btn_setting_BID);		
			checkSelf = (Button) this.findViewById(R.id.btn_setting_checkSelf);
			checkBlack = (Button) this.findViewById(R.id.btn_setting_checkBlack);
			setBlackCheckEnabled = (Button) this.findViewById(R.id.btn_setting_BlackCheckEnabled);
			setBidValue   = (Button) this.findViewById(R.id.btn_setBidValue);
			setPrintPaparClass   = (Button) this.findViewById(R.id.btn_setPrintPaparClass);

			setPrinterSpeed = (Button) this.findViewById(R.id.btn_setPrinterSpeed);
			getBlackOffset= (Button) this.findViewById(R.id.btn_getBlackOffset);
			btnSetBlackOffset =(Button) this.findViewById(R.id.btn_SetBlackOffset);
			initDevElock = (Button) this.findViewById(R.id.btn_Elock);
			btnPrinttext = (Button) this.findViewById(R.id.btn_Printtext);
			btnPrintGraph= (Button) this.findViewById(R.id.btn_printGraph);
			btnSetAutoFeedMode= (Button) this.findViewById(R.id.btn_SetAutoFeedMode);
			
			btnSetOther=(Button) this.findViewById(R.id.btn_SetOther);
			// 注册按钮监听
			backButton.setOnClickListener(new ClickListener());
			feedkButton.setOnClickListener(new ClickListener());
			exitProgram.setOnClickListener(new ClickListener());			
			BIDSet.setOnClickListener(new ClickListener());	
			checkSelf.setOnClickListener(new ClickListener());
			checkBlack.setOnClickListener(new ClickListener());
			setBlackCheckEnabled.setOnClickListener(new ClickListener());
			setBidValue.setOnClickListener(new ClickListener());
			setPrintPaparClass.setOnClickListener(new ClickListener());

			setPrinterSpeed.setOnClickListener(new ClickListener());
			getBlackOffset.setOnClickListener(new ClickListener());
			btnSetBlackOffset.setOnClickListener(new ClickListener());
			initDevElock.setOnClickListener(new ClickListener());
			btnPrinttext.setOnClickListener(new ClickListener());
			btnPrintGraph.setOnClickListener(new ClickListener());
			btnSetAutoFeedMode.setOnClickListener(new ClickListener());
			
			
			btnSetOther.setOnClickListener(new ClickListener());
			mMyClass = new MyClass();
		
		}
		public boolean PrintPicTest() {
	        boolean ret = false;
			
			InputStream in = null;
			try {
				in = getResources().getAssets().open("code.png");
			} catch (Exception e) {
				e.printStackTrace();
			}

			Data_Bmp tmpDataBmp = null;
			Bitmap bitmap = null;

			bitmap = BitmapFactory.decodeStream(in);
			tmpDataBmp = new Data_Bmp(bitmap);
			bitmap.recycle();
			bitmap = null;

			byte[][] Dotdata = tmpDataBmp.GetPrintData78M();

			int length = Dotdata.length;

			for (int i = 0; i < length; i += 2) {
				ret = mPrinter.PrintPic(Dotdata[i]); // 一行图形打印第一次打印
				if (!ret) {
					return ret;
				}
				
				mPrinter.Feed(1);
				ret = mPrinter.PrintPic(Dotdata[i + 1]); // 一行图形打印第二次打印，使图形颜色加深
				if (!ret) {
					return ret;
				}
				 // 
				mPrinter.Feed(15);
			}
			return ret;
		}
		
	// 按钮监听实现
	public class ClickListener implements View.OnClickListener {

		private static final int LENGTH_SHORT = 0;
		private String testStr1,testStr2;
		private String exitStr;

		public void onClick(View v) {
			// TODO Auto-generated method stub

			exitStr = "真的要退出程序吗？";
			testStr1 ="字符打印示例:\r\n";
			testStr2 = "映美打印机被誉为高品质打印机！映美打印机创造无限可能！"
					+ "http://www.jolimark.com/" + "\r\n" + "\r\n"+ "\r\n"+ "\r\n" + "\r\n";
			
			switch (v.getId()) {

			case R.id.btn_Kill: {        // 退出应用 按钮

				mMyClass.ExitAlertDialog(MainActivity.this, "提示", exitStr);
				break;
			}
			case R.id.btn_backPaper: {   // 退纸
//				 StepNum为走纸长度（步数），取值范围0<StepNum<49，
//			           每一步为0.176 mm（1/144）英寸
				int StepNum =22 ;       //（22*0.176 =3.872）是标准字体一行和行距的总和 （在打印纸上）。
				boolean retnVale = mPrinter.Back(StepNum);
				if(!retnVale){
				Toast.makeText(MainActivity.this,
						mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();
				}
				break;
			}

			case R.id.btn_feedkButton: { // 进纸
				int StepNum =22 ;        //同退纸，常规使用22这个值。
				boolean retnVale = mPrinter.Feed(StepNum);
				if(!retnVale){
				Toast.makeText(MainActivity.this,
						mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();	
				}
				break;
			}

			case R.id.btn_setting_BID: { // BID打印：  陈列度打印    。打印结果作为打印清晰度设置的参考。
				boolean retnVale = mPrinter.PrintBID();
				if(!retnVale){
				Toast.makeText(MainActivity.this,
						mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();
				}
				break;
			}

			case R.id.btn_setPrinterSpeed: { // 设置打印机速度    常速和高速两种。

				setPrintSpeedDialog();
				break;
			}

			case R.id.btn_setting_checkSelf: { // 自检打印：   自动打印已经设定好的字符，作为打印机机芯打印功能是否异常的参考。

				boolean retnVale = mPrinter.SelfCheck();
				if(!retnVale){
					Toast.makeText(MainActivity.this,
							mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();	
					}
				break;
			}
			case R.id.btn_setting_checkBlack: { // 黑标检测 ：打印机开始走纸，黑标传感器开始工作，在一定距离内检测黑标位。详情请参考文档。

				boolean retnVale = mPrinter.BlackCheck();
				if(!retnVale){
					Toast.makeText(MainActivity.this,
							mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();	
				}else {
					Toast.makeText(MainActivity.this, "黑标检测完成！",
								LENGTH_SHORT).show();
				}
				break;
			}

			case R.id.btn_setBidValue: {       // BID设置：陈列度设置，设置打印清晰度。

				BID_Dialog(MainActivity.this, "请输入BID值:0≤ BID_Value ≤20");
				break;
			}
			case R.id.btn_setPrintPaparClass: { // 设置打印纸类型：   76MM 和57MM两种宽度的打印纸选择

				setPrintPaparClassDialog();
				break;
			}
			
			case R.id.btn_setting_BlackCheckEnabled: { // 设置黑标使能：是否启动检测黑标功能。
				
				setBlackCheckEnabledDialog();
				break;
			}
			case R.id.btn_Elock: {   //开电子锁： 自动打开打印机装纸篓上盖。
						
				boolean retnVale;
				retnVale = mPrinter.UnLock();		 
				if(!retnVale ){
					Toast.makeText(MainActivity.this,
							"开锁异常！" , LENGTH_SHORT).show();
				}
				break;
			}
			case R.id.btn_Printtext: { //自定义 内容打印
				byte[] SData;
				try {
					SData = testStr1.getBytes("GB2312");
					boolean retnVale = mPrinter.PrintText(SData);
					if(!retnVale){
						Toast.makeText(MainActivity.this,
								mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();	
						}
					SData = testStr2.getBytes("GB2312");
					retnVale = mPrinter.PrintText(SData);
					if(!retnVale){
						Toast.makeText(MainActivity.this,
								mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();	
						}
				} catch (UnsupportedEncodingException e) {
					
					e.printStackTrace();  
					
				}			 
				break;
			}
			case R.id.btn_printGraph: {// 自定义 图形打印 （打印头8根打印针）
				PrintPicTest();
				mPrinter.Feed(200);//打印后走纸
				break;
			}
			case R.id.btn_getBlackOffset: { //读取黑标偏移量起始位
				int OffsetValue[] = {0}; //用来保存读取到的黑标偏移量起始位

				boolean rtn = mPrinter.GetBlackOffset(OffsetValue);
				if (rtn){
					Toast.makeText(MainActivity.this,
							 "BlackOffset:  " + OffsetValue[0] , Toast.LENGTH_SHORT).show();
				}
				else{
					Toast.makeText(MainActivity.this,
					         mPrinter.GetLastPrintErr() , Toast.LENGTH_SHORT).show();
				}

				break;
			}
            case R.id.btn_SetBlackOffset: { //设置黑标偏移量起始位:设置打印机检测到黑标后走纸的长度
				
            	SetBlackOffset_Dialog(MainActivity.this, "黑标偏移量:0≤ Black_Value ≤1151");
				break;
			}
            case R.id.btn_SetAutoFeedMode: {          //自动进纸设置
				
				boolean retnVale;
				if (setAutoSign % 2 == 1) {
					retnVale = mPrinter.SetAutoFeedMode(0);// 自动进纸有效
					if (!retnVale) {
						Toast.makeText(MainActivity.this,
								mPrinter.GetLastPrintErr(), LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(MainActivity.this, "自动进纸有效设置成功",
								LENGTH_SHORT).show();
					}
				} else {
					retnVale = mPrinter.SetAutoFeedMode(1);// 自动进纸无效
					if (!retnVale) {
						Toast.makeText(MainActivity.this,
								mPrinter.GetLastPrintErr(), LENGTH_SHORT)
								.show();
					} else {
						Toast.makeText(MainActivity.this, "自动进纸无效设置成功",
								LENGTH_SHORT).show();
					}
				}
				setAutoSign++;// 全局变量
				break;
			}
            case R.id.btn_SetOther: { //设置黑标偏移量起始位:设置打印机检测到黑标后走纸的长度
            	Intent ss = new Intent();
				ss.setClassName("com.apiprintdemo", TestActivity.class.getName());
				startActivity(ss);
            	
				break;
			}
			}// end switch   
		}

	}
		
	/*黑标偏移量起始位设置*/
	public void SetBlackOffset_Dialog(Context context,String title)
	{
		 
		// 取得自定义View  
		final LayoutInflater layoutInflater = LayoutInflater.from(context); 
		final View myLoginView = layoutInflater.inflate(R.layout.setblackoffset_box, null); 
		
		AlertDialog.Builder builder = new AlertDialog.Builder(context); 
		builder.setTitle(title);
		builder.setView(myLoginView);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				EditText bidEditText = (EditText)myLoginView.findViewById(R.id.editTextSet);
	        	
				Integer OffsetValue = Integer.parseInt(  bidEditText.getText().toString()  ) ;
	            if(OffsetValue>=0 && OffsetValue<=1151)
	            {  
					boolean retnVale = mPrinter.SetBlackOffset( OffsetValue );//参数取值范围：0到1151 。 实际偏移量=OffsetValue *0.176mm 
					Toast.makeText(MainActivity.this,                       //即打印机检测到黑标后走纸的长度
							mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();
				
	            }else{
	            	Toast.makeText(MainActivity.this,
							"输入的数字超出范围！", LENGTH_SHORT).show();
				
	            }
	            dialog.cancel(); 
	         
			}
		}) ;
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { 
	           public void onClick(DialogInterface dialog, int which) { 
	        	   dialog.cancel(); 
	           } 
	       });
		builder.create();
		builder.setCancelable(false);
		builder.show();
	}

	/* 设置黑标使能 */
	void setBlackCheckEnabledDialog() {
		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle("设置黑标定位:")
				
				// .setMessage("您确定删除该条信息吗？").
				.setPositiveButton("启用黑标定位",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								boolean retnVale = mPrinter
										.SetBlackCheckEnabled(1);   //启用黑标定位
								if (!retnVale) {
									Toast.makeText(MainActivity.this,
											mPrinter.GetLastPrintErr(),
											LENGTH_SHORT).show();
								}
								dialog.cancel();
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						dialog.cancel();

					}
				})
				.setNeutralButton("取消黑标定位",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

								boolean retnVale = mPrinter
										.SetBlackCheckEnabled(0);//取消黑标定位功能
								if (!retnVale) {
									Toast.makeText(MainActivity.this,mPrinter.GetLastPrintErr(),
										LENGTH_SHORT).show();
								}
								dialog.cancel();
							}
						}).create();
		alertDialog.show();

	}

	/* 设置打印速度 */
	void setPrintSpeedDialog() {
		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle("设置打印速度:")
				.
				// setMessage("您确定删除该条信息吗？").
				setPositiveButton("常速打印",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

								boolean retnVale = mPrinter.SetPrintSpeed(0);
								if (!retnVale) {
								Toast.makeText(MainActivity.this,
										mPrinter.GetLastPrintErr(),
										LENGTH_SHORT).show();
								}
								dialog.cancel();
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				})
				.setNeutralButton("高速打印",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

								boolean retnVale = mPrinter.SetPrintSpeed(1);
								if (!retnVale) {
								Toast.makeText(MainActivity.this,
										mPrinter.GetLastPrintErr(),
										LENGTH_SHORT).show();
								}
								dialog.cancel();
							}
						}).create();
		alertDialog.setCancelable(false);
		alertDialog.show();

	}

	/* 设置打印纸类型 */
	void setPrintPaparClassDialog() {
		Dialog alertDialog = new AlertDialog.Builder(this)
				.setTitle("设置打印纸类型:")
				.
				// setMessage("您确定删除该条信息吗？").

				setPositiveButton("57mm宽度",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								boolean retnVale = mPrinter.SelectPrintRange(1);
								if (!retnVale) {
								Toast.makeText(MainActivity.this,
										mPrinter.GetLastPrintErr(),
										LENGTH_SHORT).show();
								}
								dialog.cancel();
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				})
				.setNeutralButton("76mm宽度",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {

								boolean retnVale = mPrinter.SelectPrintRange(0);
								if (!retnVale) {
								Toast.makeText(MainActivity.this,
										mPrinter.GetLastPrintErr(),
										LENGTH_SHORT).show();
								}
								dialog.cancel();
							}
						}).create();
		alertDialog.setCancelable(false);
		alertDialog.show();

	}
		/*********************************************************************	*
		 * 功能: BID陈列度设置 对话框					(0x03)
		 * 参数: context为Activity；title 为对话框标题
		 * 返回: 1, 成功. 0, 失败.  如果函数失败,请调用 GetLastPrintErr()获取详细错误的信息
		 * 说明: 参数将永久保存在FLASH，直到下次修改
		 *********************************************************************	*/
		public void BID_Dialog(Context context,String title)
		{
			 
			// 取得自定义View  
			final LayoutInflater layoutInflater = LayoutInflater.from(context); 
			final View myLoginView = layoutInflater.inflate(R.layout.bid_promptbox, null); 
			
			AlertDialog.Builder builder = new AlertDialog.Builder(context); 
			builder.setTitle(title);
			builder.setView(myLoginView);//.setView(new EditText(this))
			builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					EditText bidEditText = (EditText)myLoginView.findViewById(R.id.editTextBID);
		        	//EditText EditText = (EditText)myLoginView.findViewById(R.id.et_statusPrompt);
					Integer tepStr = Integer.parseInt(  bidEditText.getText().toString()  ) ;
		            if(tepStr>=0 && tepStr<=20)
		            {
					  
						boolean retnVale = mPrinter.SetBID( tepStr );
						if (!retnVale) {
						Toast.makeText(MainActivity.this,
								mPrinter.GetLastPrintErr() , LENGTH_SHORT).show();
						}else{
							Toast.makeText(MainActivity.this,
									"BID陈列度设置 成功" , LENGTH_SHORT).show();
						}
						dialog.cancel(); 
		            }else{
		            	Toast.makeText(MainActivity.this,
								"输入的数字超出范围！" , LENGTH_SHORT).show();
		            }
		            
		         
				}
			}) ;
			builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { 
		           public void onClick(DialogInterface dialog, int which) { 
		        	   dialog.cancel(); 
		           } 
		       });
			builder.create();
			builder.setCancelable(false);
			builder.show();
		}
		
		/*********************************************************************	*
		 * 功能: 延时函数					
		 * 参数: mm_time 为毫秒； 1000毫秒=1秒
		 *********************************************************************	*/
		public void mySleep(int mm_time)
		{
			try {
				   Thread.sleep(mm_time);
				   } 
			catch (InterruptedException e) {}
			
		}
		/*********************************************************************
		 * * 功能: 按返回键的提示信息       参数: 无. 返回: 无.
		 ********************************************************************* */
		@Override
		public void onBackPressed() {

			AlertDialog dialog = new AlertDialog.Builder(
					MainActivity.this).setTitle("提示")
					.setMessage("是否退出？")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
							finish();
						}
					})
					.setNegativeButton("取消", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							dialog.cancel();
						}
					}).create();
			dialog.setCancelable(false);
			dialog.show();
		}
		@Override
	    protected void onDestroy() {
	        super.onDestroy();
	        mPrinter = null;  
	         
	    }
		

	

}
