package com.cwbuyer.lib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.LinkedList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.cwbuyer.format.EMode;
import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.PItemData;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.TbName;
import com.cwbuyer.lib.Utilis;
import com.cwbuyer.main.APos.PItemKind;
import com.cwbuyer.main.QCustff;
import com.cwbuyer.main.Qfactff;
import com.cwbuyer.main.QCustff.QCustfMode;
import com.pwbuyer.main.R;

// CSV規格 明細貨號 件數 單價
//總倉 可以選擇總倉或指定門市
//其餘欄位都要預設 會員(預設)
//單價如果不存在,找該會員(預設)交易方式(價別)
public class DataImports<mAdapter>  extends Activity {
	
private ListView mListView = null;		
ReportAdapter mAdapter = null;
private RepData data = new RepData(); //##格式化需考量內容增刪
private PItemData dataH = new PItemData(); //##格式化需考量內容增刪
private PItemData dataI = new PItemData(); //##格式化需考量內容增刪


	String[] menu_E={ "CSV匯入銷貨扣庫存", "返回" };	
	private String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");
	private final String[] tradeUser =Utilis.getIni(this,"INIH","USER",9).split("!&!");
	//0同步 1不同步(需帶 總倉或門市)
	private final int RESULT_QCUSTFF = 9999;		//會員檔回傳口令
	private final int RESULT_QDEPTFF = 9992;		//門市檔回傳口令
	private final int RESULT_QDEPTFFF = 99922;		//門市檔回傳口令
	private final int RESULT_QFACT = 1020;		//廠商檔回傳口令
	int aPart=0; //0.總倉1.門市
	Bundle bundle;	
	String msgTitle ="文件 : ";
	int nMode=0;
    int f123=0;  //0整數 1.小數點
    String HIkind="門市";
    int myKind=30;
    boolean isIn=false;
    boolean isOut=true;
	String mKind="30";
    String HIname="銷貨單";
	String csvFileName="";
	String mDept=deptStr[5];
	String tDept=deptStr[0];
	String path;
	String[] list;
	String[] listsel;
	String[] listdept;
	String cust_no=tradeUser[(int)(myKind /10-1)];

	String cust_name;
	int cust_tradetype=5;
	int cust_discount=100;
	int ppos=0;//存在於zansly_csv的筆數
	
	public class RepData{ 
		public String iPic;  
		public String iGoods; 
		public String iImpo; 
		public String iName; 
		public String iMoney;
		public String iCountry;
		public String iNumber;
		public String iCompany;
		public String iFormdate;
		public String iUnit2;
		public int iSort;
	
