package com.cwbuyer.main;

import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
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.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.cwbuyer.adapter.SizeAdapter;
import com.cwbuyer.adapter.TableAdapter.TableCell;
import com.cwbuyer.adapter.TableAdapter.TableRow;
import com.cwbuyer.format.DefaultData;
import com.cwbuyer.format.IReqCallback;
import com.cwbuyer.format.ItemData;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DBUtil;
import com.cwbuyer.lib.DialogUtilis;
import com.cwbuyer.lib.MakeTransDetail;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;


// 進貨!
// 先尺寸!
@SuppressWarnings("unused")
public class AIncomePc extends Activity{
	
	private int mMode = IncomeMode.Size;
	private LinearLayout lTableView = null;
	private LinearLayout mLayoutColor = null;
	private LinearLayout mLayoutCount = null;
	private LinearLayout mLayoutSize = null;
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	final String filepath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator + "CWBuyer";
	private DefaultData mDefaultData = null; // 採購參數
	private final String [] DISC  =Utilis.getIni(this, "QRP", "5X2QR",9).split("!&!");
	private final String [] backup=Utilis.getIni(this, "SYS","BACKOUT",9).split("!&!");
	private String[] DSend = Utilis.getIni(this,"SYS","DEPT_SEND",9).split("!&!"); 
	private LinearLayout mLayoutRoot = null;
	private ListView mSizeList = null;
	
	private ColorAdapter mColorAdapter = null;
	private SizeAdapter mSizeAdapter = null;
	private String mSize = null;
	
	private int mChoiceMode = ChoiceMode.NORMAL;
	private int mCountMode = CountMode.PLUS;
	private int mAddValue = 0;
	int tableHeight=80;
	int tabless=8;	
	
	String aInput="";
	private EditText mInput = null;
	private TextView mDiscount = null;
	private TextView mUnitprice = null;
	private Button BD1;
	private Button BD2;
	private Button BD3;
	private Button BD4;
	private Button BD5;
	private Button BD6;
	private Button BD7;
	private Button BD8;
	private Button BD9;

	private StringBuffer mBuf = new StringBuffer();
	
	LinkedList<String> mSizeLink = new LinkedList<String>();
	LinkedList<String> mColorLink = new LinkedList<String>(); 
	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 列資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 行資料
	
	private HashMap<Integer, Integer>  mColorCheckList = new HashMap<Integer,Integer>();
	LinkedList<String> mColorName = new LinkedList<String>();  
//	ArrayList<Integer> mColorCheckList = new ArrayList<Integer>();
	
