package com.cwbuyer.lib;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

import com.cwbuyer.format.IDialog;
import com.pwbuyer.main.R;

public class Utilis {
	
	public static void runVibrate(Context context) {
		try {
			String s = Utilis.getStringSet(context, "vibrator_preference", "30");
		    if (!s.equals("0")) {
				Vibrator vibrator = (Vibrator) context
						.getSystemService(Context.VIBRATOR_SERVICE);
				vibrator.vibrate(Integer.valueOf(30));
		    }
		} catch (Exception e) {
		}
	}
	
	public static Bitmap exifToDegrees(String pathP,Bitmap bitmap,int exifOrientation) {
		int nPicDegree=exifOrientation;
		Bitmap bitmapR=null;
//	    if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_90) { nPicDegree=90; } 
//	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_180) {  nPicDegree=180; } 
//	    else if (exifOrientation == ExifInterface.ORIENTATION_ROTATE_270) { nPicDegree=270; }
//	    nPicDegree=90;
		Matrix matrix = new Matrix();
		matrix.preRotate(nPicDegree);
		bitmapR = Bitmap.createBitmap(bitmap, 0, 0, 210, 280, matrix, true);

        FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(pathP);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    try {
	    	bitmapR.compress(CompressFormat.JPEG, 100, fos);
					fos.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    return bitmapR;    
	 }
	
	@SuppressWarnings("deprecation")
	public static Drawable getResourceImage(Context cnt, String res) {
		int imageResource = cnt.getResources().getIdentifier(res, null,cnt.getPackageName());
		Drawable image = null;
		if(res.indexOf("drawable/") < 0){ // 代表這個不是 Resource
			Bitmap bmp = getLimitBitmap(res, 200, 200);
			if(bmp != null){
				image = new BitmapDrawable(bmp);
			}
		}else{
			image = cnt.getResources().getDrawable(imageResource);
		}
		return image;
	}

/*	
	private static boolean createFolder(String strPath){
		boolean bSuccess = false;
		File file = new File(strPath.toString());
		if(file.exists() == true){
			bSuccess = true;
		}else{
			bSuccess = file.mkdirs();
		}
		return bSuccess;
	}
*/
/*	
	private static void saveToExternal(InputStream is, String strFullPath){
		File file = new File(strFullPath);
		try{
			if(file.exists() == true){
//				return;
			}
			else{
				if(file.createNewFile() == false)
					return;
			}
			
			if(file.exists() == true){
				FileOutputStream fos = new FileOutputStream(file);
				byte[] buf = new byte[1024];   
				int nLength = 0;
				while((nLength = is.read(buf)) > 0){
					fos.write(buf,0,nLength);
				}
				fos.flush();
				fos.close();
			}
		}catch(IOException e){
			
		}
	}
*/

/*	
	private static InputStream returnStream(String path) {
		InputStream is = null;
		try {
			URL url = new URL(path);
			URLConnection conn = url.openConnection();
			conn.connect();
			is = conn.getInputStream();

		} catch (IOException e) {
			e.printStackTrace();
		}
		return is;
	}
*/
	
	  public static void setAutoRotationMode(Activity activity) {
//			int screen = Utils.getIntSet(this, "screen_orientation_preference", 1);
		int screen = Integer.valueOf(Utilis.getStringSet(activity, "screen_orientation_preference", "1"));
//		Toast.makeText(activity, "Change Screen : " + screen, Toast.LENGTH_SHORT).show();
		switch(screen){
		case 1:
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
			break;
		case 2:
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
			break;
		case 3:
			activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
			break;
		}
	  }


	  /*
	   * 第一次使用訊息提醒
	   */
	  public static void firstUseMsg(final Context context, final String iniTag, String Msg) {
	    String s = Utilis.getStringSet(context, iniTag, "0");
	    if (s.equals("0")) {
	      new AlertDialog.Builder(context).setTitle(context.getString(R.string.sys_msg_firstuse_title)).setMessage(Msg).setPositiveButton(context.getString(R.string.sys_msg_firstuse_cancel), new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	        }
	      }).setNegativeButton(context.getString(R.string.sys_msg_firstuse_ok), new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int which) {
	          Utilis.setStringSet(context, iniTag, "1");
	        }
	      }).show();
	    }
	  }
	  
	  public static void reCNT(Context context){
		  int reCNT=toInt(getIni(context, "SYS", "IMEI", 7))+1;
		  Utilis.putIni(context, "SYS", "IMEI", ""+reCNT, 7);
	  }
	  
	private static String uniqueID = null;
	private static final String PREF_UNIQUE_ID = "PREF_UNIQUE_ID";
	
	public synchronized static String id(Context context){
		if(uniqueID == null){
			SharedPreferences sp = context.getSharedPreferences(
					PREF_UNIQUE_ID, Context.MODE_PRIVATE);
			uniqueID = sp.getString(PREF_UNIQUE_ID, null);
			if(uniqueID == null){
				uniqueID = UUID.randomUUID().toString();
				Editor editor = sp.edit();
				editor.putString(PREF_UNIQUE_ID, uniqueID);
				editor.commit();
			}
		}
		return uniqueID;
	}
	
	
	public static String getDateTime(String date){
		String[] dates = date.split("/");
		if(dates.length >= 3){
			StringBuffer buf = new StringBuffer();
			buf.append(dates[0]).append("-");
			buf.append(formatDate(dates[1])).append("-");
			buf.append(formatDate(dates[2]));
			return buf.toString();
		}else{
			return date;
		}
	}
	
	public static String chkString(String strChk){
		if(strChk != null && strChk.length() > 0){
			return strChk;
		}else{
			return "";
		}
	}
	
	// 確認轉換數字 至少為 0 
	public static int valuesInt(String strChk){
		if(strChk != null && strChk.length() > 0){
			try{
				return Integer.valueOf(strChk);
			}catch(Exception e){
				return 0;
			}
		}else{
			return 0;
		}
	}
	
	public static int chkInt(int nChk){
		if(nChk >= 0){
			return nChk;
		}else{
			return 0;
		}
	}
	
	public static SQLiteDatabase getDB(Context context) {
	    try {
	    	String mDBPath=null;	
	    	mDBPath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+getIni(context,"SYS","YEAR",4);
	    	File file = new File(mDBPath);	      
	      return SQLiteDatabase.openOrCreateDatabase(file, null);
	      
	    } catch (SQLException e) {
	      return null;
	    }
	}

	/*
	 * 刪除檔案
	 */
	public static boolean DeleteFile(String fileName) {
		try {
			File zipFile = new File(fileName);
			if (zipFile.exists()) {
				return zipFile.delete();
			} else {
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public static String getPackageName(Context context) {
		return context.getString(R.string.app_package);
	}
	
	// 過濾要上傳到 Server 的字串!
	public static String filterStr(String data){
		if(data != null){
			String target = data.replace("&", "%26");
			return target;
		}else return null;
	}
	
	public static String reverStr(String data){
		if(data != null){
			String target = data.replace("%26", "&");
			return target;
		}else return null;
	}
	
	public static String formatDate(String s) {
		if (s.length() == 1)
			s = "0" + s;
		return s;
	}
	
	public static String formatDate(int n) {
		String s = String.valueOf(n);
		if (s.length() == 1)
			s = "0" + s;
		return s;
	}
	
	// 特別為了流水號做處理
	public static String formatFlow(int n) {
		String s = String.valueOf(n);
		if (s.length() == 1){
			s = "00000" + s;
		}else if(s.length() == 2){
			s = "0000" + s;
		}else if(s.length() == 3){
			s = "000" + s;
		}else if(s.length() == 4){
			s = "00" + s;
		}else if(s.length() == 5){
			s = "0" + s;
		}
		return s;
	}
	
	public static String ordFlow(int n) {
		String s = String.valueOf(n);
		if (s.length() == 1){
			s = "00" + s;
		}else{
			s = "0" + s;
		}
		return s;
	}
	
	public static String getIMEI(Context context){
		String imei;
		TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);  
		imei = "" + tm.getDeviceId();  //DeviceId(IMEI)
		
		return imei;
	}

	/*
	 * 判斷有沒有網路
	 */
	public static boolean haveInternet(Context context) {
		boolean result = false;
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo info = connManager.getActiveNetworkInfo();
		if (info == null || !info.isConnected()) {
			result = false;
		} else {
			if (!info.isAvailable()) {
				result = false;
			} else {
				result = true;
			}
		}
		return result;
	}
	
	public static String copyDBtoSDCard(Context context) {
		String tDBZipPath ="";
		try {
			// 取得SD Card路徑
			String tSDCardPath = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
			// 指定SD Card與目標目錄名稱
			File tDataPath = new File(tSDCardPath);
			String SAVE_FOLDER = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+"CWBuyer/data/" ;
			String path = SAVE_FOLDER.substring(0, SAVE_FOLDER.length()-1);
			
	        File myDataPath = new File(path);
	        if (myDataPath.exists()){
				File f = new File(path);        
				File file[] = f.listFiles();
				for (int i=0; i < file.length; i++)
				{
					if (file[i].toString().indexOf(".zip")>0){
					Utilis.DeleteFile(SAVE_FOLDER+file[i].getName());
				    //過濾為壓縮檔,才要刪除
					}
				}
	        }
			
			String DBPath=tSDCardPath+getIni(context,"SYS","YEAR",4);
			String DBjPath=DBPath.replace(".sdb",".sdb-journal");
			String DBm=DBPath.replace("cwbuyerpos","qmtrio");
			String DBmj=DBm.replace(".sdb",".sdb-journal");
			String DBini=tSDCardPath+File.separator+"cwbuyer/PARA/ini.sdb";
			String DBiniJ=DBini.replace(".sdb",".sdb-journal");
			String JpgF1=DBini.replace("ini.sdb","img_additem.png");
			String JpgF2=DBini.replace("ini.sdb","04.jpg");
			String DBalbun=tSDCardPath+File.separator+"cwbuyer/albun/img_additem.png";
			tDBZipPath = tDataPath +getIni(context,"SYS","BACKOUT",6).replace(".sdb","_"+DateUtil.getSystemTime().substring(3, 10)+".zip");
			//cwbuyer/data/AA1_cwbuyerpos.sdb
    		StringBuffer zipList =new StringBuffer();
    		
    		File tDBPath = new File(DBPath);
    		if (tDBPath.exists()) zipList.append(DBPath);
    		
    		File tDBjPath = new File(DBjPath);
   			if (tDBjPath.exists()) zipList.append("，"+DBjPath);
   			
    		File tDBm = new File(DBm);
    		if (tDBm.exists()) zipList.append("，"+DBm);
    		
    		File tDBmj = new File(DBmj);
   			if (tDBmj.exists()) zipList.append("，"+DBmj);
   			
   			File tDBiPath = new File(DBini);
   			if (tDBiPath.exists()) zipList.append("，"+DBini);
			//Toast.makeText(context,tDBiPath.toString() , Toast.LENGTH_SHORT).show();
			
   			File tDBiiPath = new File(DBiniJ);
   			if (tDBiiPath.exists()) zipList.append("，"+DBiniJ);
			//Toast.makeText(context,DBiniJ , Toast.LENGTH_SHORT).show();
			
   			File tjpg1Path = new File(JpgF1);
   			if (tjpg1Path.exists()) zipList.append("，"+JpgF1);
			
   			File tjpg2Path = new File(JpgF2);
   			if (tjpg2Path.exists()) zipList.append("，"+JpgF2);
			
   			File tDBalbun = new File(DBalbun);
   			if (tDBalbun.exists()) zipList.append("，"+DBalbun);
			
			Toast.makeText(context,zipList.toString() , Toast.LENGTH_SHORT).show();
   			
			if (zipList.toString().length()>0){
			String[] arrayZipF =  zipList.toString().split("，");
			
			try {
				int BUFFER = 2048;
				BufferedInputStream origin = null;
				FileOutputStream dest = new FileOutputStream(tDBZipPath);
				ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
				byte data[] = new byte[BUFFER];
				
				for (int i = 0; i < arrayZipF.length; i++) {
					Log.v("Compress", "Adding: " + arrayZipF[i]);
					FileInputStream fi = new FileInputStream(arrayZipF[i]);
					origin = new BufferedInputStream(fi, BUFFER);
					if (arrayZipF[i].indexOf("/data")>0){
						ZipEntry entry = new ZipEntry(arrayZipF[i].substring(arrayZipF[i].indexOf("/data")+1));
						out.putNextEntry(entry);
					}else if (arrayZipF[i].indexOf("/PARA")>0){
						ZipEntry entry = new ZipEntry(arrayZipF[i].substring(arrayZipF[i].indexOf("/PARA")+1));
						out.putNextEntry(entry);
					}else if (arrayZipF[i].indexOf("/albun")>0){
						ZipEntry entry = new ZipEntry(arrayZipF[i].substring(arrayZipF[i].indexOf("/albun")+1));
						out.putNextEntry(entry);
					}
					int count;
					while ((count = origin.read(data, 0, BUFFER)) != -1) {
						out.write(data, 0, count);
					}
					origin.close();
				}
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			
			//toZipF(context,arrayZipF, tDBZipPath);
			}else{
				tDBZipPath="";	
			}
		} catch (Exception e) {
			Log.i("CopyDBException", e.getMessage());
			tDBZipPath="";
			Toast.makeText(context, "資料庫匯出 失敗", Toast.LENGTH_SHORT).show();
		}
		return tDBZipPath;
	}
	
	
	public static String getStringSet(Context context, final String strTag, String defValue){
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
		String value = pref.getString(strTag, defValue);
		return value;
	}
	
	public static Integer getIntSet(Context context, String name, Integer defValue) {
		try {
			SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
			return pref.getInt(name, defValue);
		} catch (Exception e) {
			Log.i("EngKing", "getStringSet_Exception: " + e.toString());
			return 0;
		}
	}
	
	public static Boolean getBooleanSet(Context context, String name, boolean defValue) {

		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
	    return pref.getBoolean(name, defValue);
	  }
	
	public static Float getFloatSet(Context context, String name, Float defValue) {
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
	    return pref.getFloat(name, defValue);
	  }
	
	public static Long getLongSet(Context context, String name, Long defValue) {
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
	    return pref.getLong(name, defValue);
	  }
	
	public static void setStringSet(Context context, final String strTag, String defValue){
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
		SharedPreferences.Editor mEditor = pref.edit();
		mEditor.putString(strTag, defValue);
		mEditor.commit();
	}
	
	public static void setIntSet(Context context, String name, Integer defValue) {
	    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
	    SharedPreferences.Editor mEditor = pref.edit();
	    mEditor.putInt(name, defValue);
	    mEditor.commit();
	  }
	
	public static void setLongSet(Context context, String name, Long defValue) {
	    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
	    SharedPreferences.Editor mEditor = pref.edit();
	    mEditor.putLong(name, defValue);
	    mEditor.commit();
	  }
	
	public static void setFloatSet(Context context, String name, Float defValue) {
	    SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
	    SharedPreferences.Editor mEditor = pref.edit();
	    mEditor.putFloat(name, defValue);
	    mEditor.commit();
	}
	
	public static void setBooleanSet(Context context, String name, Boolean defValue) {
//		SharedPreferences pref = context.getSharedPreferences(PrefKey.NAME, 0);
		SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
	    SharedPreferences.Editor mEditor = pref.edit();
	    mEditor.putBoolean(name, defValue);
	    mEditor.commit();
	  }
	
	public static String getShortName(ComponentName cn){
		String className = cn.getClassName();
		int nPos = className.lastIndexOf(".");
		String shortName = className.substring(nPos);
		return shortName;
	}
	

	
	@SuppressWarnings("unused")
	public static String getRealPathFromURI(Activity act,Uri contentURI) {
	    String result;
	    
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = act.getContentResolver().query(contentURI,
	            projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    if (cursor == null) { 
	        result = contentURI.getPath();
	    } else { 
	    	cursor.moveToFirst();
	    	result = cursor.getString(column_index);
	    }
	    cursor.close();
	    return result;
	}
	
	/**
	 * @param width   return the new Width Bmp 
	 * @param height  return the new Height Bmp
	 * @return Resacle Bitmap
	 */
	public static Bitmap getScaleBitmap(String imagePath, int newWidth, int newHeight){
		 final int COLOR_PIXEL = 3;
		 BitmapFactory.Options option = new BitmapFactory.Options();
	     option.inJustDecodeBounds = true;
	     BitmapFactory.decodeFile(imagePath, option);
	     
	     //Decode again with inSampleSize
	     int maxNumOfPixels = COLOR_PIXEL * newWidth * newHeight;
	     option.inJustDecodeBounds = false;
	     option.inSampleSize = computeSampleSize(option, -1, maxNumOfPixels);
	     
	     try{
	    	 Bitmap bmp = BitmapFactory.decodeFile(imagePath, option);
	    	 
	    	 Bitmap rescaleBmp = Bitmap.createScaledBitmap(bmp, newWidth, newHeight, true);
	    	 return rescaleBmp;
	    	 
	     }catch(OutOfMemoryError e){
	    	 Log.e("Gallery", "BitmapManager->getScaleBitmap() OutOfMemoryError!");
	    	 return null;
	     }
	}
	
	
	/**
	 * @param width   return the new Width Bmp 
	 * @param height  return the new Height Bmp
	 * @return Resacle Bitmap
	 */
	@SuppressWarnings("unused")
	public static Bitmap getLimitBitmap(String imagePath, int maxWidth, int maxHeight){
		 final int COLOR_PIXEL = 3;
		 File file=new File(imagePath);
		 if (!file.exists() || imagePath.length()<=0){return null;}  
		 BitmapFactory.Options option = new BitmapFactory.Options();
	     option.inJustDecodeBounds = true;
	     BitmapFactory.decodeFile(imagePath, option);
	     
	     int w = option.outWidth;
	     int h = option.outHeight;
	     int maxNumOfPixels =0;
	     
	     maxNumOfPixels = COLOR_PIXEL * maxWidth * maxHeight;
	     option.inJustDecodeBounds = false;
	     int nSampleSize = computeSampleSize(option, -1, maxNumOfPixels);
	     
	     option.inSampleSize = nSampleSize;
	     
	     try{
	    	 Bitmap bmp = BitmapFactory.decodeFile(imagePath, option);
	    	 return bmp;
	    	 
	     }catch(OutOfMemoryError e){
	    	 Log.e("Gallery", "BitmapManager->getScaleBitmap() OutOfMemoryError!");
	    	 return null;
	     }
	}
	
	
	public static int computeSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    int initialSize = computeInitialSampleSize(options, minSideLength,
	            maxNumOfPixels);

	    int roundedSize;
	    if (initialSize <= 8) {
	        roundedSize = 1;
	        while (roundedSize < initialSize) {
	            roundedSize <<= 1;
	        }
	    } else {
	        roundedSize = (initialSize + 7) / 8 * 8;
	    }

	    return roundedSize;
	}
	
	private static int computeInitialSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    double w = options.outWidth;
	    double h = options.outHeight;

	    int lowerBound = (maxNumOfPixels == -1) ? 1 :
	            (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
	    int upperBound = (minSideLength == -1) ? 128 :
	            (int) Math.min(Math.floor(w / minSideLength),
	            Math.floor(h / minSideLength));

	    if (upperBound < lowerBound) {
	        // return the larger one when there is no overlapping zone.
	        return lowerBound;
	    }

	    if ((maxNumOfPixels == -1) &&
	            (minSideLength == -1)) {
	        return 1;
	    } else if (minSideLength == -1) {
	        return lowerBound;
	    } else {
	        return upperBound;
	    }
	}
	
	public static void checkPicSize(String picPath){
		File filePic= new File(picPath);
	  if (filePic.exists()){//圖檔存在
		if (filePic.length()>=100000){ 
			Bitmap mBitmap = Utilis.getScaleBitmap(picPath, 240, 320);
	        FileOutputStream fos = null;
	        try {
				fos = new FileOutputStream(picPath);
			} catch (FileNotFoundException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				mBitmap.compress(CompressFormat.JPEG, 100, fos);
				fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	  }
	}
	
	@SuppressWarnings("unused")
	public static Bitmap getSmallPic(String filepath)
	{
	      //The new size to decode to 
//	      final int NEW_SIZE=100; [R]nouse
	      //Only decode image size. Not whole image
	      BitmapFactory.Options option = new BitmapFactory.Options();
	      option.inJustDecodeBounds = true;
	      BitmapFactory.decodeFile(filepath, option);
	      //Now we have image width and height. We should find the correct scale value. (power of 2)
	      int width=option.outWidth;
	      int height=option.outHeight;
	      int scale=1;
	      int max,min;
	      max=213; //[R]max=160
	      min=142; //[R]min=120
	      while(true){
	          if(width>height){max=width;} else {max=height;}
	          if(max/2<min || max/2<min)
	              break;
	          width/=2;
	          height/=2;
	          scale++;
	      }
	      scale++;

	      //Decode again with inSampleSize
	      option = new BitmapFactory.Options();
	      option.inJustDecodeBounds = false;
//	      option.inSampleSize=scale;
	      option.inSampleSize=20;
//	      option.inPurgeable=true;
//	      option.inInputShareable=true;
	       
	      return  BitmapFactory.decodeFile(filepath,option);		
	}
	
	
	public static String getMonthDate(){
    	StringBuffer buf = new StringBuffer();
    	int nYear1 = 0;
    	int nMonth1 = 0;
    	int nDay1 = 0;
    	int nYear2 = 0;
    	int nMonth2 = 0;
    	int nDay2 = 0;
    	Calendar c = Calendar.getInstance();
    	
    	c.set(Calendar.DAY_OF_MONTH, 1); // 關鍵
    	
    	nYear1 = c.get(Calendar.YEAR);
		nMonth1 = c.get(Calendar.MONTH) + 1;
		nDay1 = c.get(Calendar.DAY_OF_MONTH);
		
		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DATE, -1);   // 關鍵
		
		nYear2 = c.get(Calendar.YEAR);
		nMonth2 = c.get(Calendar.MONTH) + 1;
		nDay2 = c.get(Calendar.DAY_OF_MONTH);
		
		buf.append(nYear1).append("/");
    	buf.append(formatDate(nMonth1)).append("/");
    	buf.append(formatDate(nDay1)).append("~");
    	
    	buf.append(nYear2).append("/");
    	buf.append(formatDate(nMonth2)).append("/");
    	buf.append(formatDate(nDay2));
    	
    	return buf.toString();
    }
	
	public static String getTaxDate(String mToday){
		String mTD="";
		String TDate="01-02;03-04;05-06;07-08;09-10;11-12";
		//						012345678901234567890123456789	0   3   6  9 12 mToday formate '2019-02-19'
		int loc=TDate.indexOf(mToday.substring(5, 7))/6;
		mTD=""+(Utilis.toInt(mToday.substring(0, 4))-1911)+"年"+TDate.substring(loc*6, (loc+1)*6-1)+"月";
    	return mTD;
    }
	
	
	public static String getWeekDate(){
    	StringBuffer buf = new StringBuffer();
    	int nYear1 = 0;
    	int nMonth1 = 0;
    	int nDay1 = 0;
    	int nYear2 = 0;
    	int nMonth2 = 0;
    	int nDay2 = 0;
    	
    	Calendar c = Calendar.getInstance();
//    	c.add(Calendar.DAY_OF_MONTH, 1);
    	int day = c.get(Calendar.DAY_OF_WEEK);
    	if(day == Calendar.SUNDAY){
    		c.add(Calendar.DAY_OF_MONTH, -1);
    	}
    	
    	c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
    	c.setTime(c.getTime());
    	
    	nYear1 = c.get(Calendar.YEAR);
    	nMonth1 = c.get(Calendar.MONTH) + 1;
    	nDay1 = c.get(Calendar.DAY_OF_MONTH);
    	
    	buf.append(nYear1).append("/");
    	buf.append(formatDate(nMonth1)).append("/");
    	buf.append(formatDate(nDay1)).append("~");
    	
    	c.add(Calendar.DAY_OF_MONTH, 6);
    	
    	nYear2 = c.get(Calendar.YEAR);
    	nMonth2 = c.get(Calendar.MONTH) + 1;
    	nDay2 = c.get(Calendar.DAY_OF_MONTH);
    	
    	buf.append(nYear2).append("/");
    	buf.append(formatDate(nMonth2)).append("/");
    	buf.append(formatDate(nDay2));
    	
    	return buf.toString();
    }
	
	// 傳回上次採購的時間，沒有則回傳今天
	public static String getRecentDate(Context context){
		String recentDate = null;
		SQLiteDatabase db = Utilis.getDB(context);
		if(db != null){
			try{
				Cursor cursor = db.rawQuery("Select CREATEDATETIME from qdetail Order by CREATEDATETIME Desc limit 1", null);
				if(cursor != null){
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						recentDate = cursor.getString(0);
						recentDate = recentDate.replace("-", "/");
					}
					cursor.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				db.close();
			}
		}
		if(recentDate == null){
			recentDate = DateUtil.getCurrentDate();
		}
		return recentDate;
	}
    
	// 傳回上次採購的時間，沒有則回傳今天
	public static String getRecentPDate(Context context){
		String recentDate = null;
		SQLiteDatabase db = Utilis.getDB(context);
		if(db != null){
			try{
				Cursor cursor = db.rawQuery("Select FORMDATE from qhead Order by FORMDATE Desc limit 1", null);
				if(cursor != null){
					if(cursor.getCount() > 0){
						cursor.moveToFirst();
						recentDate = cursor.getString(0);
						recentDate = recentDate.replace("-", "/");
					}
					cursor.close();
				}
			}catch(Exception e){
				e.printStackTrace();
			}finally{
				db.close();
			}
		}
		if(recentDate == null){
			recentDate = DateUtil.getCurrentDate();
		}
		if (recentDate.indexOf("-")>0) recentDate = recentDate.replace("-", "/");
		
		return recentDate;
	}
    
	public static String getDayDate(){
    	StringBuffer buf = new StringBuffer();
    	int nYear1 = 0;
    	int nMonth1 = 0;
    	int nDay1 = 0;
    	Calendar c = Calendar.getInstance();
    	nYear1 = c.get(Calendar.YEAR);
    	nMonth1 = c.get(Calendar.MONTH) + 1;
    	nDay1 = c.get(Calendar.DAY_OF_MONTH);
    	
    	buf.append(nYear1).append("/");
    	buf.append(formatDate(nMonth1)).append("/");
    	buf.append(formatDate(nDay1));
    	
//    	buf.append("~");
    	
//    	buf.append(nYear1).append("/");
//    	buf.append(Utilis.format(nMonth1)).append("/");
//    	buf.append(Utilis.format(nDay1));
    	
    	return buf.toString();
    }

	//
	public static double dedb (double dout, int n ){
		double dreturn=dout;
		BigDecimal bd= new BigDecimal(dout);   
		dreturn=bd.setScale(n, BigDecimal.ROUND_HALF_UP).doubleValue();// 小數後面n, 四捨五入
		return  dreturn;
	}

	
    public static byte[] strTobytes(String str ,String charset){
        byte[] b=null,data=null;
        try {
            b = str.getBytes("utf-8");
            data=new String(b,"utf-8").getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return data;
    }
	
	// 取到小數點第二位
	public static float formatFloat(Float nFloat){
		try{
			StringBuffer buf = new StringBuffer();
			String strFloat = String.valueOf(nFloat);
			String[] strFormat = new String[2];
			int nFind  = strFloat.indexOf("."); // 尋找小數點
			if(nFind >= 0){
				strFormat[0] = strFloat.substring(0, nFind);
				strFormat[1] = strFloat.substring(nFind + 1, strFloat.length());
			}else{
				strFormat[0] = strFloat;
				strFormat[1] = "0";
			}
			buf.append(strFormat[0]);
			if(strFormat.length >= 2){
				
				if(strFormat[1].length() >= 2){
					// 確認第一位跟第二位都為 0 則回傳 百分比
					if(strFormat[1].charAt(0) == '0' && strFormat[1].charAt(1) == '0'){
//						return buf.toString();
					}else{
						buf.append(".");
						buf.append(strFormat[1].charAt(0));
						buf.append(strFormat[1].charAt(1));
					}
				}else{
					if(strFormat[1].length() > 0  && strFormat[1].charAt(0) != '0'){
						buf.append(".").append(strFormat[1].charAt(0));
					}
				}
			}
			return Float.valueOf(buf.toString());
		}catch(Exception e){
			return nFloat;
		}
	}
	
	
	// 取到小數點第二位
	public static String getFloatString(Float nFloat){
		try{
			StringBuffer buf = new StringBuffer();
			String strFloat = String.valueOf(nFloat);
			int nFind  = strFloat.indexOf("."); // 尋找小數點
			String[] strFormat = new String[2];
			if(nFind >= 0){
				strFormat[0] = strFloat.substring(0, nFind);
				strFormat[1] = strFloat.substring(nFind + 1, strFloat.length());
			}else{
				strFormat[0] = strFloat;
				strFormat[1] = "0";
			}
//			String[] strFormat = strFloat.split("."); // 拆掉小數點
			if(strFormat.length >= 2){
				buf.append(strFormat[0]);
				if(strFormat[1].length() >= 2){
					// 確認第一位跟第二位都為 0 則回傳 百分比
					if(strFormat[1].charAt(0) == '0' && strFormat[1].charAt(1) == '0'){
//						return buf.toString();
					}else{
						buf.append(".");
						buf.append(strFormat[1].charAt(0));
						buf.append(strFormat[1].charAt(1));
					}
				}else{
					if(strFormat[1].length() > 0  && strFormat[1].charAt(0) != '0'){
						buf.append(".").append(strFormat[1].charAt(0));
					}
				}
				return buf.toString();
			}else{
				return strFloat;
			}
		}catch(Exception e){
			return String.valueOf(nFloat);
		}
	}
	
	// 獲取 ZIP 開啟的 Intent
	public static Intent getZipFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/zip");
		return intent;
	}
	
	// 獲取 RAR 開啟的 Intent
	public static Intent getRarFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/x-rar-compressed");
		return intent;
	}  
	
	// 獲取 Image 開啟的 intent
	public static Intent getImageFileIntent( String param )  
	{  
	    Intent intent = new Intent("android.intent.action.VIEW");  
	    intent.addCategory("android.intent.category.DEFAULT");  
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
	    Uri uri = Uri.fromFile(new File(param ));  
	    intent.setDataAndType(uri, "image/*");  
	    return intent;  
	}  

	// 獲取 Pdf 開啟的 Intent
	public static Intent getPdfFileIntent(String param)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/pdf");
		return intent;
	}

	// 獲取 Word 開啟的 Intent
	public static Intent getWordFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/msword");
		return intent;
	}  

	// 獲取 Excel 開啟的 Intent
	public static Intent getExcelFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		Uri uri = Uri.fromFile(new File(param));
		intent.setDataAndType(uri, "application/vnd.ms-excel");
		return intent;
	}
	
	
	// 獲取 PPT 開啟的 Intent
	public static Intent getPPTFileIntent(String param) {
		Intent intent = new Intent("android.intent.action.VIEW"); 
	    intent.addCategory("android.intent.category.DEFAULT"); 
	    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	    Uri uri = Uri.fromFile(new File(param )); 
	    intent.setDataAndType(uri, "application/vnd.ms-powerpoint"); 
	    return intent; 
	}
	   
	// 獲取用來打開文本的 Intent   
	public static Intent getTextFileIntent(String param, boolean paramBoolean)
	{
		Intent intent = new Intent("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		if (paramBoolean) {
			Uri uri1 = Uri.parse(param);
			intent.setDataAndType(uri1, "text/plain");
		} else {
			Uri uri2 = Uri.fromFile(new File(param));
			intent.setDataAndType(uri2, "text/plain");
		}
		return intent;
	} 
	
	public static boolean isTimeServiceRunning(Context cnt) {
		ActivityManager manager = (ActivityManager) cnt.getSystemService(Context.ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if ("com.salesbook.main.MainService".equals(service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}
	
	public static double toDouble(String number){
		if(number == null || number.length() <= 0){
			return 0;
		}else{
			try{
				return Double.valueOf(number.trim());
			}catch(Exception e){
				e.printStackTrace();
				return 0;
			}
		}
	}
	
	public static int toInt(String number){
		try{
			if(number == null || number.length() <= 0){
				return 0;
			}else{
				try{
					if (number.indexOf("%")>0) number=number.substring(0,number.indexOf("%"));
					if (number.indexOf(".")>0) number=number.substring(0,number.indexOf("."));
					return Integer.valueOf(number.trim());
				}catch(Exception e){
					e.printStackTrace();
					return 0;
				}
			}
		}catch(Exception e){
			return 0;
		}
	}
	
	public static long toLong(String number){
		if(number == null || number.length() <= 0){
			return 0;
		}else{
			try{
				return Long.valueOf(number.trim());
			}catch(Exception e){
				e.printStackTrace();
				return 0;
			}
		}
	}
	
	//壓縮ZIP檔
	public static void toZipF(Context context,String[] files, String destZip) {
		try {
			int BUFFER = 2048;
			BufferedInputStream origin = null;
			FileOutputStream dest = new FileOutputStream(destZip);
			ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
			byte data[] = new byte[BUFFER];
			for (int i = 0; i < files.length; i++) {
				Log.v("Compress", "Adding: " + files[i]);
				FileInputStream fi = new FileInputStream(files[i]);
				origin = new BufferedInputStream(fi, BUFFER);
				
				ZipEntry entry = new ZipEntry(files[i].substring(files[i].indexOf(Utilis.getIni(context, "SYS","YEAR", 7))+Utilis.getIni(context, "SYS","YEAR", 7).length()+1));
				out.putNextEntry(entry);
				int count;
				while ((count = origin.read(data, 0, BUFFER)) != -1) {
					out.write(data, 0, count);
				}
				origin.close();
			}
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	  // 解壓縮 _function 2
		public static void Unzip2(String zipFileName, String outputDirectory)
				throws Exception {
			String TAG="______________####__________";
			ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
			ZipEntry z;
			String name = "";
			while ((z = in.getNextEntry()) != null) {
				name = z.getName();
				Log.d(TAG, "unzipping file: " + name);
				if (z.isDirectory()) {
					Log.d(TAG, name + "is a folder");
					File folder = new File(outputDirectory + File.separator + name);
					folder.mkdir();
				} else {
					if (name.indexOf("/")>0)
					{
						File folder = new File(outputDirectory + File.separator+name.substring(0, name.lastIndexOf("/")));
						if (!folder.exists()) folder.mkdir();
					}
					File file = new File(outputDirectory + File.separator + name);

					file.createNewFile();
					// get the output stream of the file
					FileOutputStream out = new FileOutputStream(file);
					int ch;
					byte[] buffer = new byte[1024];
					// read (ch) bytes into buffer
					while ((ch = in.read(buffer)) != -1) {
						// write (ch) byte from buffer at the position 0
						out.write(buffer, 0, ch);
						out.flush();
					}
					out.close();
				}
			}
			in.close();
		}
		
		// 確保編號保持在X位數
		public static String formatNumber(String s, int x) {
			StringBuffer buf = new StringBuffer();
			if(x > 0){
				int length = s.length();
				if (length == 0){
					for(int i = 0; i < x; i ++){
						buf.append("0");
					}
					s = buf.toString();
				}else{
					for(;length < x; length++){
						buf.append("0");
					}
					buf.append(s);
				}
				return buf.toString();
			}else{
				return s;
			}
		}

		public static String getIni(Context context,String Obj,String Key,int mode){
			//Obj,Key,Index 都應該有值,否則返回
			String value=null;		
		    try {
			      File file = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cwbuyer/para/ini.sdb");
			      SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
			      
			      StringBuffer mBuf = new StringBuffer();
			      mBuf.append("select * from system where OBJ='"+Obj+"' and KEY='"+Key+"'");
			      Cursor cs = db.rawQuery(mBuf.toString(), null);
			      if (cs.getColumnCount()>0){
			    	  cs.moveToFirst();
			    	  int index = cs.getInt(cs.getColumnIndex("POINT"));
			    	  if(mode==0){ //有預設值
			    		  value=cs.getString(index+3);
			    	  } else if (mode>=1 && mode <=8){
			    		  value=cs.getString(mode+3);  //指定要求值
			    	  }else if(mode==9){ //全數帶回  
			    		  StringBuffer Buf = new StringBuffer();
			    		  Buf.append(cs.getString(cs.getColumnIndex("T1"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T2"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T3"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T4"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T5"))+"!&!")		    		  
			    		  .append(cs.getString(cs.getColumnIndex("T6"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T7"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T8"))+"!&!")
			    		  .append(cs.getString(cs.getColumnIndex("T9")));
			    		  value=Buf.toString();
			    	  }
			      }
			      cs.close();
			      db.close();
		    } catch (SQLException e) {
			      return null;	    	
		    }
			return value;
		}

		public static void putIni(Context context,String Obj,String Key,String value,int mode){
			//Obj,Key,Index 都應該有值,否則返回
		    try {
			      File file = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+ "/cwbuyer/para/ini.sdb");
			      SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(file, null);
			      
			      StringBuffer mBuf = new StringBuffer();
			      mBuf.append("update system set T"+mode+"='"+value+"'")
			      .append(" where OBJ='"+Obj+"' and KEY='"+Key+"'");
			      db.execSQL(mBuf.toString());
			      db.close();
		    } catch (SQLException e) {
		    }
		}
		
		public static String makeSPics(Context context,String BigPic){
			 int px=210;
			 int py=280;
			 String nFile=BigPic;
//		 if(BigPic.indexOf("drawable/") < 0) {
			 File myDataPath = new File(nFile.substring(0,nFile.lastIndexOf("/")));			 
//			 myDataPath = new File(nFile.substring(0,nFile.lastIndexOf("")));			 
		        if (!myDataPath.exists()) {
		            myDataPath.mkdirs();
		          }
			 
			 Bitmap vBitmap = Bitmap.createBitmap( px,py, Bitmap.Config.RGB_565);		 
			File file = new File(BigPic);
			if ((file.exists() == true && file.length()>100000) || (nFile.equalsIgnoreCase(BigPic)==false)) {
				vBitmap=Utilis.getLimitBitmap(BigPic, px, py);
				Bitmap rsizePic=vBitmap;
					 
					 ByteArrayOutputStream stream = new ByteArrayOutputStream();
				        FileOutputStream fos = null;
						try {
							fos = new FileOutputStream(nFile);
							
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
				    try {
						int swidth = vBitmap.getWidth();
						int shgh = vBitmap.getHeight();
						
						Matrix scaleMatrix = new Matrix();
						scaleMatrix.postScale(1,1);
						rsizePic =Bitmap.createBitmap(vBitmap, 0, 0, swidth, shgh, scaleMatrix, true);
						rsizePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
						rsizePic.compress(CompressFormat.JPEG, 100, fos);
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
//		 }
			return nFile;
		 }

		//取得新的單號
		public static String getNFormno(Context context,String formf){
			int flowNumber = 0;
			String msFno=Utilis.getIni(context,"SYS","DEPT",1)+Utilis.getIni(context,"SYS","DEPT",2)+formf+DateUtil.getCurrentYearFormat1().substring(0, 2);
			//未來年度 應取2碼 應該在2020年起 要改.substring(0, 2);
			SQLiteDatabase db = Utilis.getDB(context);
			try{
				Cursor cursor = db.rawQuery("select FORMNO from " + TbName.QHEAD + " where FORMNO like '"+msFno+"%' order by FORMNO DESC limit 1", null);
				if(cursor != null){
					try{
						if(cursor.getCount() > 0){
							cursor.moveToFirst();
							flowNumber = Utilis.toInt(cursor.getString(cursor.getColumnIndex("FORMNO")).substring(msFno.length()))+1;
						}
					}catch(Exception e){
						e.printStackTrace();
					}
					cursor.close();
				}else{ //新的開始單號
					flowNumber=1;
				}
			}catch(Exception e){
				e.printStackTrace();
			}
			if(db != null){
				db.close();
			}
			return msFno+Utilis.formatFlow(flowNumber);
		}
		
		//取得新的單號
		//預設 存在 Utilis.getIni(this,"HOST","MAXITEM",5);
		public static String getNadord(Context context){
			int flowNumber = 0;
			String msFno=Utilis.getIni(context,"HOST","MAXITEM",5);
			String mRETURN=msFno;
			SQLiteDatabase db = Utilis.getDB(context);
			try{
				Cursor csH =db.rawQuery("select EMPNAME from " + TbName.QHEAD + " where EMPNAME ='"+msFno+"' and QKIND='20' and ISCONFIRM='N' and ISCHECK='N' and ATOT<>0 order by EMPNAME DESC limit 1", null);
				//先以預設的批號,檢查是否正在配貨中
					try{
						if(csH.getCount() > 0){
							//表示正在配貨中
							mRETURN=msFno;
						}else{
							//找尚未結案
							Cursor cs= db.rawQuery("select EMPNAME from " + TbName.QHEAD + " where QKIND='20' and ISCONFIRM='N' and ISCHECK='N' and ATOT>0 and EMPNAME>'00101001' and EMPNAME<'91231999' order by EMPNAME DESC limit 1", null);
								try{
									if(cs.getCount() > 0){
										cs.moveToFirst();
										mRETURN=cs.getString(0);
										if (!Utilis.getIni(context,"HOST","MAXITEM",5).equalsIgnoreCase(mRETURN))
											Utilis.putIni(context,"HOST","MAXITEM", mRETURN, 5);
									}else{
										//都已結案了,編新案
										msFno=DateUtil.getCurrentYearFormat1().substring(0, 6);
										Cursor cursor = db.rawQuery("select EMPNAME from " + TbName.QHEAD + " where EMPNAME like '"+msFno+"%' and QKIND='20' order by EMPNAME DESC limit 1", null);
										try{
											if(cursor.getCount() > 0){
												cursor.moveToFirst();
												flowNumber = Utilis.toInt(cursor.getString(cursor.getColumnIndex("EMPNAME")).substring(msFno.length()))+1;
											}else{ //新的開始單號
												flowNumber=1;
											}
										}catch(Exception e){
											e.printStackTrace();
										}
										cursor.close();
										mRETURN=msFno+Utilis.ordFlow(flowNumber);
										Utilis.putIni(context,"HOST","MAXITEM", mRETURN, 5);
									}
								}catch(Exception e){
									e.printStackTrace();
								}
								cs.close();
						}
					}catch(Exception e){
						e.printStackTrace();
					}
				csH.close();
			}catch(Exception e){
				e.printStackTrace();
			}
			if(db != null){
				db.close();
			}
			return mRETURN;
		}
		
		
		public static String makeSPic(Context context,String BigPic,String batch){
			 int px=210;
			 int py=280;
			 String nFile=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+getIni(context,"SYS", "YEAR",7)+File.separator+batch+"/"+BigPic.substring(BigPic.lastIndexOf("/")+1,BigPic.lastIndexOf("."))+".jpg";
//		 if(BigPic.indexOf("drawable/") < 0) {
			 File myDataPath = new File(nFile.substring(0,nFile.lastIndexOf("/")));			 
//			 myDataPath = new File(nFile.substring(0,nFile.lastIndexOf("")));			 
		        if (!myDataPath.exists()) {
		            myDataPath.mkdirs();
		          }
			 
			 Bitmap vBitmap = Bitmap.createBitmap( px,py, Bitmap.Config.RGB_565);		 
			File file = new File(BigPic);
			if ((file.exists() == true && file.length()>100000) || (nFile.equalsIgnoreCase(BigPic)==false)) {
				vBitmap=Utilis.getLimitBitmap(BigPic, px, py);
				Bitmap rsizePic=vBitmap;
					 
					 ByteArrayOutputStream stream = new ByteArrayOutputStream();
				        FileOutputStream fos = null;
						try {
							fos = new FileOutputStream(nFile);
							
						} catch (FileNotFoundException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						
				    try {
						int swidth = vBitmap.getWidth();
						int shgh = vBitmap.getHeight();
						
						Matrix scaleMatrix = new Matrix();
						scaleMatrix.postScale(1,1);
						rsizePic =Bitmap.createBitmap(vBitmap, 0, 0, swidth, shgh, scaleMatrix, true);
						rsizePic.compress(Bitmap.CompressFormat.JPEG, 100, stream);
						rsizePic.compress(CompressFormat.JPEG, 100, fos);
						fos.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
//		 }
			return nFile;
		 }

	@SuppressWarnings("unused")
	public static void startPrint(Context cnt,StringBuffer sPrintB,int Loca ){
		if (sPrintB.toString().length()>0){
//			final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(cnt, "SYS", "YEAR",7);	
			String lenS="0000"+(int)(Loca/7.32);
			sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
			sPrintB.append("E\r\n");
	        boolean Succed=false;
			String address=null;
			int port=0;
			   address = Utilis.getIni(cnt, "SYS","BAR_IP", 4);// 連線的ip
			   port =Utilis.toInt(Utilis.getIni(cnt, "SYS","BAR_IP", 5));// 連線的port
				 InetAddress serverAddr = null;
			        SocketAddress sc_add = null;
			        Socket socket = null;

						 try {
							 serverAddr = InetAddress.getByName(address);
							 sc_add= new InetSocketAddress(serverAddr,port);
								 socket = new Socket();
								 socket.connect(sc_add,6000);
								 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
								 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
								 out.write(data, 0, data.length);
								 socket.close();
								 Toast.makeText(cnt, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
								 Succed=true;
						 } catch (UnknownHostException e) {
							 Succed=false;
						 } catch (SocketException e) {
							 Succed=false;
						 } catch(IOException e) {
							 Succed=false;
						 }
			}
		
		
	}
		
	@SuppressWarnings("unused")
	public static void openCashDraw(Context cnt){
		String address=null;
		int port=0;
		   address = Utilis.getIni(cnt, "SYS","BAR_IP", 6);// 連線的ip
		   port =Utilis.toInt(Utilis.getIni(cnt, "SYS","BAR_IP", 7));// 連線的port

	 InetAddress serverAddr = null;
        SocketAddress sc_add = null;
        Socket socket = null;
		String FormD=DateUtil.getCurrentDate();  //2012/10/22
		int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
		String[] deptStr =Utilis.getIni(cnt,"SYS","DEPT",9).split("!&!");
	if (Ttime<=5)  FormD = DateUtil.addDate(FormD, -1);
	//@@2020/11/26 FormD
			 try {
				 serverAddr = InetAddress.getByName(address);
				 sc_add= new InetSocketAddress(serverAddr,port);
					 socket = new Socket();
					 socket.connect(sc_add,2000);
					 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
//					 String openDraw=""+ (char)27 + (char)112 +( char)0 + (char)25 + (char)250;
//					 byte data[] = new String(openDraw.getBytes("UTF8")).getBytes("BIG5");
					 byte data[] = new String(((char)27+"p"+(char)0+(char)100+(char)250).getBytes("UTF8")).getBytes("BIG5");
					 out.write(data, 0, data.length);
					 socket.close();
						SQLiteDatabase db = Utilis.getDB(cnt);
						ContentValues value = new ContentValues();
				    	value.put("TR", "0");
				    	value.put("ID", 0);
				    	value.put("QKIND", "80");
				    	value.put("FORMNO", deptStr[0]+deptStr[1]+"8"+DateUtil.getCurrentYearFormat1().substring(0, 2));
				    	value.put("FORMDATE", FormD);
				    	value.put("CTIME", DateUtil.getSystemTime().substring(2,14));
				    	value.put("UTIME", DateUtil.getSystemTime().substring(2,14));
				    	value.put("ISCONFIRM", "Y"); //"O"
				    	value.put("QATYPE", "開櫃紀錄");
				    	value.put("QNOM", "9600");
				    	value.put("QNOI", "");
				    	value.put("PS", "");
				    	value.put("MOUT", 0);
				    	value.put("MINTO", 0);
				    	value.put("MBEFORE", 0);
				    	value.put("MBALANCE", 0);
				    	value.put("MBETWEEN", 0);
				    	value.put("MAFTER", 0);
				    	value.put("DEPTNO", deptStr[0]);
				    	value.put("DEPTNAME", deptStr[2]);
				    	value.put("DEVISE", deptStr[1]);
				    	value.put("ATMNO", "");
				    	value.put("ATMNAME", "");
				    	value.put("ATMDATE", "");
				    	value.put("EMPID", "000");
				    	value.put("EMPNAME", "錢櫃開了");
				    	value.put("PIC", "drawable.icon");
				    	value.put("BANKNAME", deptStr[0]+deptStr[1]);

				    	long result = db.insert(TbName.QMACC, null, value);
				    	
				    	db.close();
					 
					 Toast.makeText(cnt, "錢櫃開啟了!!", Toast.LENGTH_LONG).show();
					 //無條件存入一筆 qmacc 開櫃紀錄
					 //收支代碼 9600 以當下直接儲存一筆

			 } catch (UnknownHostException e) {

			 } catch (SocketException e) {
				 Toast.makeText(cnt, "錢櫃連線失敗!!", Toast.LENGTH_LONG).show();
			 } catch(IOException e) {
				 Toast.makeText(cnt, "關鍵檔案開啟失敗!!", Toast.LENGTH_LONG).show();
			 }
	}

	// 顯示 SpinerDialog
	public static void showDialogCancel(Context cnt, String title, int select,
			final String[] array, final IDialog callback) {
		new AlertDialog.Builder(cnt)
				.setTitle(title)
				.setSingleChoiceItems(array, select,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// ((TextView)findViewById(R.id.text_choice)).setText(strString[which]);
								callback.onDialogFinish(which, array[which]);
								dialog.dismiss();
							}
						})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				}).create().show();
	}
}