		/*
	 	ImageView imageItem;
		TextView textGoodsNos; 	//左上 原貨號-->明細貨號mGoodsNos
		TextView textSenter;  		//右上 總件數-->總件數 進unit10 出unit20 銷unit30 員購unit40
		TextView textImpo;  		//右上 總件數-->總件數 進unit10 出unit20 銷unit30 員購unit40
		TextView textName; 		//左中 品名稱-->品名mGoodsName
		TextView textMoney;		//右中 合計金-->dSubprice
		TextView textCountry;		//左下 產地		-->交易方式(追加)(退)
		TextView textNumber;	//中下 來原編-->折數
		TextView textCompany;	//右下 供應商-->小計
		 */
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		switch (requestCode){
		case RESULT_QDEPTFF:
			if (resultCode == RESULT_OK) {				
				String rtnDept=dataR.getStringExtra("qcust_key");
				if (!rtnDept.equalsIgnoreCase(mDept)){
					if(myKind==30 || myKind==31){
					if (!rtnDept.equalsIgnoreCase(deptStr[5])){
						//不是總倉
						mDept=rtnDept;
						mKind="31";
					}else{
						mDept=rtnDept;
						mKind="30";
					}
					}else{
						mDept=rtnDept;
					}
 					myKind=Utilis.toInt(mKind);
					cust_no=tradeUser[(int)(myKind /10-1)];
					((EditText)findViewById(R.id.edit_inDept)).setText(getdeptF(mDept,0));
					((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,0));
				}					
			}			
			break;
		case RESULT_QDEPTFFF:
			if (resultCode == RESULT_OK) {				
				String rtnDept=dataR.getStringExtra("qcust_key");
				if (!rtnDept.equalsIgnoreCase(cust_no)){
					cust_no=rtnDept;
					((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,0));
				}					
			}			
			break;
		case RESULT_QCUSTFF:
			if (resultCode == RESULT_OK) {				
				String rtnCust=dataR.getStringExtra("qcust_key");
				if (!rtnCust.equalsIgnoreCase(cust_no)){
					cust_no=rtnCust;
					((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,0));
				}					
			}			
			break;
		case RESULT_QFACT:
			if (resultCode == RESULT_OK) {				
				String rtnCust=dataR.getStringExtra("qfact_key");
				if (!rtnCust.equalsIgnoreCase(cust_no)){
					cust_no=rtnCust;
					((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,1));
				}					
			}			
			break;
			
		}
	}

	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.dialog_incsv);
        if (Utilis.getIni(this,"SYS","SDB",7).equalsIgnoreCase("1")) f123=1; //需要小數位
		csvFileName =  getIntent().getStringExtra("make_mode");  //0.CSV檔匯入(銷貨扣庫存)資料庫
		//CWBuyer/cualbun/20123
		//指定CSV檔匯入的路徑
			//取得所有門市的資料	
		listdept=getdeptList();
		if (!deptStr[0].equalsIgnoreCase(deptStr[5])){
			aPart=1;
			mDept=deptStr[0];
			tDept=deptStr[0];
			
			mKind="31";
			myKind=Utilis.toInt(mKind);
		}
		msgTitle ="文件 : "+csvFileName.substring((android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+Utilis.getIni(DataImports.this, "SYS", "BACKOUT", 5)).length()+1)+ " 匯入"+HIname;
		resetButton(R.id.RB_3031);
		
        mListView = (ListView)findViewById(R.id.list_csv_data);  //將在畫面流覽的欄位們
        mAdapter = new ReportAdapter(this);
        mListView.setAdapter(mAdapter);
		ppos=startIniDb(this,csvFileName); //>0 表示上次還存在
		this.setTitle("CSV文件_即將匯入各類單據");
		//系統預設為 銷貨(總倉或門市自動判斷)
		((EditText)findViewById(R.id.edit_inDept)).setText(getdeptF(tDept,0));
		((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,0));
		((Button)findViewById(R.id.btn_tool)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.RB_3031)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.RB_10)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.RB_20)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.RB_21)).setOnClickListener(new MainClick());
		((EditText)findViewById(R.id.edit_inDept)).setOnClickListener(new MainClick());
		((EditText)findViewById(R.id.edit_outDept)).setOnClickListener(new MainClick());
		if (listdept.length<2)
			((Button)findViewById(R.id.RB_21)).setVisibility(View.INVISIBLE);

		if (ppos>0){//CSV資料存在,需要詢問 重新載入,還是繼續
			DialogUtilis.showDialog(DataImports.this, msgTitle+"已存在記憶體中,共"+ppos+" 筆", -1,
			new String[] { "重新載入", "繼續" }, new IDialog() {
				@Override
				public void onDialogFinish(int pos, String choice) {
					switch (pos) {
					case 0:
						SQLiteDatabase db_csv = Utilis.getDB(DataImports.this);
						String[] args = {csvFileName};
						db_csv.delete("zansly_csvs", "CSV_NAME=? ", args);
						db_csv.delete("zansly_csv", "CSV_NAME=? ", args);
						db_csv.close();
						firstInsertCSV(DataImports.this,csvFileName,1);
						break;
					case 1:
						firstInsertCSV(DataImports.this,csvFileName,0);
						break;
					}
				}
			});	
		}else{//直接載入
			firstInsertCSV(DataImports.this,csvFileName,1);
		}
		
		mListView.setOnItemClickListener(new OnItemClickListener(){
			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(DataImports.this);
				data = (RepData) mAdapter.getItem(position);
				chkItems(DataImports.this,data);
			}
		});
		
	}
		//總倉還可以選擇匯入的門市
		//門市不可以選擇
		//資料格式 門市編號(批號)-實際檔路徑-12未匯入/已完成
		//所以先讀取download目錄,合法的一律rename to 目前目錄,再回到目前的路徑統一判斷
	
	
	@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
          new AlertDialog.Builder(DataImports.this).setTitle(getString(R.string.str_msg)).setMessage(getString(R.string.msg_nomal_exit)).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
				finish();
            }
          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
          }).show();
          return true;
        } else {
          return super.onKeyDown(keyCode, event);
        }
    }


	//@EVENT事件補捉中心	
	class MainClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(DataImports.this);
			
			switch (id) {
			
			   case  R.id.RB_3031:  //返回
					mDept=deptStr[0];
					HIname="銷貨單";
					if (aPart==1){ 
						mKind="31";
						HIkind="門市";
						isIn=false;
						isOut=true;
						}else{
						mKind="30";
						HIkind="總倉/門市";						
						isIn=true;
						isOut=true;
					}
					myKind=Utilis.toInt(mKind);
					cust_no=tradeUser[(int)(myKind /10-1)];					
					msgTitle ="文件 : "+csvFileName.substring((android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+Utilis.getIni(DataImports.this, "SYS", "BACKOUT", 5)).length()+1)+ " 匯入"+HIname;
		        	resetButton(id);
				   break;
			   case  R.id.RB_10:  //返回
					mDept=deptStr[5];
					HIname="廠商進貨單";
					mKind="10";
					myKind=Utilis.toInt(mKind);
					cust_no=tradeUser[0];
					msgTitle ="文件 : "+csvFileName.substring((android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+Utilis.getIni(DataImports.this, "SYS", "BACKOUT", 5)).length()+1)+ " 匯入"+HIname;
					HIkind="總倉";						
					isIn=false;
					isOut=true;
		        	resetButton(id);
				   break;
			   case  R.id.RB_20:  //返回
				   if (aPart==0){
					mDept=deptStr[5];
					HIname="門市出貨單";
					cust_no=tradeUser[1];
					isIn=false;
					isOut=true;
				   }else{
						mDept=deptStr[5];
						HIname="門市出貨單";
						cust_no=deptStr[0];
						isIn=false;
						isOut=false;
				   }
					mKind="20";
					myKind=Utilis.toInt(mKind);
					HIkind="總倉";						
					((EditText)findViewById(R.id.edit_inDept)).setClickable(false);
					msgTitle ="文件 : "+csvFileName.substring((android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+Utilis.getIni(DataImports.this, "SYS", "BACKOUT", 5)).length()+1)+ " 匯入"+HIname;
		        	resetButton(id);
				   break;
			   case  R.id.RB_21:  //返回
				   if (aPart==0){
					mDept=tradeUser[1];
					HIname="門市轉貨單";
					cust_no="請選擇轉貨對象";
					isIn=true;
					isOut=true;
				   }else{
						mDept=deptStr[0];
						HIname="門市轉貨單";
						cust_no=tradeUser[1];
						isIn=false;
						isOut=true;
				   }
					HIkind="門市";						
					mKind="21";
					myKind=Utilis.toInt(mKind);
					msgTitle ="文件 : "+csvFileName.substring((android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+Utilis.getIni(DataImports.this, "SYS", "BACKOUT", 5)).length()+1)+ HIname;
		        	resetButton(id);
				   break;
			   case  R.id.edit_inDept:  //總倉門市
				   if(aPart==0 && (myKind==30 || myKind==31)){//總倉
					//銷貨
					//總倉 (門市通訊錄)含AA 
					//回傳時,要判斷AA30 或門市31
						Intent intent = new Intent();
						intent.putExtra("qcustf_qkind", PItemKind.TR20);
						intent.putExtra("qcustf_mode", 0); //普
						intent.putExtra("qcustf_key", deptStr[5]);
						intent.putExtra("pos_dept",deptStr[5]);//理論上為"SOS" 或 門市代號
						
						intent.setClass(DataImports.this, QCustff.class);
						startActivityForResult(intent, RESULT_QDEPTFF);
				   }else if(myKind==21){
						Intent intent = new Intent();
						intent.putExtra("qcustf_qkind", PItemKind.TR21);
						intent.putExtra("qcustf_mode", QCustfMode.NORMAL); 
						intent.putExtra("qcustf_key", "");
						intent.putExtra("pos_dept",cust_no);//理論上為"SOS" 或 門市代號
						intent.setClass(DataImports.this, QCustff.class);
						startActivityForResult(intent, RESULT_QDEPTFF);
					   //暫時沒有開放此功能
					   //門市轉貨單
					   //門市通訊錄 不含AA
				   }else if( aPart==1 || ( myKind==20) ||myKind==10){
					   //唯AA(不可執行)
				   }
					
				   break;
			   case  R.id.edit_outDept:  //對象
				   if((myKind==30 || myKind==31)){//銷貨
							Intent intent = new Intent();
							intent.putExtra("qcustf_qkind", myKind);
							intent.putExtra("qcustf_mode", QCustfMode.NORMAL); 
							intent.putExtra("qcustf_key", "");
							intent.putExtra("pos_dept", mDept);
							intent.setClass(DataImports.this, QCustff.class);
							startActivityForResult(intent, RESULT_QCUSTFF);
				   }else  if(myKind==10){
						Intent intent = new Intent();
						intent.setClass(DataImports.this, Qfactff.class);
						intent.putExtra("mode", EMode.EDIT);
						intent.putExtra("countryid", 0);  //表不分國別
						startActivityForResult(intent, RESULT_QFACT);
					   
				   }else if( myKind==20){
					   //門市通訊錄
					   if(aPart==0){
						Intent intent = new Intent();
						intent.putExtra("qcustf_qkind", myKind);
						intent.putExtra("qcustf_mode", QCustfMode.NORMAL); 
						intent.putExtra("qcustf_key", "");
						intent.putExtra("pos_dept", mDept);
						intent.setClass(DataImports.this, QCustff.class);
						startActivityForResult(intent, RESULT_QDEPTFFF);
					   }
				   }else if( myKind==21){
					   //門市通訊錄
						Intent intent = new Intent();
						intent.putExtra("qcustf_qkind", myKind);
						intent.putExtra("qcustf_mode", QCustfMode.NORMAL); 
						intent.putExtra("qcustf_key", "");
						intent.putExtra("pos_dept", mDept);
						intent.setClass(DataImports.this, QCustff.class);
						startActivityForResult(intent, RESULT_QDEPTFFF);
				   }
					   
				   break;
				case R.id.btn_tool:  //開始匯入
					/* 先檢查門市對象間的合理條件
					 * 詢問是否確認開始匯入
					 */
					showImport1Dialog();					
					break;
				case R.id.btn_exit:  //返回
					DialogUtilis.showDialog(DataImports.this, "是否放棄匯入?", -1,
					new String[] { "放棄", "繼續" }, new IDialog() {
						@Override
						public void onDialogFinish(int pos, String choice) {
							switch (pos) {
							case 0:
								finish();
								break;
							case 1:break;
							}
						}
					});	
					
					break;
			}	
		}
	}
	
	public void resetButton(int id){
		((Button)findViewById(R.id.RB_3031)).setBackgroundResource(R.drawable.keypad_blue2);
		((Button)findViewById(R.id.RB_10)).setBackgroundResource(R.drawable.keypad_blue2);
		((Button)findViewById(R.id.RB_20)).setBackgroundResource(R.drawable.keypad_blue2);
		((Button)findViewById(R.id.RB_21)).setBackgroundResource(R.drawable.keypad_blue2);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_green);
		((TextView)findViewById(R.id.title_csvname)).setText(msgTitle);
		((TextView)findViewById(R.id.TVIn)).setText(HIkind);
		((EditText)findViewById(R.id.edit_inDept)).setText(getdeptF(mDept,0));
		if (myKind!=10)
			((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,0));
		else
			((EditText)findViewById(R.id.edit_outDept)).setText(getdeptF(cust_no,1));
			
		((EditText)findViewById(R.id.edit_inDept)).setClickable(isIn);
		((EditText)findViewById(R.id.edit_outDept)).setClickable(isOut);
	}
	
	public String getImport0Msg(){ //USER選定了解壓縮的檔案,而提出了警語
		
		StringBuffer buf = new StringBuffer();
		switch (myKind){
		case 30:
			buf.append("您選擇了總倉:").append(getdeptF(mDept,0)).append("的銷貨單").append("\n")
			.append("對象為:").append(getdeptF(cust_no,0)).append("\n");			
			break;
		case 31:
			buf.append("您選擇了門市:").append(getdeptF(mDept,0)).append("的銷貨單").append("\n")
			.append("對象為:").append(getdeptF(cust_no,0)).append("\n");			
			break;
		case 20:
			buf.append("您選擇了總倉:").append(getdeptF(mDept,0)).append("的出貨單").append("\n")
			.append("對象為:").append(getdeptF(cust_no,0)).append("\n");			
			break;
		case 21:
			buf.append("您選擇了門市:").append(getdeptF(mDept,0)).append("的轉貨單").append("\n")
			.append("對象為:").append(getdeptF(cust_no,0)).append("\n");			
			break;
		case 10:
			buf.append("您選擇總倉:").append(getdeptF(mDept,0)).append("的廠商進貨單").append("\n")
			.append("對象為:").append(getdeptF(cust_no,1)).append("\n");			
			break;
		}
		buf.append("資料將匯入所有商品 , 是否繼續執行?").append("\n\n");
		
		return buf.toString();
	}
	
	public String[] getdeptList(){
		String[] lists=null;
		StringBuffer lst=new StringBuffer();
		SQLiteDatabase db = Utilis.getDB(DataImports.this);
		Cursor cs=db.rawQuery("select CUSTNO,CUSTNAME,TRADETYPE,DISCOUNT from qcust where TR='20' order by CUSTNO"  , null);
		if (cs.getCount()>0){
			cs.moveToFirst();
			for (int xx=0;xx<cs.getCount();xx++){
				if (!cs.getString(0).equalsIgnoreCase(Utilis.getIni(DataImports.this,"SYS","DEPT",6))){  //總倉除外
				lst.append(cs.getString(0)+","+cs.getString(1)+","+cs.getString(2)+","+cs.getString(3)+"!&!");
				}
				cs.moveToNext();
			}
		}
		db.close();
		cs.close();
		
		lists=lst.toString().split("!&!");
		if(lists.length<=0){
			Toast.makeText(DataImports.this,"查無門市的資料!!", Toast.LENGTH_SHORT).show();
			return null;
		}else{
			Toast.makeText(DataImports.this,"門市的資料!!"+lst.toString(), Toast.LENGTH_SHORT).show();
			return lists;
		}
	}
	
	//取代號/名稱
	public String  getdeptF(String whoNo,int mode){
		//mode=0qcust 1qfact
		String rtnCust=whoNo;
		String whoSQL="select CUSTNO,CUSTNAME,TRADETYPE from qcust where CUSTNO= '"+whoNo+"'";
		Cursor cs=null;
		SQLiteDatabase db = Utilis.getDB(DataImports.this);
		if (mode==1) 
			whoSQL="select FACTNO,FACTNAME,TRADETYPE from qfact where FACTNO= '"+whoNo+"'";
		
		   cs=db.rawQuery(whoSQL , null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				rtnCust=cs.getString(0)+"/"+cs.getString(1);
				cust_tradetype=cs.getInt(2);
			}	
		db.close();
		if (cs !=null) cs.close();
		return rtnCust;
	}	

	private class ReportAdapter extends BaseAdapter{
		
		private LayoutInflater mInflater;
		
		public LinkedList<RepData> mList = new LinkedList<RepData>();
		
		public ReportAdapter (Context context ){
		      mInflater = LayoutInflater.from(context);
		}

		@SuppressWarnings("unused")
		public RepData getData(int Position){
			return mList.get(Position);
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return mList.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		@SuppressWarnings("unchecked")
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_posh, null);
				holder = new ViewHolder();
				holder.imageItem = (ImageView)convertView.findViewById(R.id.img_ppic);
				holder.textGoodsNo = (TextView) convertView.findViewById(R.id.text_pgoodsno);
				holder.textImpo = (TextView) convertView.findViewById(R.id.text_pimpo);
				holder.textName = (TextView) convertView.findViewById(R.id.text_pname);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_pmoney);
				holder.textNumber = (TextView) convertView.findViewById(R.id.text_pnumber);
				holder.textCountry = (TextView) convertView.findViewById(R.id.text_pcountry);
				holder.textCompany = (TextView) convertView.findViewById(R.id.text_pcompany);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			@SuppressWarnings("unused")
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			RepData data = mList.get(position);
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(data.iPic, 80, 80));
			
			holder.textGoodsNo.setText(data.iGoods);
			
			holder.textName.setText(data.iName);
			holder.textCountry.setText(data.iCountry);
			holder.textCompany.setText(data.iCompany);
			holder.textMoney.setText(data.iMoney);
			holder.textNumber.setText(data.iNumber);
			holder.textImpo.setText(data.iImpo);			
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textGoodsNo;
			TextView textImpo;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			
		}

		
	}  //PItemAdapter ended