	private int mMID = 0;
	private String mKind = "30"; //預設為總店倉銷貨單
	private String mBatch=null;
	private int mCong=1;
	private int mItemMode = 0;  //0.新增商品 1.編輯商品 2.單據展開 3.QDETAIL印條碼 4.QITEMS印條碼
	private int nbar=0;
	private int nUnit=1; // 件/段 自動判斷
	private int isUnit=0; //0件 1段 
	private final String[] barStr =Utilis.getIni(this,"SYS","BAR_IP",9).split("!&!");
	private static final String[] season = { "春夏","春夏","秋","秋冬","四季"};
	private int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5)); //0OK 1密碼不符

	private ItemData mItemData = null;
	
	private String mSplitSizes;
	private String mSplitColorNo;
	private String mSplitColor;
	private String mCountList;
	private double dDiscount=0;
	private double dUnitprice=0;
	private ArrayList<String> mArrayColorNumber = new ArrayList<String>();
	private ArrayList<String> mArrayColorName = new ArrayList<String>();
	private int mViewMode = 0;
	int Wheight;
	int Wwidth;
	
	class SizeData {
		int id;
		String strSize;
	}
	
	public class ColorData{
		int id;
		String name;
		String number;
		int color;
	}
	
	public interface ViewMode{
		int NORMAL = 0;
		int DIRECT = 1;
	}
	
	class IncomeData{
		int nColor = 0;
		String strColor = null;
		ArrayList<Integer> countlist = new ArrayList<Integer>();
	}
	
	public interface ChoiceMode{
		int NORMAL = 0; //單選   	ok
		int ROW = 1; // 列選      	ok
		int CELL = 2; // 行選	
		int ALL = 3; //全選
		int EDIT = 6; //
	}
	
	public interface IncomeMode{
		int Size = 0;
		int Color = 1;
		int Count = 2;
	}
	
	public interface CountMode{
		int PLUS = 0;
		int NEGATIVE = 1;
	}
	
	@SuppressWarnings("deprecation")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.income_layout);

		DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        Wwidth = dm.widthPixels;
        Wheight = dm.heightPixels;
		tableHeight=(int) (Wheight/16);
		if (Wwidth<=800) tabless=(int) (Wwidth/100)+2; else  tabless=(int) (Wwidth/140)+1;
        mMID = getIntent().getIntExtra("mid",0);
        mBatch = getIntent().getStringExtra("batch"); // qitems主貨編號   or   qdetailMID
        mItemMode = getIntent().getIntExtra("item_mode", 0);
        mCong=getIntent().getIntExtra("cong",1);  //預設為顯示單價 折數
        nUnit = getIntent().getIntExtra("unit",1);
        if (nUnit<=1) {nUnit=1;isUnit=0;} else  isUnit=1;
        if (isUnit==0) ((Button)findViewById(R.id.btn_unit)).setText("件"); else  ((Button)findViewById(R.id.btn_unit)).setText(""+nUnit+"段");

        mSplitSizes = getIntent().getStringExtra("size");
        mSplitColorNo = getIntent().getStringExtra("colorno");
        mSplitColor = getIntent().getStringExtra("color");
        mCountList = getIntent().getStringExtra("countlist");
        
        mKind = getIntent().getStringExtra("mkind");  //GalleryViewP專用
        // 2GalleryViewP (3ManageItem 4QPosff)   0.ADD 1.EDIT_Aitem
        dUnitprice = getIntent().getDoubleExtra("unitprice",0);
        dDiscount = getIntent().getDoubleExtra("discount",0);
		
	   	nbar=Utilis.toInt(barStr[7]); if (nbar==0) nbar=1;
        if(mItemMode ==2){
        	((Button)findViewById(R.id.btn_size)).setVisibility(View.INVISIBLE);
        	((Button)findViewById(R.id.btn_color)).setVisibility(View.INVISIBLE);
        	((Button)findViewById(R.id.btn_count)).setVisibility(View.INVISIBLE);
        }else if(mItemMode ==5){  //來自3QDETAIL 4QITEMS 5
        	((Button)findViewById(R.id.btn_size)).setText("吊牌1");
       		((Button)findViewById(R.id.btn_color)).setText("吊牌2");
       		((Button)findViewById(R.id.btn_count)).setText("條碼3");
    		getDefaultData();
        }else if(mItemMode ==3 || mItemMode ==4){  //來自3QDETAIL 4QITEMS 5
        	((Button)findViewById(R.id.btn_size)).setText("吊牌1");
       		((Button)findViewById(R.id.btn_color)).setText("吊牌2");
       		((Button)findViewById(R.id.btn_count)).setText("條碼3");
       		((Button)findViewById(R.id.btn_save)).setText("條碼4");
    		getDefaultData();
    		
       	//}else if(mItemMode ==5 ){
    		//純粹就是將 輸入的部分 傳回 就可以了
        }
        
        // 設定顏色的 Grid
        GridView grid = (GridView)findViewById(R.id.gridview);
        mColorAdapter = new ColorAdapter(this);
    	grid.setAdapter(mColorAdapter);
       	//代表這是有正確的顏色尺寸表,可以直接展現TABLE表
    	if ( mSplitColorNo.equalsIgnoreCase("YN") &&  mSplitSizes.equalsIgnoreCase("F") 
		&& (mCountList == null || mCountList.equalsIgnoreCase("0"))){
    	if (backup[1].equalsIgnoreCase("1")) mSplitColorNo="00";
    		mViewMode = ViewMode.NORMAL;
    	}else{	
        	mViewMode = ViewMode.DIRECT;
        	// 處理資料
        	mSize = mSplitSizes;
        	String[] numbers = mSplitColorNo.split("，");
        	String[] names = mSplitColor.split("，");        	
        	for(int i = 0; i < numbers.length; i++){
        		mArrayColorNumber.add(numbers[i]);
        		mArrayColorName.add(names[i]);
        		int suss=0;
        		for (int j=0;j<mColorAdapter.getCount();j++){
        			if (mColorAdapter.getColorNumber(j).equalsIgnoreCase(numbers[i])){
        				mColorCheckList.put(j, 1);  //放入每個顏色位址=0
        				suss=1;
        				//要由色盤找到position 而不是存入I
        			}
        		}
        		if (suss==0)  mColorCheckList.put(i, 1);  //不得已
        	}
    	}
        
        
        lTableView = (LinearLayout)findViewById(R.id.tableview);
        mMode = getIntent().getIntExtra("income_mode", IncomeMode.Size);
        lTableView.setVisibility(View.GONE);
        
        mLayoutColor = (LinearLayout)findViewById(R.id.layout_color);
        mLayoutColor.setVisibility(View.GONE);
        
        mLayoutSize = (LinearLayout)findViewById(R.id.layout_size);
        mLayoutSize.setVisibility(View.VISIBLE);
        
        // 先設定 Size 的 Layout
        mSizeAdapter = new SizeAdapter(this);
        mSizeList = (ListView)findViewById(R.id.list_size);
        mSizeList.setVisibility(View.VISIBLE);
        mSizeList.setAdapter(mSizeAdapter);
        mSizeList.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int pos, long arg3) {
				String size = mSizeAdapter.getSize(pos);
				((TextView)findViewById(R.id.text_size)).setText("目前選中: " + size);
				Toast.makeText(AIncomePc.this, "目前選中 : " + size, Toast.LENGTH_SHORT).show();
				mSize = size;
				// 選擇之後馬上跳 Color
				changeMode(IncomeMode.Color);
			}
    	});
        
    	// 設定計算進貨
    	mLayoutCount = (LinearLayout)findViewById(R.id.layout_count);
    	InputFilter[] FilterArray = new InputFilter[1];
    	FilterArray[0] = new InputFilter.LengthFilter(8); // 加入正負號
    	mInput = (EditText)findViewById(R.id.text_print);
    	mDiscount = (TextView)findViewById(R.id.text_discount);
    	mUnitprice = (TextView)findViewById(R.id.text_price);
		BD1= (Button)findViewById(R.id.btn_disc1);
		BD1.setText(DISC[0]);
		BD2= (Button)findViewById(R.id.btn_disc2);
		BD2.setText(DISC[1]);
		BD3= (Button)findViewById(R.id.btn_disc3);
		BD3.setText(DISC[2]);
		BD4= (Button)findViewById(R.id.btn_disc4);
		BD4.setText(DISC[3]);
		BD5= (Button)findViewById(R.id.btn_disc5);
		BD5.setText(DISC[4]);
		BD6= (Button)findViewById(R.id.btn_disc6);
		BD6.setText(DISC[5]);
		BD7= (Button)findViewById(R.id.btn_disc7);
		BD7.setText(DISC[6]);
		BD8= (Button)findViewById(R.id.btn_disc8);
		BD8.setText(DISC[7]);
		BD9= (Button)findViewById(R.id.btn_disc9);
		BD9.setText(DISC[8]);
    	mInput.setFilters(FilterArray);
    	mInput.addTextChangedListener(watcherCount);
    	mDiscount.setFilters(FilterArray);
    	mUnitprice.setFilters(FilterArray);

    	if (PSWD!=0 && (mKind.equalsIgnoreCase("10") || mKind.equalsIgnoreCase("20") || mKind.equalsIgnoreCase("21"))){
      		mDiscount.setVisibility(View.INVISIBLE);
    		mUnitprice.setVisibility(View.INVISIBLE);
    		BD1.setVisibility(View.INVISIBLE);
    		BD2.setVisibility(View.INVISIBLE);
    		BD3.setVisibility(View.INVISIBLE);
    		BD4.setVisibility(View.INVISIBLE);
    		BD5.setVisibility(View.INVISIBLE);
    		BD6.setVisibility(View.INVISIBLE);
    		BD7.setVisibility(View.INVISIBLE);
    		BD8.setVisibility(View.INVISIBLE);
    		BD9.setVisibility(View.INVISIBLE);
    	}
    	
    	SQLiteDatabase db = Utilis.getDB(this);
    	String mPics="";
    	Cursor cs=null;
		cs =db.rawQuery("select PIC from qdetail where GOODSNO='"+mBatch+"' order by MID desc limit 1", null); 
    	if (cs.getCount()>0){
    		cs.moveToFirst();
    		mPics=cs.getString(cs.getColumnIndex("PIC"));
    	}
    	db.close();
    	cs.close();
    	
		if (mPics==null || mPics.length()<=0) mPics=filepath+"/para/img_additem.png";
		File localFile = new File(mPics);
		if (localFile.exists()){
			BitmapDrawable d = new BitmapDrawable(mPics);
   			((LinearLayout)findViewById(R.id.tableview)).setBackgroundDrawable(d);
		}
		
		mBuf.append(""); //[R]
		mInput.setText("");
		if (mCong!=0){
			mDiscount.setText(String.valueOf(dDiscount));
			mUnitprice.setText(String.valueOf(dUnitprice));
			mDiscount.setOnClickListener(new MainClick());
			mUnitprice.setOnClickListener(new MainClick());
			BD1.setOnClickListener(new MainClick());
			BD2.setOnClickListener(new MainClick());
			BD3.setOnClickListener(new MainClick());
			BD4.setOnClickListener(new MainClick());
			BD5.setOnClickListener(new MainClick());
			BD6.setOnClickListener(new MainClick());
			BD7.setOnClickListener(new MainClick());
			BD8.setOnClickListener(new MainClick());
			BD9.setOnClickListener(new MainClick());
		}
        ((Button)findViewById(R.id.btn_size)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_color)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_count)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_save)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_unit)).setOnClickListener(new MainClick());       
        ((Button)findViewById(R.id.btn_number_0)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_1)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_2)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_3)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_4)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_5)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_6)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_7)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_8)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_number_9)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_opreate_plus)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_cell)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_row)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_all)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_choice_single)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_clean_number)).setOnClickListener(processListener);
		((Button)findViewById(R.id.btn_save_item)).setOnClickListener(processListener);
		
		((Button)findViewById(R.id.btn_opreate_plus)).setOnLongClickListener(new MainLongClick());
		
		if(mViewMode == ViewMode.DIRECT){
			changeMode(IncomeMode.Count);
		}

		mInput.setOnKeyListener(new View.OnKeyListener() {
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
			//監視鍵盤按鍵
			if(event.getAction()== KeyEvent.ACTION_DOWN){ 
					if  (keyCode==KeyEvent.KEYCODE_ENTER && mInput.getText().toString().length()>0){
							aInput=mInput.getText().toString();  //未來設置全大寫開關(許先生貨號有小寫英文為供應商代號)
							//將進行 table 第一欄位 輸入數值
							//如果單一顏色尺寸,直接帶回
							for(int nRow = 1; nRow < mCountRow.size(); nRow++){
								int nCellKey = mCountRow.get(nRow);
								for(int i = 2 ; i < mSizeLink.size(); i++){
									int value = Utilis.toInt(aInput);
									mCountCell.remove(nCellKey + i);
									mCountCell.put(nCellKey + i, String.valueOf(value));
									TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + i);
									view.setText("" + value);
								}
							}
							cleanNumber();
							
							((Button)findViewById(R.id.btn_save)).requestFocus();
						return false;
					}else if (keyCode==KeyEvent.KEYCODE_Q){
						finish();
					}
			}
			return false;
			}
		});