public void makeData(Context context, String csv_fn){
	/*開啟檔案,檢查一下商品檔是否完整,應顯示是否成功
		" CSV_NAME       VARCHAR( 80 ),"+
		" GOODSNO       VARCHAR( 20 ),"+
		" COLOR       VARCHAR( 4 ),"+
		" SIZE       VARCHAR( 8 ),"+
		" UNIT             DOUBLE,"+
		" PRICE             DOUBLE)";
		getDetail
		GOODSNO,GOODSNAME,COLORNO,COLOR,SIZE,PIC
				 				RepData data = new RepData();
	 */
		SQLiteDatabase db = Utilis.getDB(context);
		String SQL="select GOODSNO,COLOR,SIZE,PRICE,sum(UNIT) from zansly_csv WHERE CSV_NAME='"+csv_fn+"' group by GOODSNO,COLOR,SIZE,PRICE";
		Cursor cs=db.rawQuery(SQL, null);
		if (cs.getCount()>0){
			if(mAdapter.mList != null)	mAdapter.mList.clear();
			while (cs.moveToNext()){
			String FieldQdetail[]=getDetail(context,db,cs.getString(0),cs.getString(1),cs.getString(2));
			
				if(FieldQdetail!=null && FieldQdetail.length>0){
					//表示貨品檔存在
					RepData data = new RepData();
					data.iPic=FieldQdetail[5];  //圖片
					data.iFormdate=FieldQdetail[0]; //主貨號 做為KEY 不顯示
					data.iGoods=FieldQdetail[0]; //主貨號
					data.iName=FieldQdetail[1]; //品名
					data.iCountry=FieldQdetail[2]+"/"+FieldQdetail[3]; //COLORNO/COLORNAME
					data.iNumber=FieldQdetail[4]; //SIZES
					data.iImpo="小計"+Utilis.dedb(cs.getDouble(3)*cs.getDouble(4), 2);

					data.iMoney="單價:"+Utilis.dedb(cs.getDouble(3),2);
					data.iCompany="件數:"+Utilis.dedb(cs.getDouble(4),0);
					mAdapter.mList.add(data);

				}
			}
    	mAdapter.notifyDataSetChanged();
		}
		
		}				

private void chkItems(Context context, final RepData data){
	LayoutInflater factory = LayoutInflater.from(this);
	final View v1 = factory.inflate(R.layout.fcount, null);
	final EditText edtCount = (EditText) v1.findViewById(R.id.edcount);
	final EditText edtUprice = (EditText) v1.findViewById(R.id.eduprice);
	((EditText) v1.findViewById(R.id.ediscount)).setVisibility(View.INVISIBLE);
	final String eGOODS=data.iGoods;
	final String eCOLOR=data.iCountry.substring(0,data.iCountry.indexOf("/"));
	final String eSIZE=data.iNumber;
	double eUNIT=Utilis.toDouble(data.iMoney);
	double ePRICE=Utilis.toDouble(data.iNumber);
	@SuppressWarnings("unused")
	boolean chkd=false;
	edtCount.setText(""+data.iMoney);  //件數
	edtUprice.setText(""+data.iNumber);
	SQLiteDatabase db = Utilis.getDB(DataImports.this);
	Cursor cs=db.rawQuery("select CSV_NAME,GOODSNO,COLOR,SIZE,UNIT,PRICE from zansly_csv where CSV_NAME='"+csvFileName+"' and GOODSNO='"+eGOODS+"' and COLOR='"+eCOLOR+"' and SIZE='"+eSIZE+"'", null);
	if (cs.getCount()>0){
		cs.moveToFirst();
		eUNIT=cs.getDouble(4);
		ePRICE=cs.getDouble(5);
		edtCount.setText(""+eUNIT);  //件數
		edtUprice.setText(""+ePRICE);
		chkd=true;
	}
	cs.close();
	db.close();
	
	
	edtUprice.requestFocus();
	//edtPic.setImageBitmap(reflactionBitmap);
	  new AlertDialog.Builder(this).setTitle(data.iGoods+"-"+data.iCountry+"-"+data.iNumber+data.iName+"\n"+this.getString(R.string.detail_msg_fgalleryedu)).setView(v1).setNeutralButton("確認傳回", new DialogInterface.OnClickListener() {
	      public void onClick(DialogInterface dialog, int which) {
	    	  double nCount=Utilis.toDouble(edtCount.getText().toString());
	    	  double nPri=Utilis.toDouble(edtUprice.getText().toString());
	    	  {//Update Db 
					SQLiteDatabase db = Utilis.getDB(DataImports.this);				
					ContentValues value = new ContentValues();

					String[] args = {csvFileName,eGOODS,eCOLOR,eSIZE};				
					value.put("UNIT",nCount);								
					value.put("PRICE",nPri);
					
					@SuppressWarnings("unused")
					int success =db.update("zansly_csv", value,"CSV_NAME=? and GOODSNO=? and COLOR= ? and SIZE=?", args);
					db.close();
					makeData(DataImports.this,csvFileName);					
	    	  }
	      }
	    }).setNegativeButton("放棄編輯", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		      }
	    })
	    .show();
}
							

	public void showImport1Dialog(){
		DialogUtilis.showDialog(DataImports.this, getImport0Msg(), -1,
		new String[] { "放棄匯入", "開始匯入" }, new IDialog() {
			@Override
			public void onDialogFinish(int pos, String choice) {
				switch (pos) {
				case 0:
					break;
				case 1:
					boolean succes=startImport();
					if (succes==true) {
						Toast.makeText(DataImports.this,msgTitle+"/n已成功匯入本日暫存單:", Toast.LENGTH_SHORT).show();
						finish();
						
					}
					else
						Toast.makeText(DataImports.this,csvFileName+"匯入失敗!!\n    匯入失敗!!", Toast.LENGTH_SHORT).show();
					break;
				}
			}
		});	
		
	}

	private void getGoodsF(SQLiteDatabase db,Cursor cs){
		Cursor csG=db.rawQuery("select * from qdetail where GOODSNO='"+cs.getString(1)+"'", null);
		if (csG.getCount()>0){
			csG.moveToFirst();
			dataI.mGoodsNo=csG.getString(csG.getColumnIndex("GOODSNO"));
			dataI.mGoodsNos=cs.getString(1)+"-"+cs.getString(2)+"-"+cs.getString(3);	
			dataI.mGoodsName=csG.getString(csG.getColumnIndex("GOODSNAME"));
			dataI.mSourceNo=csG.getString(csG.getColumnIndex("SOURCENO"));
			dataI.mGoodsType=getGoodsTypeName(db,csG.getString(csG.getColumnIndex("GOODSTYPE")));
			dataI.mBatch=csG.getString(csG.getColumnIndex("BATCH"));
			dataI.mSupply=csG.getString(csG.getColumnIndex("SUPPLY"));
			dataI.mColors=csG.getString(csG.getColumnIndex("COLOR"));
			dataI.mSizes=csG.getString(csG.getColumnIndex("SIZE"));
			dataI.nSeason=csG.getInt(csG.getColumnIndex("SEASON"));	
			dataI.mUnit2=csG.getString(csG.getColumnIndex("COLORNO"));
			dataI.mOrddate=""+csG.getInt(csG.getColumnIndex("UNIT"));
			dataI.dAcost=cs.getDouble(4)*csG.getDouble(csG.getColumnIndex("P1"));
			dataI.dRate=csG.getDouble(csG.getColumnIndex("BILLRATE"));
			dataI.dP0=csG.getDouble(csG.getColumnIndex("P0"));
			dataI.dP1=csG.getDouble(csG.getColumnIndex("P1"));
			dataI.dP2=csG.getDouble(csG.getColumnIndex("P2"));
			dataI.dP3=csG.getDouble(csG.getColumnIndex("P3"));
			dataI.dP4=csG.getDouble(csG.getColumnIndex("P4"));
			dataI.dP5=csG.getDouble(csG.getColumnIndex("P5"));
			dataI.mPic=csG.getString(csG.getColumnIndex("PIC"));
			dataI.mCountry=getCountryName(db,csG.getString(csG.getColumnIndex("COUNTRY")));
			dataI.mYear=csG.getString(csG.getColumnIndex("UNIT2"));
		}
    csG.close();		
	}
	
	private String getGoodsTypeName(SQLiteDatabase db,String aQ){
		String typeName=aQ;
		String SQL="select GOODTYPE from qc_type where _ID='"+aQ+"'";
		Cursor cst=db.rawQuery(SQL,null);
		if (cst.getColumnCount()>0) {
			cst.moveToFirst();
			typeName=cst.getString(0);
		}
		cst.close();
		return  typeName;
	}
	