/*		
		((Button)findViewById(R.id.btn_choice_cell)).setOnFocusChangeListener(new View.OnFocusChangeListener(){
			  public void onFocusChange(View view, boolean hasFocus){
			    if(hasFocus){
			    	mInput.requestFocus();
			    } else {
			    }
			  }
			});		
		mInput.requestFocus();
*/
    }
	
	class MainLongClick implements OnLongClickListener { //目前為(-)長按觸發(將目前存貨都視為[全退])
		@Override
		public boolean onLongClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AIncomePc.this);
			switch (id) {
				case R.id.btn_opreate_plus:
				{
					if (mKind.equalsIgnoreCase("10") && mBatch.length()>0 && mItemMode==2){ //來自廠商進貨單全退
						SQLiteDatabase db = Utilis.getDB(AIncomePc.this);
						Cursor cs =db.rawQuery("select COLOR, UNIT1, SIZE, sum(UNIT10) as SUM1, sum(UNIT30) as SUM3, sum(UNIT40) as SUM4 from qitems " +
								"where GOODSNO='"+mBatch+"' group by COLOR, UNIT1, SIZE", null); 
						if (cs.getCount()>0){//逐筆讀取各色尺寸的進銷存
							cleanNumber();		onSetAll();  //全數歸零
							cs.moveToFirst();
							for (int xx=0;xx<cs.getCount();xx++){
								int colchk=-1; int sizchk=-1;
								for (int i=0;i<mArrayColorNumber.size();i++){
									if(mArrayColorNumber.get(i).equalsIgnoreCase(cs.getString(0))){
										colchk=i;
										break;
									}
								}	
								for (int k=2;k<mSizeLink.size();k++){
									if (mSizeLink.get(k).equalsIgnoreCase(cs.getString(2))){
										sizchk=k;
										break;
									}
								}
								if (colchk<0){//現有的顏色表不存在,需增設
									mArrayColorNumber.add(cs.getString(0));
									mArrayColorName.add(cs.getString(1));
									colchk=mArrayColorNumber.size()-1;
									mCountCell.put(colchk * 100  ,cs.getString(0));
									mCountCell.put(colchk * 100 +1 ,cs.getString(1));
//									for (int k=2;k<mSizeLink.size();k++){
										//mCountCell.put((colchk+1) * 100 + k,"0");
									for (int k=2;k<=mSizeLink.size()+1;k++){  //200_COLNO 201_COLNA 202_S 203_M 204_L										
										mCountCell.put((colchk) * 100 + k,"0");
									}
								}
								if (sizchk<0){//現有的尺寸表不存在,需增設
									mSizeLink.add(cs.getString(2));
									sizchk=mSizeLink.size()-1;
									//mCountCell.put(sizchk,cs.getString(2));									
									//for (int i=1;i<mArrayColorNumber.size();i++){
										//mCountCell.put(i * 100 +sizchk ,"0");
									for (int i=0;i<mArrayColorNumber.size();i++){
										mCountCell.put(i * 100 +sizchk+2 ,"0");
									}
								}
								//完整的表檔中,存入件數,且為(-)
								if ((cs.getInt(3)-cs.getInt(4)-cs.getInt(5))!=0){
								 mCountCell.put((colchk+1) * 100 + sizchk, "-"+(cs.getInt(3)-cs.getInt(4)-cs.getInt(5)));	
								}
								cs.moveToNext();
							}
						}
						db.close();
						cs.close();
					}
					//如何讓TABLE_UPDATE
					if(mLayoutRoot != null){
						mLayoutRoot.removeAllViews();
					}
					
		        	ArrayList<TableRow> table = new ArrayList<TableRow>();
//		        	int width = AIncomePc.this.getWindowManager().getDefaultDisplay().getWidth()/6 - 8;
		        	// 先新增 TableCell[]
		        	// 再新增 TableRow
		        	// 最後再 加入 Table
		        	for(int i = 0; i <= mArrayColorNumber.size(); i++){
		        		TableCell[] titles = new TableCell[mSizeLink.size()];
		        		for(int k = 0; k < titles.length; k++){
		        			titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.IMAGE);
		        		} 
		        		table.add(new TableRow(titles));
		        	}
		        	
		        	TableRow tableRow = table.get(0);
		        	
		        	for(int i = 0; i <= mArrayColorNumber.size(); i ++){
		        		TableRowView row = new TableRowView(AIncomePc.this, tableRow, i);
		        		mLayoutRoot.addView(row);
		        	}
					
					break;
				}
			}
			return false;
		}
	}

	private ProcessKeypadInput processListener = new ProcessKeypadInput();
	
	class ProcessKeypadInput implements OnClickListener{
		@Override
		public void onClick(View v) {
			Utilis.runVibrate(AIncomePc.this);
			int id = v.getId();
			switch(id){
			case R.id.btn_number_0:
				processNumber("0");
				break;
			case R.id.btn_number_1:
				processNumber("1");
				break;
			case R.id.btn_number_2:
				processNumber("2");
				break;
			case R.id.btn_number_3:
				processNumber("3");
				break;
			case R.id.btn_number_4:
				processNumber("4");
				break;
			case R.id.btn_number_5:
				processNumber("5");
				break;
			case R.id.btn_number_6:
				processNumber("6");
				break;
			case R.id.btn_number_7:
				processNumber("7");
				break;
			case R.id.btn_number_8:
				processNumber("8");
				break;
			case R.id.btn_number_9:
				processNumber("9");
				break;
			case R.id.btn_opreate_plus:
//				processOpreate("+");
				if(mCountMode == CountMode.PLUS){
					mCountMode = CountMode.NEGATIVE; // 負的
					((Button)findViewById(R.id.btn_opreate_plus)).setText("-");
//					mInput.setTextColor(Color.RED);
//					mBuf.append("-", 0, 1);
					int value = Utilis.toInt(mBuf.toString());
					if(value > 0){
						mBuf.delete(0, mBuf.length());
						mBuf.append((0 - value));
					}
					mInput.setText(mBuf.toString());
				}else{
					mCountMode = CountMode.PLUS;	// 正的
					((Button)findViewById(R.id.btn_opreate_plus)).setText("+");
//					mInput.setTextColor(Color.rgb(0, 100, 0));
					try{
//						mBuf.append("", 0, 1);
						int value = Utilis.toInt(mBuf.toString());
						if(value < 0){
							mBuf.delete(0, mBuf.length());
							mBuf.append((0 - value));
						}
						mInput.setText(mBuf.toString());
					}catch(Exception e){
						e.printStackTrace();
					}
				}
				
				// 處理 TextView 的數值
//				mBuf.append("1");
				break;
			case R.id.btn_choice_cell:

				clearAllBackground();
				((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_count_focus);
				mChoiceMode = ChoiceMode.CELL;
				break;
			case R.id.btn_choice_row:

				clearAllBackground();
				((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_count_focus);
				mChoiceMode = ChoiceMode.ROW;
				break;
			case R.id.btn_choice_all:
				onSetAll();
				cleanNumber();
				break;
			case R.id.btn_choice_single:

				clearAllBackground();
				((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_count_focus);
				mChoiceMode = ChoiceMode.NORMAL;
				break;
			case R.id.btn_clean_number:
				cleanNumber();
				break;
			case R.id.btn_save_item:
				finish();
				break;
			}
		}
	}
	
	private void clearAllBackground(){
		((Button)findViewById(R.id.btn_choice_all)).setBackgroundResource(R.drawable.keypad_count2);
		((Button)findViewById(R.id.btn_choice_cell)).setBackgroundResource(R.drawable.keypad_count2);
		((Button)findViewById(R.id.btn_choice_row)).setBackgroundResource(R.drawable.keypad_count2);
		((Button)findViewById(R.id.btn_choice_single)).setBackgroundResource(R.drawable.keypad_count2);
	}
	
	public void processNumber(String number){
		if(mBuf.length() < 5){
			if(mBuf.length() > 0 && mBuf.charAt(0) == '0'){
				mBuf.delete(0, 1);
			}
			mBuf.append(number);
			mInput.setText(mBuf.toString());
		}else{
		    Toast.makeText(this, "超過顯示位數", Toast.LENGTH_SHORT).show();
		}
	}
	
	public void cleanNumber(){
		int len = mBuf.length();
		if(len > 0){
			mBuf.delete(0, len);
		}
//		mBuf.append("0");
		mInput.setText("0");
	}

	
	private void changeMode(int mode){
		if(mode != mMode){
			// 先判斷如果是 Count 就要跳出 Dialog
			mMode = mode;
			switch(mode){
				case IncomeMode.Size:
				{
					// Size Visible
					mLayoutSize.setVisibility(View.VISIBLE);
					mLayoutColor.setVisibility(View.GONE);
					mLayoutCount.setVisibility(View.GONE);
					lTableView.setVisibility(View.GONE);
					break;
				}
				case IncomeMode.Color:
				{
					mLayoutSize.setVisibility(View.GONE);
					mLayoutColor.setVisibility(View.VISIBLE);
					mLayoutCount.setVisibility(View.GONE);
					lTableView.setVisibility(View.GONE);
					break;
				}
				case IncomeMode.Count:
				{
					if(mLayoutRoot != null){
						mLayoutRoot.removeAllViews();
					}
					
					mLayoutSize.setVisibility(View.GONE);
					mLayoutColor.setVisibility(View.GONE);
					mLayoutCount.setVisibility(View.VISIBLE);
					lTableView.setVisibility(View.VISIBLE);
		        	((LinearLayout)findViewById(R.id.layout_count)).setVisibility(View.VISIBLE);
		        	
		        	mLayoutRoot = (LinearLayout)findViewById(R.id.root);
		        	
		        	if(mSizeLink != null){
		        		mSizeLink.clear();
		        	}
		        	mCountRow.clear();
		        	mCountCell.clear();
		        	
		        	mSizeLink.add("代碼"); // 顏色
		        	mSizeLink.add("顏色"); // 尺寸
		        	// 設定 Title 行 mSizeLink==('代碼','顏色','35','36','37',.....)
		        	String[] sizes = mSize.split(",");
		        	for(int i = 0; i < sizes.length; i++){
		        		mSizeLink.add(sizes[i]);
		        	}
		        	// 設定初始Row 列
		        	for(int i = 0; i <= mArrayColorNumber.size(); i++){
		        		// 設定Row會包含哪些 Key
		        		mCountRow.put(i, i * 100);
		        		for(int k = 0; k < mSizeLink.size(); k ++){
			        		if( i == 0){
			        			mCountCell.put(i * 100 + k, mSizeLink.get(k));
			        		}else{ // 第二列以後
			        			if( k == 0){ // 新增號碼
			        					mCountCell.put(i * 100 + k, mArrayColorNumber.get(i - 1));
			        			}else if( k == 1){ // 新增顏色名稱
			        					mCountCell.put(i * 100 + k, mArrayColorName.get(i - 1)); 
			        			}else{ // 初始化各個值
			        				mCountCell.put(i * 100 + k, "0");
			        			}
			        		}
		        		}
		        	}
		        	if(mViewMode == ViewMode.DIRECT){ 
    					// 復原值
		        		try{
				        	String[] numberLevel1 = mCountList.split("，");
			        		int chk=0;
				        	if (isUnit==1){//需檢查是否為整除的,再換算為手
					        	for(int nRow = 1; nRow < mCountRow.size(); nRow++){
					        		String[] numberLevel2 = numberLevel1[nRow - 1].split(",");
					        		for (int xx=0;xx<numberLevel2.length;xx++){
						        		if(Utilis.toInt(numberLevel2[xx])!=0){
						        			if ((Utilis.toInt(numberLevel2[xx]) % nUnit)!=0)
						        				chk=1;break;
						        		}
					        		}
					        		if (chk==1) break;
					        	}
				        	}
				        	if (chk==1 || nUnit<=1){//表示需由(段)改為(件)
				        		isUnit=0;
				        		((Button)findViewById(R.id.btn_unit)).setText("件");				        		
				        	} else{
				        		isUnit=1;
				        		((Button)findViewById(R.id.btn_unit)).setText(""+nUnit+"段");				        		
				        	}

				        	for(int nRow = 1; nRow < mCountRow.size(); nRow++){
				        		String[] numberLevel2 = numberLevel1[nRow - 1].split(",");
				        		int nLevel2 = 0;
				    			int nCellKey = mCountRow.get(nRow);
				    			for(int i = 2 ; i < mSizeLink.size(); i++){
				    				if(nLevel2 < numberLevel2.length){
					    				int value =Utilis.toInt(numberLevel2[nLevel2]);
					    				if (isUnit==1) value=Utilis.toInt(numberLevel2[nLevel2])/nUnit;
				    					mCountCell.put(nCellKey + i, ""+value);
				    				}
				    				nLevel2++;
				    			}
				    		}
		        		}catch(Exception e){
		        			e.printStackTrace();
		        		}
		        	}
		        	
		        	ArrayList<TableRow> table = new ArrayList<TableRow>();
		        	// 先新增 TableCell[]
		        	// 再新增 TableRow
		        	// 最後再 加入 Table
		        	for(int i = 0; i <= mArrayColorNumber.size(); i++){
		        		TableCell[] titles = new TableCell[mSizeLink.size()];
		        		for(int k = 0; k < titles.length; k++){
		        			titles[k] = new TableCell((Wwidth/tabless)-8,tableHeight,TableCell.IMAGE);
		        		}
		        		table.add(new TableRow(titles));
		        	}
		        	
		        	TableRow tableRow = table.get(0);
		        	
		        	for(int i = 0; i <= mArrayColorNumber.size(); i ++){
		        		TableRowView row = new TableRowView(this, tableRow, i);
		        		mLayoutRoot.addView(row);
		        	}
		            // 暫時拿掉
//		            TableAdapter tableAdapter = new TableAdapter(this, table);
//		            tableAdapter.setData(mCountRow, mCountCell);
//		            ListView listview = (ListView)findViewById(R.id.ListView01);
//		            listview.setAdapter(tableAdapter);
		        	break;
		        	
		        } // end case 
			}
		}
	}
	
	public class TableRowView extends LinearLayout {  
        public TableRowView(Context context, TableRow tableRow, int position) {  
            super(context);  
            this.setOrientation(LinearLayout.HORIZONTAL);  
            for (int i = 0; i < tableRow.getSize(); i++) { 
                TableCell tableCell = tableRow.getCellValue(i);  
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(  
                        tableCell.width, tableCell.height);  
                layoutParams.setMargins(0, 0, 1, 1);  
                EditText textCell = new EditText(context);  
                    textCell.setSingleLine();
                    textCell.setGravity(Gravity.CENTER);  
                    textCell.setBackgroundColor(Color.WHITE);
                    if(mCountRow.containsKey(position) == true){
                    	int key = mCountRow.get(position);
                    	if( mCountCell.containsKey(key + i)){
                    		textCell.setText(String.valueOf(mCountCell.get(key + i)));
                    	}else{
                    		textCell.setText("X");
                    	}
                    }else{
                    	textCell.setText("X");
                    }
                    textCell.setId(position * 100 + i);
                    textCell.setTextColor(Color.BLACK);
                    if(position >=1 && i >= 2){
                    	textCell.setOnClickListener(new Clickable(position,i));
                    	textCell.setOnKeyListener(new ClickDown(position,i));
                    	textCell.setInputType(InputType.TYPE_CLASS_PHONE);
                    	textCell.setBackgroundResource(R.drawable.keypad_table);
                    	if (position ==1 && i == 2) {
                    		textCell.setSelection(0,textCell.getText().toString().length());
                    		textCell.requestFocus();
                    	}
                    }else  if(position > 0 && i ==0){  //
                    	String colorN=DBUtil.ColorGetTxt(AIncomePc.this,textCell.getText().toString());
                    	String [] colors=colorN.split(";");
                    	textCell.setBackgroundColor(Utilis.toInt(colors[2]));
                    	textCell.setClickable(false);
                    }else{
                    	textCell.setBackgroundColor(Color.rgb(208, 208, 208));
                    	textCell.setClickable(false);
                    }
                    
                    addView(textCell, layoutParams);  
//                } 
            }  
            this.setBackgroundColor(Color.BLACK);
        }  
    }
	
	class Clickable implements OnClickListener{
    	private int mRow;
    	private int mCell;
    	Clickable(int row, int cell){
    		mRow = row;
    		mCell = cell;
    	}
		@Override
		public void onClick(View v) {
			int id = v.getId();
			handleCount(id, mRow, mCell, mChoiceMode);
//			Toast.makeText(AIncomePc.this, "Click " + mRow + " , " + mCell, Toast.LENGTH_SHORT).show();
		}
    }

	class ClickDown implements OnKeyListener{
    	private int mRow;
    	private int mCell;
    	ClickDown(int row, int cell){
    		mRow = row;
    		mCell = cell;
    	}
		@Override
		public boolean onKey(View v, int keyCode, KeyEvent event) {
			 if(event.getAction()== KeyEvent.ACTION_DOWN){
					//if  (keyCode==KeyEvent.KEYCODE_ENTER || keyCode==KeyEvent.KEYCODE_DPAD_LEFT || keyCode==KeyEvent.KEYCODE_DPAD_RIGHT  || keyCode==KeyEvent.KEYCODE_DPAD_DOWN || keyCode==KeyEvent.KEYCODE_DPAD_UP){
						int id = v.getId();
						mChoiceMode=ChoiceMode.EDIT;
						onEDIT(id, mRow, mCell, keyCode);
						return true;
					//}
//			 }else if (keyCode == KeyEvent.KEYCODE_0 || keyCode == KeyEvent.KEYCODE_1 ||keyCode == KeyEvent.KEYCODE_2 ||keyCode == KeyEvent.KEYCODE_3 ||keyCode == KeyEvent.KEYCODE_4 ||keyCode == KeyEvent.KEYCODE_5 ||keyCode == KeyEvent.KEYCODE_6 ||keyCode == KeyEvent.KEYCODE_7 ||keyCode == KeyEvent.KEYCODE_8 ||keyCode == KeyEvent.KEYCODE_9 ){
//				Toast.makeText(AIncomePc.this, "目前鍵入 : " + keyCode, Toast.LENGTH_SHORT).show();
//				return true;
			 }

			return false;
		}
    }
	
	private void onEDIT(int id,int row,int cell,int keyCode){
		int nCellKey = mCountRow.get(row);
		EditText view = (EditText)mLayoutRoot.findViewById(id);
		int value =Utilis.toInt(view.getText().toString());
		int finish=0;
		mCountCell.remove(nCellKey + cell);
		mCountCell.put(nCellKey + cell, String.valueOf(value));
		int nRow=row;
		int nCell=cell;
		if  (keyCode==KeyEvent.KEYCODE_ENTER  || keyCode==KeyEvent.KEYCODE_DPAD_RIGHT){
			if ((cell+1)<mSizeLink.size()){
				nCell =cell+1;
			}else{nCell=2;	
				if ((row+1)<mCountRow.size())	nRow=row+1;	else	{finish=1;}
			}
		}else if  (keyCode==KeyEvent.KEYCODE_DPAD_LEFT){
			if ((cell-1)<=mSizeLink.size()){
				nCell =cell-1;
			}else{nCell=2;	
				if ((row-1)>=mCountRow.size())	nRow=row-1;	else	{finish=1;}
			}
		}else if  (keyCode==KeyEvent.KEYCODE_DPAD_UP){
			if ((row-1)<=mCountRow.size())	nRow=row-1;
		}else if  (keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
			if ((row+1)<mCountRow.size())	nRow=row+1;
		}
		if (finish==0){
		int nid=(nRow)*100+nCell;
		EditText nview = (EditText)mLayoutRoot.findViewById(nid);
		nview.setSelection(0,nview.getText().toString().length());
		nview.requestFocus();
		}else
		((Button)findViewById(R.id.btn_save)).requestFocus();
	}
	// 全選使用
	private void onSetAll(){
		// 去掉頭兩個值
		mAddValue = Utilis.toInt(mBuf.toString());
		for(int nRow = 1; nRow < mCountRow.size(); nRow++){
			int nCellKey = mCountRow.get(nRow);
			for(int i = 2 ; i < mSizeLink.size(); i++){
				int value = Utilis.toInt(mCountCell.get(nCellKey + i));
				value = mAddValue;
				mCountCell.remove(nCellKey + i);
				mCountCell.put(nCellKey + i, String.valueOf(value));
				EditText view = (EditText)mLayoutRoot.findViewById(nCellKey + i);
				view.setText("" + value);
			}
		}
	}
	
	private void handleCount(int id, int row, int cell, int mode){
		mAddValue = Utilis.toInt(mBuf.toString());
		if(mode == ChoiceMode.NORMAL){
			int nCellKey = mCountRow.get(row);
			int value = Utilis.toInt(mCountCell.get(nCellKey + cell));
			if (mAddValue!=0){
				value += mAddValue;
			}else {
				value = mAddValue;
			}
			mCountCell.remove(nCellKey + cell);
			mCountCell.put(nCellKey + cell, String.valueOf(value));
			EditText view = (EditText)mLayoutRoot.findViewById(id);
//			String strValue = view.toString();
			view.setText("" + value);
		}else if(mode == ChoiceMode.ROW){
			int nCellKey = mCountRow.get(row);
			// 去掉頭兩個值
			for(int i = 2 ; i < mSizeLink.size(); i++){
				int value = Utilis.toInt(mCountCell.get(nCellKey + i));
					value = mAddValue;
				mCountCell.remove(nCellKey + i);
				mCountCell.put(nCellKey + i, String.valueOf(value));
				EditText view = (EditText)mLayoutRoot.findViewById(nCellKey + i);
				view.setText("" + value);
			}
			cleanNumber();
		}else if(mode == ChoiceMode.CELL){
			for(int nRow = 1; nRow < mCountRow.size(); nRow++){
				int nCellKey = mCountRow.get(nRow);
				int value = Utilis.toInt(mCountCell.get(nCellKey + cell));
					value = mAddValue;
				mCountCell.remove(nCellKey + cell);
				mCountCell.put(nCellKey + cell, String.valueOf(value));
				EditText view = (EditText)mLayoutRoot.findViewById(nCellKey + cell);
				view.setText("" + value);
			}
			cleanNumber();
		}else if(mode == ChoiceMode.EDIT){
			//個別欄位輸入 
			int nCellKey = mCountRow.get(row);
			EditText view = (EditText)mLayoutRoot.findViewById(id);
			int value =Utilis.toInt(view.getText().toString());
			mCountCell.remove(nCellKey + cell);
			mCountCell.put(nCellKey + cell, String.valueOf(value));
		}
		//cleanNumber();
	}
	
	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(AIncomePc.this);
			switch (id) {
			//針對純粹非建檔的呼叫,不可以執行 btn_size,btn_color,btn_count
			//儲存時,呼叫 saveData() 但是mItemMode要為0,才不會更新了 採購
				case R.id.text_price:
				{
					mUnitprice.setText(mBuf.toString());
					mBuf.delete(0, mBuf.toString().length());
					mBuf.append("");
					aInput="";
					mInput.setText("");
					mInput.requestFocus();
					break;
				}			
				case R.id.text_discount:
				{
					mDiscount.setText(mBuf.toString());
					mBuf.delete(0, mBuf.toString().length());
					mBuf.append("");
					aInput="";
					mInput.setText("");
					mInput.requestFocus();
					break;
				}			
				case R.id.btn_size:
				{
					if(mItemMode<2){
						if(mMode == IncomeMode.Count){
						DialogUtilis.showDialogChk(AIncomePc.this, "訊息提示", "警告!此資料未存取，若是離開此頁資料將會清空，請問是否離開?", new IReqCallback(){
							@Override
							public void onAction() {
								// TODO Auto-generated method stub
								mViewMode = ViewMode.NORMAL;
								changeMode(IncomeMode.Size);
							}
						});
						}else if(mMode != IncomeMode.Size){
						changeMode(IncomeMode.Size);
						}
					} else if(mItemMode==3){ //印條碼F1 QDETAIL
						Toast.makeText(AIncomePc.this, "目前選中MID : " + mBatch, Toast.LENGTH_SHORT).show();
						String sendS=makeBarcode("1",mBatch,"0");
						  outBarcode(sendS,1);
							finish();
					}else if(mItemMode==4){ //印條碼F4 QITEMS
						Toast.makeText(AIncomePc.this, "目前選中貨號 : " + mBatch, Toast.LENGTH_SHORT).show();						
						String sendS=makeBarcode("1",mBatch,"1");
						  outBarcode(sendS,1);
							finish();
					}else if(mItemMode==5){ //印條碼F4 QITEMS
						Toast.makeText(AIncomePc.this, "目前選中貨號 : " + mBatch, Toast.LENGTH_SHORT).show();						
						String sendS=makeBarcode("1",mBatch,"0");
						  outBarcode(sendS,1);
							//finish();
					}
					break;
				}
				case R.id.btn_color:
				{
					if(mItemMode<2){					
						if(mMode == IncomeMode.Count){
						DialogUtilis.showDialogChk(AIncomePc.this, "訊息提示", "警告!此資料未存取，若是離開此頁資料將會清空，請問是否離開?", new IReqCallback(){
							@Override
							public void onAction() {
								// TODO Auto-generated method stub
								mViewMode = ViewMode.NORMAL;
								//如何真的歸零?????
								changeMode(IncomeMode.Color);
								//@@test
								//mColorCheckList.clear();
							}
						});
						}else if(mMode != IncomeMode.Color){
						changeMode(IncomeMode.Color);
						}
					} else if(mItemMode==3){ //印條碼F2
						String sendS=makeBarcode("2",""+mBatch,"0");
						  outBarcode(sendS,2);
							finish();
					}else if(mItemMode==4){ //印條碼F4
						String sendS=makeBarcode("2",mBatch,"1");
						  outBarcode(sendS,2);
							finish();
					}else if(mItemMode==5){ //印條碼F4
						String sendS=makeBarcode("2",mBatch,"0");
						  outBarcode(sendS,2);
							//finish();
					}
					
					break;
				}
				case R.id.btn_count:
				{
					if(mItemMode<2){					
						if(mSize == null || mSize.length() <= 0){
							Toast.makeText(AIncomePc.this, "請先選擇 Size", Toast.LENGTH_SHORT).show();
							return;
						}
						if(mColorCheckList.size() <= 0){
							Toast.makeText(AIncomePc.this, "請選擇任一顏色", Toast.LENGTH_SHORT).show();
							return;
						}
						
						changeMode(IncomeMode.Count);
					} else if(mItemMode==3){ //印條碼F3
						String sendS=makeBarcode("3",mBatch,"0");						
						  outBarcode(sendS,3);
							finish();
					}else if(mItemMode==4){ //印條碼F4
						String sendS=makeBarcode("3",mBatch,"1");
						outBarcode(sendS,3);
						finish();
					}else if(mItemMode==5){ //印條碼F4
						String sendS=makeBarcode("3",mBatch,"0");
						outBarcode(sendS,3);
						//finish();
					}
					break;
				}
				case R.id.btn_save:
				{
					if(mItemMode<=2){
						if(mMode == IncomeMode.Count){
							if(saveData() == true){
								if(mItemMode<2){
									mItemMode=3;
						        	((Button)findViewById(R.id.btn_size)).setText("吊牌1");
						       		((Button)findViewById(R.id.btn_color)).setText("吊牌2");
						       		((Button)findViewById(R.id.btn_count)).setText("條碼3");
						       		((Button)findViewById(R.id.btn_save)).setText("條碼4");
						    		getDefaultData();
								}else{
									finish();
								}
							}
						}else{
							Toast.makeText(AIncomePc.this, "訊息提示!請於數量頁面存取資料", Toast.LENGTH_SHORT).show();
						}
					}else if(mItemMode==3){ //印條碼F4
						String sendS=makeBarcode("4",mBatch,"0");
						  outBarcode(sendS,4);
							finish();
					}else if(mItemMode==4){ //印條碼F4
						String sendS=makeBarcode("4",mBatch,"1");
						  outBarcode(sendS,4);
							finish();
					}else if(mItemMode==5){
						if(saveData() == true){
							finish();
						}
					}
					break;
				}
				case R.id.btn_exit:
				{
					finish();
					break;
				}
				case R.id.btn_unit:
				{//切換 段 件
					
					//如果為(件)切換為(段) 應先檢查 每個數值是否整除nUnit
					
					//如果為 段 切換為 件 可以 直接 *nUnit
					//即時 維護 buttom , isUnit
					if (nUnit>1){ //應先確認 nUnit>1 才有必要切換
						if (isUnit==1){ //如果為 段 切換為 件 可以 直接 *nUnit
							for(int nRow = 1; nRow < mCountRow.size(); nRow++){
								int nCellKey = mCountRow.get(nRow);
								for(int j = 2 ; j < mSizeLink.size(); j++){
									int value = Utilis.toInt(mCountCell.get(nCellKey + j))*nUnit;
									mCountCell.remove(nCellKey + j);
									mCountCell.put(nCellKey + j, String.valueOf(value));
									TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + j);
									view.setText("" + value);
								}
							}
							isUnit=0;
							((Button)findViewById(R.id.btn_unit)).setText("件");
						}else{ //(件)切換為(段) 如果全部整除 才可以 切換
							int err=0;
							for(int nRow = 1; nRow < mCountRow.size(); nRow++){
								int nCellKey = mCountRow.get(nRow);
								for(int j = 2 ; j < mSizeLink.size(); j++){
									if (Utilis.toInt(mCountCell.get(nCellKey + j))!=0 && (Utilis.toInt(mCountCell.get(nCellKey + j))%nUnit)!=0){
										err=1;	break;
									}
								}
								if (err!=0) break;
							}
							if (err==0){//才可以 切換為 (段)
								for(int nRow = 1; nRow < mCountRow.size(); nRow++){
									int nCellKey = mCountRow.get(nRow);
									for(int j = 2 ; j < mSizeLink.size(); j++){
										if (Utilis.toInt(mCountCell.get(nCellKey + j))!=0){
											int value = Utilis.toInt(mCountCell.get(nCellKey + j))/nUnit;
											mCountCell.remove(nCellKey + j);
											mCountCell.put(nCellKey + j, String.valueOf(value));
											TextView view = (TextView)mLayoutRoot.findViewById(nCellKey + j);
											view.setText("" + value);
										}
									}
								}
								isUnit=1;
								((Button)findViewById(R.id.btn_unit)).setText(""+nUnit+"段");
							}else{
								Toast.makeText(AIncomePc.this, "沒有整除,(件)無法換算為(段)", Toast.LENGTH_SHORT).show();
							}
						}
					}
					break;
				}
				case R.id.btn_disc1:{
					mDiscount.setText(BD1.getText().toString());
					break;
				}
				case R.id.btn_disc2:{
					mDiscount.setText(BD2.getText().toString());
					break;
				}
				case R.id.btn_disc3:{
					mDiscount.setText(BD3.getText().toString());
					break;
				}
				case R.id.btn_disc4:{
					mDiscount.setText(BD4.getText().toString());
					break;
				}
				case R.id.btn_disc5:{
					mDiscount.setText(BD5.getText().toString());
					break;
				}
				case R.id.btn_disc6:{
					mDiscount.setText(BD6.getText().toString());
					break;
				}
				case R.id.btn_disc7:{
					mDiscount.setText(BD7.getText().toString());
					break;
				}
				case R.id.btn_disc8:{
					mDiscount.setText(BD8.getText().toString());
					break;
				}
				case R.id.btn_disc9:{
					mDiscount.setText(BD9.getText().toString());
					break;
				}
			}
		}
	}
	
	 private String makeBarcode(String ID,String search,String sMode){
		 
		String sepa="\r\n";
		SQLiteDatabase db = Utilis.getDB(AIncomePc.this);
		Cursor cursorAlbun = null;
		StringBuffer sPrice = new StringBuffer();
       StringBuffer bufQ = new StringBuffer();
//		應開始命名所要存的 /cwbuyer/cwbuyer_trans_888168.csv"
	if (sMode.equalsIgnoreCase("0")){ //原始的
		bufQ.append("select  * from qdetail");
		bufQ.append(" where MID='" + mMID+"'");
		cursorAlbun = db.rawQuery(bufQ.toString(), null);
		String Country=null;
		if (cursorAlbun != null) {
			if (cursorAlbun.getCount() > 0) {																
			cursorAlbun.moveToFirst();
				Cursor cs = db.rawQuery("select * from qc_country where _ID="+cursorAlbun.getInt(cursorAlbun.getColumnIndex("COUNTRY")), null);
				if (cs.getCount()>0){
					cs.moveToFirst();
					Country=cs.getString(cs.getColumnIndex("NAME"));
				}else {
					Country=cursorAlbun.getString(cursorAlbun.getColumnIndex("COUNTRY"));
				}
				cs.close();
				//貨品明細編號需透過回圈讀取顏色尺寸的組合
			for(int nRow = 1; nRow < mCountRow.size(); nRow++){
				int nCellKey = mCountRow.get(nRow);
				for(int i = 2 ; i < mSizeLink.size(); i++){
					int value = Utilis.toInt(mCountCell.get(nCellKey + i));
						//產生貨品明細編號
					if(value>0){
						sPrice.append("^KF"+ID+sepa);
						//@@@
						sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+sepa);
						sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")))+sepa);
						sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+"-");
						sPrice.append(mCountCell.get(nCellKey + 0)+"-");
						sPrice.append(mCountCell.get(i)+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COLORNO")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COLOR")))+sepa);
						sPrice.append(mSplitSizes+sepa);
						sPrice.append(mCountCell.get(nCellKey + 0)+sepa);
						sPrice.append(mCountCell.get(nCellKey + 1)+sepa);
						sPrice.append(mCountCell.get(i)+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("BATCH")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P0")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P4")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P5")))+sepa);
						sPrice.append(season[cursorAlbun.getInt(cursorAlbun.getColumnIndex("SEASON"))]+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT")))+sepa);
						
						String Quality[]= new String[6];
						Quality=getQuality(cursorAlbun.getString(cursorAlbun.getColumnIndex("QUALITY_ID")));
						for (int s=0;s<6;s++)	sPrice.append(Quality[s]+sepa);
		        		sPrice.append(Country+sepa);
						sPrice.append(getmCode(cursorAlbun,0)+sepa);  //暗碼
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT2")))+sepa);
						sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("CREATEDATETIME")))+sepa);
						sPrice.append("E"+sepa);
						int printn=Utilis.toInt(mCountCell.get(nCellKey + i));
						if (nbar>1) printn=(printn+(nbar-1))/nbar;
						sPrice.append("~P"+String.valueOf(printn)+sepa);
					}	
				}
			}
			}
		}	
	} else {//iMode!=0
		bufQ.append("select distinct * from qitems");
		bufQ.append(" where GOODSNO='" + search+"'");
		bufQ.append(" order by CREATEDATETIME DESC ");
		cursorAlbun = db.rawQuery(bufQ.toString(), null);

		if (cursorAlbun != null) {
			if (cursorAlbun.getCount() > 0) {																
			cursorAlbun.moveToFirst();

			for(int nRow = 1; nRow < mCountRow.size(); nRow++){
				int nCellKey = mCountRow.get(nRow);
				for(int i = 2 ; i < mSizeLink.size(); i++){
					int value = Utilis.toInt(mCountCell.get(nCellKey + i));
				//貨品明細編號需透過回圈讀取顏色尺寸的組合
				if(value>0){
					sPrice.append("^KF"+ID+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SOURCENO")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNO")))+"-");
					sPrice.append(mCountCell.get(nCellKey + 0)+"-");
					sPrice.append(mCountCell.get(i)+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("GOODSNAME")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("UNIT2")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COLORS")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SIZES")))+sepa);
					sPrice.append(mCountCell.get(nCellKey + 0)+sepa);
					sPrice.append(mCountCell.get(nCellKey + 1)+sepa);
					sPrice.append(mCountCell.get(i)+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("SUPPLY")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("BATCH")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P0")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P4")))+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("P5")))+sepa);
					sPrice.append(season[cursorAlbun.getInt(cursorAlbun.getColumnIndex("SEASON"))]+sepa);
					sPrice.append( DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("ORDDATE")))+sepa);
					
					String Quality[]= new String[6];
					Quality=getQuality("1")	;  //未來可能需要時,要參QDETAIL
					for (int s=0;s<6;s++)	sPrice.append(Quality[s]+sepa);
					//成份
	        		sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("COUNTRY")))+sepa);
					sPrice.append(getmCode(cursorAlbun,1)+sepa);  //暗碼
					sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("YEAR")))+sepa);
					sPrice.append(DBCloud.chkStrB(cursorAlbun.getString(cursorAlbun.getColumnIndex("FORMDATE")))+sepa);
					sPrice.append("E"+sepa);
					int printn=Utilis.toInt(mCountCell.get(nCellKey + i));
					if (nbar>1) printn=(printn+(nbar-1))/nbar;
					sPrice.append("~P"+String.valueOf(printn)+sepa);
				}	
				}
				
			}
			}
		}
	}
		
			//每產生一個STRINGBUF:sPrice 就是一份完整的文件
				db.close();
				cursorAlbun.close();
				
		return sPrice.toString();		
	 }

		private void getDefaultData(){
	    	SQLiteDatabase sdb = Utilis.getDB(this);
	    	if(sdb != null){
				Cursor cursor = sdb.rawQuery("select * from qc_default", null);
				if(cursor != null){
					try{
						if(cursor.getCount() > 0){
							cursor.moveToFirst();
							mDefaultData = new DefaultData();
							mDefaultData.nYear = cursor.getInt(cursor.getColumnIndex("YEAR"));
							mDefaultData.employ = cursor.getString(cursor.getColumnIndex("EMPLOY"));
							mDefaultData.nBarOut = cursor.getInt(cursor.getColumnIndex("BAROUT")); //保留
							mDefaultData.nFileOut = cursor.getInt(cursor.getColumnIndex("FILEOUT")); //保留
							mDefaultData.nPrintOut = cursor.getInt(cursor.getColumnIndex("PRINTOUT")); //保留
							mDefaultData.nCa1 = cursor.getInt(cursor.getColumnIndex("CA1"));
							mDefaultData.nCa2 = cursor.getInt(cursor.getColumnIndex("CA2"));
							mDefaultData.nCa3 = cursor.getInt(cursor.getColumnIndex("CA3"));
							mDefaultData.nCb1 = cursor.getInt(cursor.getColumnIndex("CB1"));
							mDefaultData.nCb2 = cursor.getInt(cursor.getColumnIndex("CB2"));
							mDefaultData.nCb3 = cursor.getInt(cursor.getColumnIndex("CB3"));
							mDefaultData.nCc1 = cursor.getInt(cursor.getColumnIndex("CC1"));
							mDefaultData.nCc2 = cursor.getInt(cursor.getColumnIndex("CC2"));
							mDefaultData.nCc3 = cursor.getInt(cursor.getColumnIndex("CC3"));
							mDefaultData.nCd1 = cursor.getInt(cursor.getColumnIndex("CD1"));
							mDefaultData.nCd2 = cursor.getInt(cursor.getColumnIndex("CD2"));
							mDefaultData.nCd3 = cursor.getInt(cursor.getColumnIndex("CD3"));
						}
					}catch(Exception e){
						e.printStackTrace();
					}finally{
						cursor.close();
					}
				}
				sdb.close();
	    	}
	    }
	 
	 private String getmCode(Cursor cursor,int check){
			StringBuffer sPrice = new StringBuffer();
			 String PR3=""+cursor.getInt(cursor.getColumnIndex("P3"));
			 if (PR3.length()==3 || PR3.length()==2)
				 PR3="0"+PR3;
			 else if (PR3.length()==1)
				 PR3="00"+PR3;
			 
			 String PR1=""+cursor.getInt(cursor.getColumnIndex("P1"));
			 if (PR1.length()==3 || PR1.length()==2)
				 PR1="0"+PR1;
			 else if (PR1.length()==1)
				 PR1="00"+PR1;
			
			String dDay="CREATEDATETIME"; if (check==1) dDay="FORMDATE";
			String dPrice=PR3+","+cursor.getString(cursor.getColumnIndex("P5"))+","+cursor.getString(cursor.getColumnIndex("P2"))+","+cursor.getString(cursor.getColumnIndex("P0"))+","+cursor.getString(cursor.getColumnIndex("SUPPLY"))+","+cursor.getString(cursor.getColumnIndex(dDay)).substring(2, 4)+cursor.getString(cursor.getColumnIndex(dDay)).substring(5, 7)+cursor.getString(cursor.getColumnIndex(dDay)).substring(8)+","+cursor.getString(cursor.getColumnIndex("P4"))+","+PR1;
			String[] arrayW = dPrice.split(",");

		if (mDefaultData.nCa1>0 && mDefaultData.nCa2>0){
			if (arrayW[mDefaultData.nCa1-1].length()<(mDefaultData.nCa3+mDefaultData.nCa2-1)){
				sPrice.append(arrayW[mDefaultData.nCa1-1]); }
			else {
				sPrice.append(arrayW[mDefaultData.nCa1-1].substring(mDefaultData.nCa2-1, mDefaultData.nCa3-1+mDefaultData.nCa2));
			}
		}
		
		if (mDefaultData.nCb1>0 && mDefaultData.nCb2>0){
			if (arrayW[mDefaultData.nCb1-1].length()<(mDefaultData.nCb3+mDefaultData.nCb2-1)){
				sPrice.append(arrayW[mDefaultData.nCb1-1]); }
			else {
				sPrice.append(arrayW[mDefaultData.nCb1-1].substring(mDefaultData.nCb2-1, mDefaultData.nCb3-1+mDefaultData.nCb2));
			}
		}	
		
		if (mDefaultData.nCc1>0 && mDefaultData.nCc2>0){
			if (arrayW[mDefaultData.nCc1-1].length()<(mDefaultData.nCc3+mDefaultData.nCc2-1)){
				sPrice.append(arrayW[mDefaultData.nCc1-1]); }
			else {
				sPrice.append(arrayW[mDefaultData.nCc1-1].substring(mDefaultData.nCc2-1, mDefaultData.nCc3-1+mDefaultData.nCc2));
			}
		}	

		if (mDefaultData.nCd1>0 && mDefaultData.nCd2>0){
			if (arrayW[mDefaultData.nCd1-1].length()<(mDefaultData.nCd3+mDefaultData.nCd2-1)){
				sPrice.append(arrayW[mDefaultData.nCd1-1]); }
			else {
				sPrice.append(arrayW[mDefaultData.nCd1-1].substring(mDefaultData.nCd2-1, mDefaultData.nCd3-1+mDefaultData.nCd2));
			}
		}
		return sPrice.toString(); 
	 }
	 
		private TextWatcher watcherCount = new TextWatcher(){  
	        @Override  
	        public void afterTextChanged(Editable s) {  
	        }  
	        @Override  
	        public void beforeTextChanged(CharSequence s, int start, int count,  
	                int after) {  
	        }  
	        @Override  
	        public void onTextChanged(CharSequence s, int start, int before,  
	                int count) {
	        	  	//reCount();
	        }  
	    };
	 
	 