private String getColorName(SQLiteDatabase db,String aQ){
		String colorName=aQ;
		String SQL="select TXT from qc_color where NO='"+aQ+"'";
		Cursor cst=db.rawQuery(SQL,null);
		if (cst.getColumnCount()>0) {
			cst.moveToFirst();
			colorName=cst.getString(0);
		}
		cst.close();
		return  colorName;
	}
	
	private String getCountryName(SQLiteDatabase db,String aQ){
		String countryName=aQ;
		String SQL="select NAME from qc_country where _ID='"+aQ+"'";
		Cursor cst=db.rawQuery(SQL,null);
		if (cst.getColumnCount()>0) {
			cst.moveToFirst();
			countryName=cst.getString(0);
		}
		cst.close();
		return  countryName;
	}
	
	private boolean  startImport(){
		boolean succes=false;
		SQLiteDatabase db = Utilis.getDB(DataImports.this);
		Cursor cs=db.rawQuery("select CSV_NAME,GOODSNO,COLOR,SIZE,UNIT,PRICE from zansly_csv where CSV_NAME='"+csvFileName+"'", null);
		/*判斷 myKind 決定單別,取得單號,BANKNAME
		 *取得USER的 所有資訊
		 *布局HI的所有必要欄位
		 *逐筆商品必要的資料
		 *先I後H
		 */
		
		if (cs.getCount()>0){
			dataH = new PItemData();
			dataH.mUser=cust_no;
			if (myKind!=10)
			dataH.mUsername=getdeptF(cust_no,0).substring(getdeptF(cust_no,0).indexOf("/")+1);
			else
				dataH.mUsername=getdeptF(cust_no,1).substring(getdeptF(cust_no,1).indexOf("/")+1);
			
			dataH.nTrade=cust_tradetype;
			dataH.mDeptno=mDept;
			dataH.nID=0;
			dataH.mTR=mKind;
			dataH.mKind=mKind;
			dataH.mFno= Utilis.getNFormno(DataImports.this,mKind.substring(0,1)); //新單號
			dataH.mFormdate=DateUtil.getCurrentDate();
			dataH.mTime= DateUtil.getSystemTime().substring(2,14);
			dataH.mBankname=deptStr[0]+deptStr[1];
	    	dataH.dRate=Utilis.toDouble(Utilis.getIni(this,"INIH","BANKRATE",(myKind/10))); //交易的匯率
	    	dataH.mBankno=Utilis.getIni(this,"INIH","BANK",(myKind/10));
	    	dataH.mEmpid="匯入";
	    	dataH.mEmpname=Utilis.getIni(this,"INIH","EMPNAME",(myKind/10)); //櫃員名稱
	    	dataH.mIsconfirm="N";
	    	dataH.mIscheck="N";
	    	//HEAD 專屬的歸零項目
			dataH.mHandno="+0";	//理論上是貨品明細"+5 -1"
			dataH.mOrddate="";	//KEYIN
			dataH.mFinedate="";	//KEYIN
	 		dataH.dOrdcash=0;	//KEYIN
			dataH.dOrdcard=0;	//KEYIN
			dataH.dCash=0;			//KEYIN
			dataH.dCard=0;			//KEYIN
			dataH.dAtot=0;  		//總件數	<--來自於ITEMS的統計累加 UNIT10 20 30 40 等１不同單據
			dataH.dAsum=0; 		//應收		<--來自於ITEMS的統計累加 SUBPRICE
			dataH.dBsum=0; 		//實收 		<--使用者的強制輸入
			dataH.dCosts=0; 		//總成本 <--來自於ITEMS的統計累加 ACOST
			dataH.dTuresum=0;	//換算匯率後的實際金額 edBsum*edRate
			dataH.dDismoney=0;//折讓=應收-實收
			dataH.dAtm=0;
			dataH.dTrcash=0;
			dataH.mhPs=csvFileName;
			dataH.mhPs1="";
			dataH.mhPs2="";
			dataH.dInc=0;
			dataH.dMic=0;
			double asum=0,bsum=0,costs=0,inc=0,mic=0,atot=0;
			//db.beginTransaction();
//			try{
				while (cs.moveToNext()){
					double	aunit=cs.getDouble(4);
					dataI = new PItemData();
					getGoodsF(db,cs);				
					
					dataI.dUnit=0; //OR用
					
					switch (myKind){
					case 30:
						dataI.dUnit10=0;
						dataI.dUnit20=0;
						dataI.dUnit30=aunit;
						dataI.dUnit40=0;
						break;
					case 31:
						dataI.dUnit10=0;
						dataI.dUnit20=0;
						dataI.dUnit30=aunit;
						dataI.dUnit40=0;
						break;
					case 20:
						dataI.dUnit10=0;
						dataI.dUnit20=aunit;
						dataI.dUnit30=0;
						dataI.dUnit40=0;
						break;
					case 21:
						dataI.dUnit10=0;
						dataI.dUnit20=aunit;
						dataI.dUnit30=0;
						dataI.dUnit40=0;
						break;
					case 10:
						dataI.dUnit10=aunit;
						dataI.dUnit20=0;
						dataI.dUnit30=0;
						dataI.dUnit40=0;
						break;
					}
					dataI.dUnitprice=cs.getDouble(5);
					dataI.dRateprice=0;
					dataI.dRealsum=0;
					dataI.dsubprice=Utilis.dedb(cs.getDouble(5)*cs.getDouble(4),f123);
					asum+=Utilis.dedb(cs.getDouble(5)*cs.getDouble(4),f123);
					bsum=asum;
					if (cs.getDouble(4)>=0) inc+=cs.getDouble(4);
					if (cs.getDouble(4)<0) mic+=cs.getDouble(4);
					costs+=dataI.dAcost;
					atot+=cs.getDouble(4);
					
					dataI.mTime= DateUtil.getSystemTime().substring(2,14);
					dataI.mColor=cs.getString(2);
					dataI.mSize=cs.getString(3);
					dataI.mUnit1=getColorName(db,cs.getString(2));
					dataI.mPS="";  //PS
	
					ContentValues value = new ContentValues();
					value.put("ID",dataH.nID);
					value.put("TR",dataH.mTR);
					value.put("QKIND",dataH.mKind);
					value.put("FORMNO",dataH.mFno);
					value.put("HANDNO",dataH.mHandno);
					value.put("FORMDATE",dataH.mFormdate);
					value.put("CREATEDATETIME",dataH.mTime);
					value.put("ISCONFIRM",dataH.mIsconfirm);
					value.put("ISCHECK",dataH.mIscheck);
					value.put("EMPID","匯入");
					value.put("EMPNAME",dataH.mEmpname);
					value.put("USER",dataH.mUser);
					value.put("USERNAME",dataH.mUsername);
					value.put("TRADETYPE",dataH.nTrade);
					value.put("DEPTNO",dataH.mDeptno);
					value.put("GOODSNO",dataI.mGoodsNo);
					value.put("GOODSNOS",dataI.mGoodsNos);
					value.put("SOURCENO",dataI.mSourceNo);
					value.put("UNIT1",dataI.mUnit1);
					value.put("UNIT2",dataI.mUnit2);
					value.put("UNIT",dataI.mOrddate);
					value.put("UNITPRICE",dataI.dUnitprice);
					value.put("DISCOUNT",100);
					value.put("ACOST",dataI.dCosts);
					value.put("RATE",dataI.dRate);
					value.put("RATEPRICE",0);
					value.put("REALSUM",dataI.dCosts);
					value.put("SUBPRICE",dataI.dsubprice);
					value.put("P0",dataI.dP0);
					value.put("P1",dataI.dP1);
					value.put("P2",dataI.dP2);
					value.put("P3",dataI.dP3);
					value.put("P4",dataI.dP4);
					value.put("P5",dataI.dP5);
					
					value.put("COLOR",dataI.mColor);
					value.put("SIZE",dataI.mSize);
					value.put("ORDDATE",dataI.mOrddate);
					value.put("FINEDATE","0");
					value.put("BATCH",dataI.mBatch);
					value.put("SUPPLY",dataI.mSupply);
					value.put("GOODSTYPE",dataI.mGoodsType);
					value.put("GOODSNAME",dataI.mGoodsName);
					value.put("COLORS",dataI.mColors);
					value.put("SIZES",dataI.mSizes);
					value.put("UNIT10",dataI.dUnit10);
					value.put("UNIT20",dataI.dUnit20);
					value.put("UNIT30",dataI.dUnit30);
					value.put("UNIT40",dataI.dUnit40);
					value.put("PIC",dataI.mPic);
					value.put("PS","匯");
					value.put("SEASON",""+dataI.nSeason);
					value.put("COUNTRY",dataI.mCountry);
					value.put("YEAR",dataI.mYear);
					@SuppressWarnings("unused")
					long result = db.insert(TbName.QITEMS, null, value);
				}
				
				ContentValues value = new ContentValues();
				value.put("TR",dataH.mTR);
				value.put("ID", dataH.nID);
				value.put("QKIND",dataH.mKind );
				value.put("FORMNO",dataH.mFno);
				if (mic<0){
					value.put("HANDNO","+"+inc+""+mic);
				}else {
					value.put("HANDNO","+"+inc);
				}
				value.put("FORMDATE",dataH.mFormdate);
				value.put("CREATEDATETIME",dataH.mTime);
				value.put("ISCONFIRM",dataH.mIsconfirm);
				value.put("ISCHECK",dataH.mIscheck);
				value.put("ISLIST","");
				value.put("EMPID",dataH.mEmpid);
				value.put("EMPNAME",dataH.mEmpname);
				value.put("USER",dataH.mUser);
				value.put("USERNAME",dataH.mUsername);
				value.put("TRADETYPE",dataH.nTrade); //外幣			
				value.put("DEPTNO",dataH.mDeptno);
				value.put("ORDCASH",dataH.dOrdcash);
				value.put("ORDCARD",dataH.dOrdcard);
				value.put("CASH",dataH.dCash);
				value.put("CARD",dataH.dCard);
				value.put("ATOT",atot);
				value.put("ORDDATE",dataH.mOrddate);
				value.put("FINEDATE",dataH.mFinedate);
				value.put("ASUM",asum);
				value.put("BSUM",bsum);
				value.put("BILLRATE",1);
				value.put("COSTS",costs);
				value.put("TURESUM",costs);
				value.put("DISMONEY",0);
				value.put("BANKNO",dataH.mBankno);
				value.put("BANKNAME",dataH.mBankname);
				value.put("ATM",dataH.dAtm);
				value.put("ATMDATE",dataH.mAtmdate);
				value.put("TRCASH",dataH.dTrcash);
				value.put("PS",dataH.mhPs);
				value.put("PS1",dataH.mhPs1);
				value.put("PS2",dataH.mhPs2);
				
				@SuppressWarnings("unused")
				long result = db.insert(TbName.QHEAD, null, value);			
	            //db.setTransactionSuccessful();
	            succes=true;
//			}
//			catch(Exception e){
//			}
//			finally{
			          //db.endTransaction();
//			}
			
		}
		cs.close();
		db.close();
		return succes;
	}
	
	
	private int  startIniDb(Context context ,String csv_fn){
		int total_rec=0;
		SQLiteDatabase db_csv = Utilis.getDB(context);
		//第一段 無論如何 建立	TABLE  
		//若已存在,清除所有不是這個CSV的
		//@@@或保留最後? 10筆
		String SQL_INI=" CREATE TABLE  IF NOT EXISTS zansly_csvs ("+ 
				" CSV_NAME       VARCHAR( 80 ),"+
				" GOODSNO       VARCHAR( 20 ),"+
				" COLOR       VARCHAR( 4 ),"+
				" SIZE       VARCHAR( 8 ),"+
				" UNIT             DOUBLE ,"+
				" PRICE             DOUBLE)";
		db_csv.execSQL(SQL_INI);
		
		SQL_INI=" CREATE TABLE  IF NOT EXISTS zansly_csv ("+ 
				" CSV_NAME       VARCHAR( 80 ),"+
				" GOODSNO       VARCHAR( 20 ),"+
				" COLOR       VARCHAR( 4 ),"+
				" SIZE       VARCHAR( 8 ),"+
				" UNIT             DOUBLE ,"+
				" PRICE             DOUBLE)";
		db_csv.execSQL(SQL_INI);
		
		SQL_INI=" select * from zansly_csvs where CSV_NAME='"+csv_fn+"'";
		Cursor cs= db_csv.rawQuery(SQL_INI, null);
		if (cs.getCount()>0) total_rec=cs.getCount();
		
		//只保留唯一一組CSV,其餘清除
		String[] args = {csv_fn};
		@SuppressWarnings("unused")
		int xx=db_csv.delete("zansly_csv", "CSV_NAME<>? ", args);
		xx=db_csv.delete("zansly_csvs", "CSV_NAME<>? ", args);
		
		if (cs!=null) cs.close();
		db_csv.close();
		
		return total_rec;
	}
	
	private void firstInsertCSV(Context context ,String csv_fn,int mode){
		//mode 1載入 0不載入繼續
		if (mode==1){
		File localFile = new File(csv_fn);
		 if (localFile.exists()){

			SQLiteDatabase db = Utilis.getDB(context);
				String encodout = "UTF8";
				StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
				String sepa[]={",",";","\t"};
				int sepaK=-1;
				//AA123456-01-F;BB654321-03-F;
				//貨號-色-尺;
				
				FileInputStream fis;
				try {
					fis = new FileInputStream(localFile);
					InputStreamReader isr = new InputStreamReader(fis, encodout);
					Reader in = new BufferedReader(isr);
					int ch;
					try {
						/*將CSV檔一一存入zansly_csvs
							" CSV_NAME       VARCHAR( 80 ),"+
							" GOODSNO       VARCHAR( 20 ),"+
							" COLOR       VARCHAR( 4 ),"+
							" SIZE       VARCHAR( 8 ),"+
							" UNIT             DOUBLE,"+
							" PRICE             DOUBLE)";
						*/
						while ((ch = in.read()) > -1) {
							buffers.append((char)ch);
							if(buffers.toString().indexOf("\r\n")>0){
								String fields=buffers.toString().substring(0,buffers.toString().length()-2);
								if (sepaK<0) {
									if (fields.indexOf(sepa[0])>=2) sepaK=0;
									else if (fields.indexOf(sepa[1])>=2) sepaK=1;
									else  if (fields.indexOf(sepa[2])>=2) sepaK=2;
								}
								if (sepaK>=0){
								String[] arrayField = fields.toString().split(sepa[sepaK]);
									if (arrayField.length>=2){
										if(Utilis.toDouble(arrayField[1])!=0 && Utilis.toDouble(arrayField[2])>0){
											
											String DGOODS="";String DCOLORNO="00";String DSIZES="F";
											if (arrayField[0].indexOf("-") !=arrayField[0].lastIndexOf("-")){ 
												DGOODS=arrayField[0].substring(0,arrayField[0].indexOf("-"));
												DCOLORNO=arrayField[0].substring(arrayField[0].indexOf("-")+1,arrayField[0].lastIndexOf("-"));
												DSIZES=arrayField[0].substring(arrayField[0].lastIndexOf("-")+1).trim();
											}else if(arrayField[0].indexOf("-") >0){
												DGOODS=arrayField[0].substring(0,arrayField[0].indexOf("-"));
												DCOLORNO=arrayField[0].substring(arrayField[0].indexOf("-")+1).trim();
												DSIZES="F";
											}
											
											ContentValues value = new ContentValues();
											value.put("CSV_NAME",csv_fn);								
											value.put("GOODSNO",DGOODS);								
											value.put("COLOR",DCOLORNO);								
											value.put("SIZE",DSIZES);								
											value.put("UNIT",Utilis.toDouble(arrayField[1]));								
											value.put("PRICE",Utilis.toDouble(arrayField[2]));								
											@SuppressWarnings("unused")
											long result = db.insert("zansly_csvs", null, value);
										}
									}	
								}
								buffers.delete(0, buffers.toString().length()	);	
							}
						}
						String SQL="insert into zansly_csv (CSV_NAME,GOODSNO,COLOR,SIZE,UNIT,PRICE )";
						SQL+=" select a.CSV_NAME,a.GOODSNO,a.COLOR,a.SIZE,sum(a.UNIT),a.PRICE from zansly_csvs as a ";
						SQL+="group by a.GOODSNO,a.COLOR,a.SIZE,a.PRICE";
						db.execSQL(SQL);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
					
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
				db.close();
				}
		 }
		}
    	makeData(context,csv_fn);
	}
	
	public String[] getDetail(Context context,SQLiteDatabase db,String aGoods,String aColno,String aSize){
		String[] lists=null;
		StringBuffer lst=new StringBuffer();
		String SQL="select  GOODSNO,GOODSNAME,COLORNO,COLOR,SIZE,PIC from qdetail where GOODSNO='"+aGoods+"' order by BATCH desc limit 1";
		Cursor cs=db.rawQuery(SQL , null);
		//adapter GOODSNO,GOODSNAME,COLOR,PIC,
		
		if (cs.getCount()>0){
			cs.moveToFirst();
			String mColno[]=cs.getString(2).split("，");
			String mCol[]=cs.getString(3).split("，");
			int loc=-1;
			for(int i=0;i<(mColno.length);i++){
				if (mColno[i].equalsIgnoreCase(aColno)){
					loc=i;
					break;
				}
			}
			String aColorname="混色";
			if (loc>=0) aColorname=mCol[loc];
			loc=-1;
			
			//找出顏色/名稱/尺寸
			String mSiz[]=cs.getString(4).split(",");
			for(int i=0;i<(mSiz.length);i++){
				if (mSiz[i].equalsIgnoreCase(aSize)){
					loc=i;
					break;
				}
			}
			String aTrueSize="F"; 
			if (loc>=0) aTrueSize=mSiz[loc];
			
				lst.append(aGoods+"!&!"+cs.getString(1)+"!&!"+aColno+"!&!"+aColorname+"!&!"+aTrueSize+"!&!"+cs.getString(5));
				//貨號 品名 色號 色名 尺寸 圖檔名
				lists=lst.toString().split("!&!");
		}
		if (cs!=null ) cs.close();
			return lists;
	}
	
}