private void outBarcode( String sendText,int xyz){
	
			
		   String address = barStr[1];// 連線的ip
		   int port =Utilis.toInt(barStr[2]);// 連線的port
		   if (xyz==4){
			   address = Utilis.getIni(this,"SYS", "DEV", 5);
			   port =Utilis.toInt(Utilis.getIni(this,"SYS", "DEV", 6));
		   }
				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,5000);
					 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
					 byte data[] = new String(sendText.getBytes("UTF8")).getBytes("BIG5");
	                    SystemClock.sleep(500);
					 out.write(data, 0, data.length);
	                    SystemClock.sleep(500);
					 out.flush();
					 Toast.makeText(AIncomePc.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
			 } catch (UnknownHostException e) {
				 Toast.makeText(AIncomePc.this, "InetAddress物件建立失敗!!", Toast.LENGTH_LONG).show();
			 } catch (SocketException e) {
				 Toast.makeText(AIncomePc.this, "socket建立失敗", Toast.LENGTH_LONG).show();				 
			 } catch(IOException e) {
				 Toast.makeText(AIncomePc.this,"傳送失敗", Toast.LENGTH_LONG).show(); 
			 } finally{
				 try {
					socket.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					 Toast.makeText(AIncomePc.this, "socket關閉失敗", Toast.LENGTH_LONG).show();				 
					e.printStackTrace();
				}				 
			 }
	}		 

	 private String[] getQuality(String ID){
		String quality[] = {" "," "," "," "," "," "};
		SQLiteDatabase db = Utilis.getDB(AIncomePc.this);
		Cursor cs = null;
		String SQLask = "select * from qc_quality where _ID='"+ID+"'";
		cs = db.rawQuery(SQLask, null);
			if (cs.getCount() > 0) {																
				cs.moveToFirst();
				for (int i=0;i<6;i++){
					if (cs.getString(i+1)==null || cs.getString(i+1).length()==0)
						quality[i]=" ";
					else	
						if ((i%2)==1)
							quality[i]=cs.getString(i+1)+"%";
						else
							quality[i]=cs.getString(i+1);
				}
			} 
		db.close();
		cs.close();
		return quality; 
	 }
	 
	/**是在每一筆存入前應整合的,且更新給QDETAIL & QITEMS 所有同一個GOODSNO
	*最好放在AINCOME的SAVEDATA
 	*也在進入重新編輯色尺寸後,應讀取已存在的色尺寸,再加入整合所有的顏色尺寸
 	**/
	public boolean saveData(){
		SQLiteDatabase dbC = Utilis.getDB(AIncomePc.this);
		String [] tt = {"","",""};
		String [][] colsiz = new String[31][31];
		String [] XmColn={""};
		String [] XmCol={""};
		String [] XmSiz={""};
		String cntList="";
		int t1=-1;
		int t2=-1;
		int [] mIDt={0};
		//colsiz= new String[31][31];
			for (int y=0;y<=30;y++){	for (int z=0;z<=30;z++){	colsiz[y][z]="0";		}	}	
		
		int totalIn = 0; // 總數量
		for(int i = 0; i < mArrayColorNumber.size(); i ++){
			String Coln=null;
			String Col=null;
					Coln=mArrayColorNumber.get(i);
					Col=mArrayColorName.get(i);
				int chk1=-1;
				for (int z=0;z<=t1;z++){
					if (XmColn[z].equalsIgnoreCase(Coln)){	chk1=z;	}
				}	
				if(chk1<0){ //表示樣本沒有
					//應該增色號樣本字串
					t1=t1+1;
					if (t1>0) { tt[0]=tt[0]+"，"; tt[1]=tt[1]+"，"; }
					tt[0]=tt[0]+Coln;
					tt[1]=tt[1]+Col;
					XmColn=tt[0].split("，");
					XmCol=tt[1].split("，");
					chk1=t1;
				}
		}		
				
		for(int nRow = 1; nRow < mCountRow.size(); nRow++){
			
				int nCellKey = mCountRow.get(nRow);
				
				for(int j = 2 ; j < mSizeLink.size(); j++){
					String value = mCountCell.get(nCellKey + j);
					if (isUnit==1 && nUnit>1 && Utilis.toInt(value)!=0) value=""+ (Utilis.toInt(value)*nUnit);
					int chk2=-1;
					for (int w=0;w<=t2;w++){
					if (XmSiz[w].equalsIgnoreCase(mSizeLink.get(j)	)){	chk2=w;	}
					}
					if(chk2<0){ //表示樣本沒有
						//應該增尺寸樣本字串
						t2=t2+1;
						if (t2>0) tt[2]=tt[2]+",";
						tt[2]=tt[2]+mSizeLink.get(j);
						XmSiz=tt[2].split(",");
						chk2=t2;
					}
					
					colsiz[nRow-1][chk2]=value;
					totalIn=totalIn+Utilis.toInt(value);
				}
		}	
		
		for (int i=0;i<=t1;i++){
			if (i>0)  cntList=cntList+"，";
			 for (int j=0;j<=t2;j++) {
				if (j>0)  cntList=cntList+",";
				 cntList=cntList+colsiz[i][j];
	        }
	    }
		
			if(mItemMode <2){  //關鍵著是否去儲存qdetail 的色尺寸量 0表不執行
//				try{
					// 新增進貨檔的時候
					//colsiz[t][chk1][chk2]=value;
				//@@@movetohere_test
				ContentValues values = new ContentValues();
					values.put("SIZE", tt[2]); //mSize
					values.put("COLOR", tt[1]);
					values.put("COLORNO", tt[0]);
					values.put("INLIST",cntList);
					values.put("IMPO", totalIn);
					
					String[] args = {String.valueOf( mMID)};
					int success = dbC.update(com.cwbuyer.lib.TbName.QDETAIL, values,
							"MID=?", args);
					if(success > 0){
						Toast.makeText(this, "修改資料成功", Toast.LENGTH_SHORT).show();
					}else{
						Toast.makeText(this, "修改資料失敗", Toast.LENGTH_SHORT).show();
						return false;
					}
					
					mItemData = DBUtil.CItem.getData(this, mMID, false);
					
					if (DSend[8].equalsIgnoreCase("1")) {
						Toast.makeText(AIncomePc.this, "單品上傳雲端!!", Toast.LENGTH_SHORT).show();
						Intent intent = new Intent();
						intent.setClass(AIncomePc.this,MakeTransDetail.class);
						intent.putExtra("make_batch",mItemData.batch);
						intent.putExtra("make_mode",0);
						intent.putExtra("make_kind",0);
						intent.putExtra("make_user",mItemData.GoodsNo);
						intent.putExtra("make_01",1);
						startActivity(intent);
					}
			} 	//galleryview
				// 修改的時候不需要取存到資料庫
				// 但是要回傳資料
		dbC.close();
			Intent intent = new Intent();
			intent.putExtra("item_impo", totalIn);
			intent.putExtra("item_size", tt[2]);
			intent.putExtra("item_color", tt[1]);
			intent.putExtra("item_colorno", tt[0]);
			intent.putExtra("item_countlist", cntList);
			intent.putExtra("unitprice", Utilis.toDouble(mUnitprice.getText().toString()));
			intent.putExtra("discount", Utilis.toDouble(mDiscount.getText().toString()));
			AIncomePc.this.setResult(RESULT_OK,intent);

		return true;			
//		return false;
	}

	private int ColorGetnumber(Context context,String key){
		int number=0;
		SQLiteDatabase db = Utilis.getDB(context);
		Cursor cs = null;					
		StringBuffer mySqlBuf = new StringBuffer();
			mySqlBuf.append("select distinct NO,PIC from qc_color where NO='"+key+"'");
			cs = db.rawQuery(mySqlBuf.toString(), null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				number=cs.getInt(1);
			}
			db.close();
			cs.close();
		return number;	
	}
	
	public class ColorAdapter extends BaseAdapter{
		private LinkedList<ColorData> mList = null;
		private LayoutInflater mInflater;
    	/* MyAdapter的建構子，傳入三個參數 */
        public ColorAdapter(Context context) {
          /* 參數初始化 */
          mInflater = LayoutInflater.from(context);
          mList = new LinkedList<ColorData>();
          getData(context);
        }
        
        public ColorData getColorData(int pos){
        	return mList.get(pos);
        }
        
        public String getColorName(int pos){
        	return mList.get(pos).name;
        }
        
        public String getColorNumber(int pos){
        	return mList.get(pos).number;
        }
        
        public void getData(Context context){
    		if(mList != null){
    			mList.clear();
    		}
    		SQLiteDatabase db = Utilis.getDB(context);
    		Cursor cursor = db.rawQuery("select * from qc_color order by NO", null);
    		if(cursor != null){
    			try{
    				if(cursor.getCount() > 0){
    					cursor.moveToFirst();
    					for(int i = 0; i < cursor.getCount(); i++){
    						ColorData data = new ColorData();
    						data.id = cursor.getInt(cursor.getColumnIndex("_ID"));
    						data.color = cursor.getInt(cursor.getColumnIndex("PIC"));
    						data.name = cursor.getString(cursor.getColumnIndex("TXT"));
    						data.number = cursor.getString(cursor.getColumnIndex("NO"));
    						mList.add(data);
    						cursor.moveToNext();
    					}
    				}
    			}catch(Exception e){
    				e.printStackTrace();
    			}finally{
    				cursor.close();
    				cursor = null;
    			}
    		}
    		db.close();
    		db = null;
    	}
    	
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			 ViewHolder holder;
		      if (convertView == null) {
		    	convertView = mInflater.inflate(R.layout.list_color, null);  
		        holder = new ViewHolder();
		        holder.textName = (TextView)convertView.findViewById(R.id.text_name);
		        holder.textColor = (ImageView)convertView.findViewById(R.id.text_color);
		        holder.check = (CheckBox)convertView.findViewById(R.id.checkbox);
		        holder.check.setVisibility(View.VISIBLE);
		        convertView.setTag(holder);
		      }else{
		    	  holder = (ViewHolder) convertView.getTag();
		      }
		      ColorData data = mList.get(position);
		      holder.textColor.setBackgroundColor(data.color);
		      holder.textName.setText(data.number + " " + data.name);
		      holder.check.setOnCheckedChangeListener(new RadioCheck(position));
		      if (mSplitColorNo!=null && mSplitColorNo.length()>0){
		      if (mSplitColorNo.indexOf(data.number)>=0)   holder.check.setChecked(true);
		      }
		      return convertView;
		}
		
		private class RadioCheck implements CompoundButton.OnCheckedChangeListener
		{
			private int mPosition = 0;
			public RadioCheck(int nPos){
				mPosition = nPos;
			}
			
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){
				int nChoick = 1;
				ColorData data = mList.get(mPosition);
				if(isChecked){
					if (mColorCheckList.containsKey(mPosition) == true) {
					}else{
					mColorCheckList.put(mPosition, nChoick);
	        		mArrayColorNumber.add(data.number);
	        		mArrayColorName.add(data.name);
					}
				}else{
					if (mColorCheckList.containsKey(mPosition) == true) {
						mColorCheckList.remove(mPosition);
						for (int i=0;i<mArrayColorNumber.size();i++){
							if (mArrayColorNumber.get(i).equalsIgnoreCase(data.number)){
								mArrayColorNumber.remove(i);		
								mArrayColorName.remove(i);
								break;
							}
						}
					}
				}
			}
		}
		
		private class ViewHolder {
		  ImageView textColor;
	      TextView textName;
	      CheckBox check;
		}
	}
}

