package com.cwbuyer.lib;

import java.io.File;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
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.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
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.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.cwbuyer.format.IDialog;
import com.cwbuyer.format.KeySet;
import com.cwbuyer.main.APos.PItemKind;
import com.pwbuyer.main.R;

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
@SuppressLint("HandlerLeak")
@SuppressWarnings("unused")
public class QRep_02 extends Activity{
	
	ReportAdapter mAdapter = null;
	ReportAdapter mAdapter1 = null;
	ReportAdapter mAdapter2 = null;
	
	
	TextView mTextDuration = null;
	
	int mMode = KeySet.SearchMode.MONTH;
	DecimalFormat df = new DecimalFormat();
	private final int RESULT_GALLERY=6666; 		//GALLERY
	
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5));
	int ORS=Utilis.toInt(Utilis.getIni(this, "SYS","DEPT_SEND", 6));
	private String[] compStr =Utilis.getIni(this,"USER","COMPANY",9).split("!&!");
	//if (ORS!=2) //含預購帳
	//@@@是否在總倉狀態,可以統計各門市會員的對帳單
	/** State :  true 正式 , false 樣品*/
	String mEndDay = null;
	String mStartDay = null;
	String dbEndDay = null;
	String dbStartDay = null;
	int Pswd=0;
	int nPart=0;
	String [] barStr;
	int Loca=0;	
	String sepa="\r\n";
	StringBuffer sPrintB = new StringBuffer();
	StringBuffer mBuf = new StringBuffer();
	
	String USERN;
	int locations=0;	
	String mDept ="";
	int mCloud=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT_SEND",4));
	String clouds="http://"+Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 2)+File.separator;
	String uriAPI1=clouds+"qrep02_1.php";
	String uriAPI2=clouds+"qrep02_2.php";
	String uriAPI3=clouds+"qrep02_3.php";
	String uriAPIP=clouds+"qrep02_p.php";
	String uriAPIPA4=clouds+"qrep02_pA4.php";

	public ProgressDialog myDialog = null;
	protected static final int REFRESH_DATA = 0x00000001;
	
	//發展為長按而啟動的功能
	String[] menu_E={ "廠商", "出貨","銷貨","員購"};
	String[] menu_S={ "--------","交易對帳單","列印交易對帳單","列印交易明細對帳單","列印交易對帳A4單","列印交易明細對帳A4單", "返回"};
	String[] menu_B={ "交易明細清單", "返回"};

	String mKind=null; //單別 102030405060
	
	int nKind=0;
	int isPrintDetail=3; //是否為明細對帳單
	DatePicker dp1;
	DatePicker dp2;
   	String mWho="";

   	double TT10=0;  	//總進貨量_BSUM
   	double TM10=0; 	//總進貨額_(ASUM)
   	double TT30=0;	//總銷貨量_CASH
   	double TM30=0;	//總銷貨額_CARD
   	double TS30=0;	//總銷貨額_BSUM-CASH-CARD-ORDCASH-ORDCARD
   	double StkT=0;		//總存貨量
   	double StkM=0;	//總存貨額
   	double R10;
   	double TR10;
   	
   	double T10=0;  	//BSUM
   	double T11=0;  	//ASUM
   	double M10=0; 	//本進貨額
   	double T30=0;		//本銷貨量
   	double M30=0;	//本銷貨額
   	double S30=0;	//本銷貨額
   	double Profit=0; 	//本期毛利
   	double Profits=0; //本期利率
   	
   	double TAtm=0;
   	double MAtm=0;
   	double TTrcash=0;
   	double MTrcash=0;
	
	private int mYear1 = 0;
	private int mYear2 = 0;
	private int mMonth1 = 0;
	private int mMonth2 = 0;
	private int mDay1 = 0;
	private int mDay2 = 0;
	
	ListView mListView = null;
	ListView mListView1 = null;
	ListView mListView2 = null;
	
	int Floor=0;
	
//For  Table
	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>();  // 尺寸欄資料
	

	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;
		
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrep01);
		df.applyPattern( "#,##0");

        mTextDuration = (TextView)findViewById(R.id.text_duration);
        //@@應增加營業時間的判斷而視為當日或前一天
        mStartDay =DateUtil.getCurrentDate();  //2012/10/15 將 batch 視為當日的關鍵"/"
        mEndDay=mStartDay;
        mDept = getIntent().getStringExtra("QRep_Dept");
        barStr=Utilis.getIni(this,"SYS","BAR_IP",9).split("!&!");
        //暫時不開放外部決定哪一種方式 預設為 週
        nKind =getIntent().getIntExtra("QRep_02", PItemKind.TR30); //預設為客戶對帳單
        mKind=""+nKind; if (nKind==11) mKind="10";
        //11 視為 廠商對帳依配貨處 否則 10 依商品檔的供應商
        mWho =getIntent().getStringExtra("QRep_who"); //來自QPosff or QCustff
        if (mWho.equalsIgnoreCase("QCustff") || mWho.equalsIgnoreCase("QFactff") ){
        	USERN=getIntent().getStringExtra("QRep_user"); //來自QCustff
        }
        //Toast.makeText(QRep_02.this,mDept , Toast.LENGTH_LONG).show();        
        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());		//離開
        
        ((LinearLayout)findViewById(R.id.layout_bottom)).setVisibility(View.GONE);
        ((LinearLayout)findViewById(R.id.layout_tops)).setVisibility(View.GONE);
        ((LinearLayout)findViewById(R.id.layout_top)).setVisibility(View.VISIBLE);
        
        ((Button)findViewById(R.id.btn_prev_date)).setOnClickListener(new MainClick());//上一
        ((Button)findViewById(R.id.btn_next_date)).setOnClickListener(new MainClick());//下一
        
        ((Button)findViewById(R.id.btn_btn0)).setOnClickListener(new MainClick());	//日        
        ((Button)findViewById(R.id.btn_btn1)).setOnClickListener(new MainClick());	//週        
        ((Button)findViewById(R.id.btn_btn2)).setOnClickListener(new MainClick());  //月
        ((Button)findViewById(R.id.btn_btn3)).setOnClickListener(new MainClick());//季
        ((Button)findViewById(R.id.btn_btn4)).setText("輸出");
        ((Button)findViewById(R.id.btn_btn4)).setOnClickListener(new MainClick()); //批號

    	((TextView)findViewById(R.id.text_r10t)).setText("前帳:");
    	((TextView)findViewById(R.id.text_rp0t)).setText("未結:");
    	
        if(nKind!=PItemKind.TR10 && nKind!=PItemKind.TR20 && nKind!=PItemKind.TR21){
        	((TextView)findViewById(R.id.text_t10t)).setText("應收:");
        	((TextView)findViewById(R.id.text_t30t)).setText("收現:");
        	((TextView)findViewById(R.id.text_r30t)).setText("未收:");
        	((TextView)findViewById(R.id.text_tott)).setText("訂金:");
        } else {
        	((TextView)findViewById(R.id.text_t10t)).setText("");
        	((TextView)findViewById(R.id.text_t30t)).setText("");
        	((TextView)findViewById(R.id.text_r30t)).setText("");
        	((TextView)findViewById(R.id.text_tott)).setText("");
        }
        
        mListView = (ListView)findViewById(R.id.list_item);
        mListView1 = (ListView)findViewById(R.id.list_item1);
        mListView2 = (ListView)findViewById(R.id.list_item2);

        mAdapter = new ReportAdapter(this);
        mAdapter1 = new ReportAdapter(this);
        mAdapter2 = new ReportAdapter(this);
        
        mListView.setAdapter(mAdapter);
        mListView1.setAdapter(mAdapter1);
        mListView2.setAdapter(mAdapter2);
        
        if (!Utilis.getIni(this,"SYS","DEPT",1).equalsIgnoreCase(Utilis.getIni(this,"SYS","DEPT",6))) nPart=1;  //門市版        
        //原先就是執行一遍 因為不會中途改變模式
        //現在是可以切換
        //只要一切換,都會從最近日期範圍貨最近一批最近一季起算
        chkMode();
        
   mListView.setOnItemClickListener(new OnItemClickListener() {
	   @Override
		public void onItemClick(AdapterView<?> parent, View v,
		int position, long ids) {
			// TODO Auto-generated method stub
			locations=position;
			//if (mWho.equalsIgnoreCase("QCustff")) menu_S=menu_S1; else menu_S=menu_S0;
			Utilis.runVibrate(QRep_02.this);
			DialogUtilis.showDialog(QRep_02.this, "請選擇以下功能", -1,
			menu_S, new IDialog() {
			@Override
				public void onDialogFinish(int pos, String choice) {
				switch (pos) {
					case 0: //對帳明細維護
						break;
					case 1: //顯示對帳單
					{
						RepData datas = (RepData) mAdapter.getItem(locations);
						int Sok=0;
						String mSQLstr=makeSQLstr(datas, mBuf);
								//雲端
						if  (Utilis.haveInternet(QRep_02.this) && Utilis.toInt(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 3))==1 && mCloud>0){
								StringBuffer bfstr = new StringBuffer();
								StringBuffer bfstrF = new StringBuffer();

									bfstr.append(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 2)).append(";");
									bfstrF.append("UID").append(";");
									bfstr.append(mKind).append(";");
									bfstrF.append("QKIND").append(";");
									bfstr.append(USERN).append(";");
									bfstrF.append("USER").append(";");
									bfstr.append(mDept).append(";");
									bfstrF.append("DEPTNO").append(";"); 
									bfstr.append(mStartDay).append(";");
									bfstrF.append("STARTDAY").append(";");
									bfstr.append(mEndDay).append(";");
									bfstrF.append("ENDDAY").append(";"); 
									bfstr.append(mSQLstr);
									bfstrF.append("SQLADD");  //總倉代號 名稱
									
									final String []fields=bfstr.toString().split(";");
									final String []fieldFs=bfstrF.toString().split(";");
									
								      myDialog = ProgressDialog.show(QRep_02.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
									  
								      new Thread()
								      { 
								        public void run()
								        { 
								          try
								          { 
												HttpPost httpRequest = new HttpPost(uriAPI2);
												// Post運作傳送變數必須用NameValuePair[]陣列儲存
												Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI2);

												List<NameValuePair> params = new ArrayList<NameValuePair>();
												for(int x=0;x<fields.length;x++){
													params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
												}
												try {
													// 發出HTTP request(請求) 
													httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
													// 取得HTTP response(回傳) 
													HttpResponse httpResponse = new DefaultHttpClient()
															.execute(httpRequest);
													// 若狀態碼為200 ok 
													if (httpResponse.getStatusLine().getStatusCode() == 200)
													{
														// 取出回應字串
														//Toast.makeText(QRep_12.this, "取得前200", Toast.LENGTH_LONG).show();
														String strResult = EntityUtils.toString(httpResponse	.getEntity());
														//Toast.makeText(QRep_12.this, "取得"+strResult, Toast.LENGTH_LONG).show();
														mHandlerQDR_22.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
														
													}
												} catch (Exception e)
												{
													e.printStackTrace();
												}

								          }
								          catch (Exception e)
								          {
								            e.printStackTrace();
								          }
								          finally
								          {
								            // 卸載所建立的myDialog物件。
								            myDialog.dismiss();
								          }
								        }
								      }.start(); 
					}else{	
								//單機
								SQLiteDatabase db = Utilis.getDB(QRep_02.this);
								Cursor cs=db.rawQuery(mSQLstr, null);
								
							if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 || nKind==11){
									if (cs.getCount()>0){
										while (cs.moveToNext()){
											RepData data = new RepData();							
											data.iGoods=cs.getString(1);
											data.iName=cs.getString(0);
											data.iCountry=cs.getString(2);
											if(nKind!=11){
												if (cs.getInt(9)!=0)
													data.iImpo="應收:"+new BigDecimal(Math.round(cs.getDouble(8))).toString()+"(折"+cs.getString(9)+")";
												else
													data.iImpo="應收:"+new BigDecimal(Math.round(cs.getDouble(8))).toString();
											}else{
												if (cs.getInt(9)!=0)
													data.iImpo="應付:"+new BigDecimal(Math.round(cs.getDouble(8))).toString()+"(折"+cs.getString(9)+")";
												else
													data.iImpo="應付:"+new BigDecimal(Math.round(cs.getDouble(8))).toString();
											}
											data.iMoney="現金:";data.iCompany="訂金";
											if (cs.getDouble(4)!=0) data.iMoney=data.iMoney+new BigDecimal(Math.round(cs.getDouble(4))).toString();
											if (cs.getDouble(5)!=0) data.iMoney=data.iMoney+" 票刷:"+new BigDecimal(Math.round(cs.getDouble(5))).toString();
											if (cs.getDouble(10)!=0) data.iMoney=data.iMoney+" 匯:"+new BigDecimal(Math.round(cs.getDouble(10))).toString();
											
											if (cs.getDouble(6)!=0) data.iCompany=data.iCompany+new BigDecimal(Math.round(cs.getDouble(6))).toString();
											if (cs.getDouble(7)!=0) data.iCompany=data.iCompany+" 票刷:"+new BigDecimal(Math.round(cs.getDouble(7))).toString();
											if (cs.getDouble(11)!=0) data.iCompany=data.iCompany+" 墊:"+new BigDecimal(Math.round(cs.getDouble(11))).toString();
											mAdapter1.mList.add(data);
										}
									Sok=2;	
									}
									
							}else if (nKind==PItemKind.TR10){//廠商進貨單
								
								if (cs.getCount()>0){
									while (cs.moveToNext()){
										RepData data = new RepData();							
										data.iGoods=cs.getString(1);
										data.iName=cs.getString(0);
										data.iImpo="應付:"+new BigDecimal(Math.round(cs.getDouble(2))).toString();
										data.iMoney="件數:"+cs.getString(3);
										data.iCompany="款數:"+cs.getString(4);
										mAdapter1.mList.add(data);
									}
									Sok=2;	
								}
							}else{//門市對帳單
								if (cs.getCount()>0){
									while (cs.moveToNext()){
										RepData data = new RepData();
										data.iGoods=cs.getString(1);
										data.iName=cs.getString(0);
										data.iCountry=cs.getString(2);
										if (datas.iFormdate.equalsIgnoreCase(cs.getString(12)))
											data.iImpo="出貨:"+new BigDecimal(Math.round(cs.getDouble(8)+cs.getDouble(11))).toString();
										else
											data.iImpo="轉給("+cs.getString(12)+")"+new BigDecimal(Math.round(cs.getDouble(8)+cs.getDouble(11))).toString();
										
										data.iMoney="現金:";data.iCompany="訂金";
										if (cs.getDouble(4)!=0) data.iMoney=data.iMoney+new BigDecimal(Math.round(cs.getDouble(4))).toString();
										if (cs.getDouble(5)!=0) data.iMoney=data.iMoney+" 票刷:"+new BigDecimal(Math.round(cs.getDouble(5))).toString();
										if (cs.getDouble(10)!=0) data.iMoney=data.iMoney+" 匯:"+new BigDecimal(Math.round(cs.getDouble(10))).toString();
										
										if (cs.getDouble(6)!=0) data.iCompany=data.iCompany+new BigDecimal(Math.round(cs.getDouble(6))).toString();
										if (cs.getDouble(7)!=0) data.iCompany=data.iCompany+" 票刷:"+new BigDecimal(Math.round(cs.getDouble(7))).toString();
										if (cs.getDouble(11)!=0) data.iCompany=data.iCompany+" 墊:"+new BigDecimal(Math.round(cs.getDouble(11))).toString();
										mAdapter1.mList.add(data);
									}
									Sok=2;	
								}
							}
							cs.close();
							db.close();
							if (Sok!=0){
								Floor=1;
								((TextView)findViewById(R.id.text_t10t)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_m10)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_r10t)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_t30t)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_m30)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_r30t)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_tott)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_tot)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_mtot)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_rp0t)).setVisibility(View.GONE);
								((TextView)findViewById(R.id.text_rp0)).setVisibility(View.GONE);
								
								((TextView)findViewById(R.id.text_r10)).setText(datas.iImpo);//總前帳
								((TextView)findViewById(R.id.text_t10)).setText(datas.iName);//總應收 				
								((TextView)findViewById(R.id.text_t30)).setText(datas.iCountry);  //現金總收
								((TextView)findViewById(R.id.text_r30)).setText(datas.iCompany);//總結欠
								
						        ((Button)findViewById(R.id.btn_btn0)).setVisibility(View.INVISIBLE);	//日        
						        ((Button)findViewById(R.id.btn_btn1)).setVisibility(View.INVISIBLE);	//週        
						        ((Button)findViewById(R.id.btn_btn2)).setVisibility(View.INVISIBLE);  //月
						        ((Button)findViewById(R.id.btn_btn3)).setVisibility(View.INVISIBLE);//季
						        ((Button)findViewById(R.id.btn_btn4)).setVisibility(View.INVISIBLE);
						        ((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.INVISIBLE);//上一
						        ((Button)findViewById(R.id.btn_next_date)).setVisibility(View.INVISIBLE);//下一

								((ListView)findViewById(R.id.list_item)).setVisibility(View.GONE);
								((ListView)findViewById(R.id.list_item1)).setVisibility(View.VISIBLE);
								
								mAdapter1.notifyDataSetChanged();
								mTextDuration.setText(datas.iFormdate+"/ "+ mStartDay + "~" + mEndDay);
							}
						}
						break;
					}
					case 2: //列印對帳單
					{
						isPrintDetail=0;
						ListPrint();
						break;
					}
					case 3: //列印明細對帳單
					{
						isPrintDetail=1;
						ListPrint();
						break;
					}
					case 4: //列印A4對帳單
					{
						isPrintDetail=3;
						ListPrintA4();
						break;
					}
					case 5: //列印明細A4對帳單
					{
						isPrintDetail=4;
						ListPrintA4();
						break;
					}
					case 6: //返回
					{
						break;
					}
				}
			}				
		});
	}
});

        mListView1.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				locations=position;
				
				Utilis.runVibrate(QRep_02.this);
				DialogUtilis.showDialog(QRep_02.this, "請選擇以下功能", -1,
				menu_B, new IDialog() {
					@Override
					public void onDialogFinish(int pos, String choice) {
						switch (pos) {
							case 0: //每單交易明細
							{
									if (mAdapter2.mList != null) {
										mAdapter2.mList.clear();
									}
									if (mAdapter1.getCount()>0){
										RepData datas = (RepData) mAdapter1.getItem(locations);
										mBuf = new StringBuffer();
										mBuf.append("select GOODSNO,GOODSNAME,COLORS,SIZES,PIC,max(UNITPRICE),sum(UNIT"+(nKind/10*10)+"),max(DISCOUNT),sum(SUBPRICE) ");
										mBuf.append(" from qitems ")
									    .append(" where  FORMNO='"+datas.iName+"'");
										if (nKind==PItemKind.TR10 ) mBuf.append(" and SUPPLY ='"+USERN+"'");
										mBuf.append(" group by GOODSNO,GOODSNAME,COLORS,SIZES,PIC");
										
										if  (Utilis.haveInternet(QRep_02.this) && Utilis.toInt(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 3))==1 && mCloud>0){
											StringBuffer bfstr = new StringBuffer();
											StringBuffer bfstrF = new StringBuffer();

											bfstr.append(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 2)).append(";");
												bfstrF.append("UID").append(";");
												bfstr.append(mKind).append(";");
												bfstrF.append("QKIND").append(";");
												bfstr.append(USERN).append(";");
												bfstrF.append("USER").append(";");
												bfstr.append(mDept).append(";");
												bfstrF.append("DEPTNO").append(";"); 
												bfstr.append(mStartDay).append(";");
												bfstrF.append("STARTDAY").append(";");
												bfstr.append(mEndDay).append(";");
												bfstrF.append("ENDDAY").append(";"); 
												bfstr.append(mBuf.toString());
												bfstrF.append("SQLADD");  //總倉代號 名稱
												
												
												final String []fields=bfstr.toString().split(";");
												final String []fieldFs=bfstrF.toString().split(";");
												
											      myDialog = ProgressDialog.show(QRep_02.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
												  
											      new Thread()
											      { 
											        public void run()
											        { 
											          try
											          { 
															HttpPost httpRequest = new HttpPost(uriAPI3);
															// Post運作傳送變數必須用NameValuePair[]陣列儲存
															Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI3);

															List<NameValuePair> params = new ArrayList<NameValuePair>();
															for(int x=0;x<fields.length;x++){
																params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
															}
															try {
																// 發出HTTP request(請求) 
																httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
																// 取得HTTP response(回傳) 
																HttpResponse httpResponse = new DefaultHttpClient()
																		.execute(httpRequest);
																// 若狀態碼為200 ok 
																if (httpResponse.getStatusLine().getStatusCode() == 200)
																{
																	// 取出回應字串
																	String strResult = EntityUtils.toString(httpResponse	.getEntity());
																	//Toast.makeText(QRep_12.this, "取得"+strResult, Toast.LENGTH_LONG).show();
																	mHandlerQDR_23.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
																	
																}
															} catch (Exception e)
															{
																e.printStackTrace();
															}

											          }
											          catch (Exception e)
											          {
											            e.printStackTrace();
											          }
											          finally
											          {
											            // 卸載所建立的myDialog物件。
											            myDialog.dismiss();
											          }
											        }
											      }.start(); 
										

										} else {												
										//單機
											SQLiteDatabase db = Utilis.getDB(QRep_02.this);
											
											Cursor cs=db.rawQuery(mBuf.toString(), null);
											if (cs.getCount()>0){
												while (cs.moveToNext()){
													RepData data = new RepData();							
													data.iGoods=cs.getString(0)+"/"+cs.getString(1);
													data.iPic=cs.getString(4);
													data.iName=cs.getString(2);
													data.iCountry=cs.getString(3);
													data.iImpo="件數:"+cs.getString(6);
													data.iMoney="單價:"+cs.getString(5)+" 折:"+cs.getString(7);
													data.iCompany="小計:"+cs.getString(8);
													mAdapter2.mList.add(data);
												}
											Floor=2;
											mAdapter2.notifyDataSetChanged();
											
											((ListView)findViewById(R.id.list_item1)).setVisibility(View.GONE);
											((ListView)findViewById(R.id.list_item2)).setVisibility(View.VISIBLE);
											
											}
											cs.close();
											db.close();
										}	
									}
								break;
							}
							case 1: //返回
							{
								break;
							}
						}
					}				
				});
			}
		});
        
        
}	
	
	public void onResume(){
		super.onResume();
		
		//表示非外來程式 
//			getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
		
		DBCloud.aa0_aa1_auto_HI(this,nKind);
		
		Floor=0;

        ((Button)findViewById(R.id.btn_btn0)).setVisibility(View.VISIBLE);	//日        
        ((Button)findViewById(R.id.btn_btn1)).setVisibility(View.VISIBLE);	//週        
        ((Button)findViewById(R.id.btn_btn2)).setVisibility(View.VISIBLE);  //月
        ((Button)findViewById(R.id.btn_btn3)).setVisibility(View.VISIBLE);//季
        ((Button)findViewById(R.id.btn_btn4)).setVisibility(View.VISIBLE);
		((ListView)findViewById(R.id.list_item)).setVisibility(View.VISIBLE);
        ((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);//上一
        ((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);//下一
		((ListView)findViewById(R.id.list_item1)).setVisibility(View.GONE);
		
		((TextView)findViewById(R.id.text_t10t)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_m10)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_r10t)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_t30t)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_m30)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_r30t)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_tott)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_tot)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_mtot)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_rp0t)).setVisibility(View.VISIBLE);
		((TextView)findViewById(R.id.text_rp0)).setVisibility(View.VISIBLE);
		

			mAdapter.notifyDataSetChanged();
		}
	
	private void setCondition(){
				mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
	}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	public void getGroupData(Context context, String startDayX, String endDayX, String condition, String conditionValue) {
					
			if (mAdapter.mList != null) {
				mAdapter.mList.clear();
			}
			
//			SQLiteDatabase db = Utilis.getDB(context);
//			try {
				Cursor cursorGroup = null;

				StringBuffer bufCategory = new StringBuffer();
				if(startDayX != null && startDayX.length() > 0)	dbStartDay = startDayX.replace("/", "-");
				if(endDayX != null && endDayX.length() > 0) dbEndDay = endDayX.replace("/", "-");
			
				 Toast.makeText(QRep_02.this, "對帳自_"+startDayX+"至_"+endDayX+"為止", Toast.LENGTH_LONG).show();

				T11=0;TT10=0;  TM10=0; 	TT30=0;	TM30=0;
				TS30=0;	 StkT=0;		StkM=0;	
				TAtm=0;MAtm=0;TTrcash=0;MTrcash=0;
				Profit=0; Profits=0;	TR10=0; 
				//先算出到本期為止,是否結清
				//沒結清者,才會進一步對帳
				bufCategory=bufCategory.delete(0, bufCategory.toString().length());
				if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41  || nKind==11){
					if (nKind!=11)//廠商對帳
			    	bufCategory.append("select A.USER,B.CUSTNAME,"); //
			    	else
				    	bufCategory.append("select A.USER,B.FACTNAME,");//
			    		
					bufCategory.append("sum(A.BSUM),sum(A.COSTS),sum(A.CASH),sum(A.CARD),sum(A.ORDCASH),sum(A.ORDCARD),sum(A.ATOT),sum(A.DISMONEY),sum(A.ASUM),sum(A.ATM),sum(A.TRCASH)");
					//2BSUM,3COSTS,4CASH,5CARD,6ORDCASH,7ORDCARD,8ATOT,9DISMONY,10ASUM,11ATM,12TRCASH
					if (nKind!=11)//廠商對帳
						bufCategory.append(" from qhead A join qcust B on A.USER=B.CUSTNO");
					else
						bufCategory.append(" from qhead A join qfact B on A.USER=B.FACTNO");
						
				    bufCategory.append(" where");
				    bufCategory.append(" ( (A.FORMDATE <= '").append(dbEndDay).append("'  and A.ISCONFIRM='Y' and A.ISCHECK='N' ) or ")
					.append(" ( (A.FINEDATE<>'' and A.FINEDATE <= '").append(dbEndDay).append("')  and A.ISCONFIRM='Y' and A.ISCHECK='N' )");
					if (ORS!=2){
						bufCategory.append(" or  ( (A.ORDDATE<>'' and A.ORDDATE <= '").append(dbEndDay).append("') and ((A.ISCONFIRM='Y') or (A.ISCONFIRM='N' and A.ISCHECK='Y' ) )) )");
					}else{
						bufCategory.append(")");
					}
					if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31)													
						bufCategory.append(" and A.DEPTNO='"+mDept+"' and A.QKIND like '"+mKind.substring(0,1)+"%'");
					else
						bufCategory.append(" and A.QKIND like '"+mKind.substring(0,1)+"%'");
						
				    if (mWho.equalsIgnoreCase("QCustff")) bufCategory.append(" and A.USER = '"+USERN+"'");  
				    	bufCategory.append(" group by A.USER ");
				    if (!mWho.equalsIgnoreCase("QCustff"))	bufCategory.append(" having sum(A.BSUM-A.CASH-A.CARD-A.ORDCASH-A.ORDCARD-A.ATM)<>0 ");
				    	bufCategory.append(" order by A.USER ");
				}else if (nKind==PItemKind.TR10){//廠商進貨單
					bufCategory.append("SELECT  qitems.SUPPLY, qfact.FACTNAME," +
							"min(FORMDATE) as MINDATE,max(FORMDATE) as MAXDTE," +
							"count(distinct qitems.GOODSNO) as TOTGOODS," +
							"sum( qitems.UNIT10) as TOTCOME,sum(qitems.SUBPRICE) as TOTMONEY " +
							"FROM qitems join qfact " +
							"on qitems.SUPPLY=qfact.FACTNO " +
							"where qitems.FORMDATE>='"+dbStartDay+"' " +
							"and qitems.FORMDATE<='"+dbEndDay+"'");
				    if (mWho.equalsIgnoreCase("QFactff")) bufCategory.append(" and qitems.SUPPLY = '"+USERN+"' and ISCONFIRM='Y'");  
					
			    	bufCategory.append(" and qitems.QKIND='10' group by  qitems.SUPPLY");
				} else{//門市對帳單
					bufCategory.append("SELECT  qitems.USER, qcust.CUSTNAME," +
							"min(qitems.FORMDATE) as MINDATE,max(qitems.FORMDATE) as MAXDTE," +
							"count(distinct qitems.GOODSNO) as TOTGOODS," +
							"sum( qitems.UNIT20) as TOTCOME,sum(qitems.SUBPRICE) as TOTMONEY " +
							"FROM qitems join qcust " +
							"on qitems.USER=qcust.CUSTNO " +
							"where qitems.FORMDATE>='"+dbStartDay+"' " +
							"and qitems.FORMDATE<='"+dbEndDay+"'");
				    bufCategory.append(" and qitems.QKIND like '"+mKind.substring(0,1)+"%' and ISCONFIRM='Y'");
				    if (mWho.equalsIgnoreCase("QCustff")) bufCategory.append(" and qitems.USER = '"+USERN+"'");  
			    	bufCategory.append(" group by qitems.USER order by qitems.USER ");
				}
			    //已上取得所有成員,至今所有帳,不包括後面日期的帳
			    //只要再算出本期的帳,相減就得到本期帳
				
				//雲端是要把 SQL語法 傳送
				//對帳雲端版_需要
				if  (Utilis.haveInternet(QRep_02.this) && Utilis.toInt(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 3))==1 && mCloud>0){
					StringBuffer bfstr = new StringBuffer();
					StringBuffer bfstrF = new StringBuffer();
					
						bfstr.append(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 2)).append(";");
						bfstrF.append("UID").append(";");
						bfstr.append(mKind).append(";");
						bfstrF.append("QKIND").append(";");
						bfstr.append(USERN).append(";");
						bfstrF.append("USER").append(";");
						bfstr.append(mDept).append(";");
						bfstrF.append("DEPTNO").append(";"); 
						bfstr.append(dbStartDay).append(";");
						bfstrF.append("STARTDAY").append(";");
						bfstr.append(dbEndDay).append(";");
						bfstrF.append("ENDDAY").append(";"); 
						bfstr.append(bufCategory.toString());
						bfstrF.append("SQLADD");  //總倉代號 名稱
						
						final String []fields=bfstr.toString().split(";");
						final String []fieldFs=bfstrF.toString().split(";");
						
					      myDialog = ProgressDialog.show(QRep_02.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
						  
					      new Thread()
					      { 
					        public void run()
					        { 
					          try
					          { 
									HttpPost httpRequest = new HttpPost(uriAPI1);
									// Post運作傳送變數必須用NameValuePair[]陣列儲存
									Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI1);

									List<NameValuePair> params = new ArrayList<NameValuePair>();
									for(int x=0;x<fields.length;x++){
										params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
									}
									try {
										// 發出HTTP request(請求) 
										httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
										// 取得HTTP response(回傳) 
										HttpResponse httpResponse = new DefaultHttpClient()
												.execute(httpRequest);
										// 若狀態碼為200 ok 
										if (httpResponse.getStatusLine().getStatusCode() == 200)
										{
											// 取出回應字串
											//Toast.makeText(QRep_12.this, "取得前200", Toast.LENGTH_LONG).show();
											String strResult = EntityUtils.toString(httpResponse	.getEntity());
											//Toast.makeText(QRep_02.this, "取得"+strResult, Toast.LENGTH_LONG).show();
											mHandlerQDR_21.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
										}
										
									} catch (Exception e)
									{
										e.printStackTrace();
									}

					          }
					          catch (Exception e)
					          {
					            e.printStackTrace();
					          }
					          finally
					          {
					            // 卸載所建立的myDialog物件。
					            myDialog.dismiss();
					          }
					        }
					      }.start(); 
				}else{	
				
				//否則往下走
				SQLiteDatabase db = Utilis.getDB(context);
			    
 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
				int chked=0;
				 //Toast.makeText(QRep_02.this,bufCategory.toString()+"__"+cursorGroup.getCount(), Toast.LENGTH_LONG).show(); 				
				if (cursorGroup != null) {
					if (cursorGroup.getCount() > 0) {
						cursorGroup.moveToFirst();
						for (int i = 0; i < cursorGroup.getCount(); i++) {
							RepData data = new RepData();							
							chked=0;
							if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 || nKind==11){
								//先試算有否欠款者,有欠款的才需列出對帳單 sumOwl=0 表示不欠0
								//再來取得每個成員的目前的帳,就可算出前帳
								data.iFormdate=cursorGroup.getString(0); //客戶代號 做為KEY 不顯示
								data.iGoods=cursorGroup.getString(0)+"/"+cursorGroup.getString(1); //客戶代號/名稱
								
								double sumOwl=cursorGroup.getDouble(2)-(cursorGroup.getDouble(4)+cursorGroup.getDouble(5)+cursorGroup.getDouble(6)+cursorGroup.getDouble(7)+cursorGroup.getDouble(11));
								//到本期為止的未收款
								StringBuffer bufDetail = new StringBuffer();
								Cursor csd;
								
								if (nKind!=11){
									bufDetail.append("select A.USER,B.CUSTNAME,") //
									.append("sum(A.BSUM),sum(A.COSTS),sum(A.CASH),sum(A.CARD),sum(A.ORDCASH),sum(A.ORDCARD),sum(A.ATOT),sum(A.DISMONEY),sum(A.ASUM),sum(A.ATM),sum(A.TRCASH)")
							    	.append(" from qhead  A join qcust B on A.USER=B.CUSTNO");
								}else{//廠商對帳
									bufDetail.append("select A.USER,B.FACTNAME,") //
									.append("sum(A.BSUM),sum(A.COSTS),sum(A.CASH),sum(A.CARD),sum(A.ORDCASH),sum(A.ORDCARD),sum(A.ATOT),sum(A.DISMONEY),sum(A.ASUM),sum(A.ATM),sum(A.TRCASH)")
							    	.append(" from qhead  A join qfact B on A.USER=B.FACTNO");
								}
								
								bufDetail.append(" where  (( (A.FORMDATE >= '").append(dbStartDay).append("' and A.FORMDATE <= '").append(dbEndDay).append("') and A.ISCONFIRM='Y' and A.ISCHECK='N' ) or  ")
								.append(" ( (A.FINEDATE<>'' and A.FINEDATE>='").append(dbStartDay).append("' and A.FINEDATE <= '").append(dbEndDay).append("')  and A.ISCONFIRM='Y' and A.ISCHECK='N' )");
								if (ORS!=2){
									bufDetail.append(" or  ( (A.ORDDATE<>'' and A.ORDDATE>='").append(dbStartDay).append("' and A.ORDDATE <= '").append(dbEndDay).append("')  and ((A.ISCONFIRM='Y') or (A.ISCONFIRM='N' and A.ISCHECK='Y' ) ) ))" );
								}else{
									bufDetail.append(")");
								}
								
								if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31)													
									bufDetail.append(" and A.DEPTNO='"+mDept+"'  and A.USER ='"+cursorGroup.getString(0)+"'");
								else
									bufDetail.append("  and A.USER ='"+cursorGroup.getString(0)+"'");
										
								bufDetail.append(" and A.QKIND like '"+mKind.substring(0,1)+"%'")
								.append(" group by A.USER");
								
								csd=db.rawQuery(bufDetail.toString(), null);
								 //Toast.makeText(QRep_02.this,bufDetail.toString()+"__"+csd.getCount(), Toast.LENGTH_LONG).show(); 				
								
								if (csd.getCount()>0){
									csd.moveToFirst();
									chked=1;
	
										double sumOwl2=Math.round(csd.getDouble(2)-(csd.getDouble(4)+csd.getDouble(5)+csd.getDouble(6)+csd.getDouble(7)+csd.getDouble(11)));
										
										if (sumOwl !=0 || sumOwl2!=0 || mWho.equalsIgnoreCase("QCustff") || mWho.equalsIgnoreCase("QFactff")) { 
											data.iSort=1;//做為未來是否傳送資料依據
											
											TR10=TR10+Math.round(sumOwl-sumOwl2); //前欠
											Profits=Math.round(Profits+sumOwl);  //總結欠
											data.iImpo="前帳:"+new BigDecimal(Math.round(sumOwl-sumOwl2)).toString();
											
											T10=Math.round(csd.getDouble(10)); //本期應收(BSUM)(2)
											T11=Math.round(T11+T10); //本期總應收(ASUM)(2);
											TT10=TT10+T10;  //
											M10=csd.getDouble(3);//成本
											TM10=TM10+M10;//成本
											T30=csd.getDouble(4); //現金收入
											TT30=TT30+T30;
											M30=csd.getDouble(5); //票卡收入
											TM30=TM30+M30;
											S30=Math.round(csd.getDouble(6)); //訂現收入
											StkT=StkT+S30;
											R10=csd.getDouble(7); //訂刷收入
											StkM=Math.round(StkM+R10);
											MAtm=Math.round(csd.getDouble(11));//匯款統計 
											TAtm=TAtm+MAtm;
											MTrcash=Math.round(csd.getDouble(12));//代運統計
											TTrcash=TTrcash+MTrcash;
											Profit=Profit+Math.round((T10+MTrcash)-(T30+M30+S30+R10+MAtm));
											data.iCompany="未結:"+new BigDecimal(Math.round(sumOwl)).toString();
											if(nKind!=11){
											 data.iName="應收:"+new BigDecimal(Math.round(T10+MTrcash)).toString();// if (PSWD==0) data.iName=data.iName+"("+(T10-M10)+")";  //毛利
											if (csd.getInt(9)!=0)
												data.iCountry="收現:"+new BigDecimal((T30+S30)).toString()+" 票刷:"+new BigDecimal((M30+R10)).toString()+" 匯:"+new BigDecimal(MAtm).toString()+"(折)"+csd.getInt(9);
											else
												data.iCountry="收現:"+new BigDecimal((T30+S30)).toString()+" 票刷:"+new BigDecimal((M30+R10)).toString()+" 匯:"+new BigDecimal(MAtm).toString();
												
											 data.iMoney="未收:"+new BigDecimal(((T10+MTrcash)-(T30+M30+S30+R10+MAtm))).toString()+" 代運:"+new BigDecimal(MTrcash).toString();
											}else{
												 data.iName="應付:"+new BigDecimal(Math.round(T10+MTrcash)).toString();// if (PSWD==0) data.iName=data.iName+"("+(T10-M10)+")";  //毛利
													if (csd.getInt(9)!=0)
														data.iCountry="付現:"+new BigDecimal((T30+S30)).toString()+" 票刷:"+new BigDecimal((M30+R10)).toString()+" 匯:"+new BigDecimal(MAtm).toString()+"(折)"+new BigDecimal(csd.getInt(9)).toString();
													else
														data.iCountry="付現:"+new BigDecimal((T30+S30)).toString()+" 票刷:"+new BigDecimal((M30+R10)).toString()+" 匯:"+new BigDecimal(MAtm).toString();
														
													 data.iMoney="未付:"+new BigDecimal(((T10+MTrcash)-(T30+M30+S30+R10+MAtm))).toString()+" 代運:"+new BigDecimal(MTrcash).toString();
											}
								 		} else if (sumOwl!=0){ //沒有本期帳單,卻有欠款
								 			chked=1;
											TR10=TR10+Math.round(sumOwl); //前欠
											Profits=Math.round(Profits+sumOwl);  //總結欠
								 			data.iImpo="前帳:"+new BigDecimal(Math.round(sumOwl)).toString();
											data.iCompany="未結:"+new BigDecimal(Math.round(sumOwl)).toString();
											if(nKind!=11) data.iName="應收:0(0)";  //毛利
											else data.iName="應付:0(0)";  //毛利
											if(nKind!=11){
												if (csd.getInt(9)!=0)
													data.iCountry="收現: 0 票刷: 0 匯:0 (折)"+csd.getInt(9);
												else
													data.iCountry="收現: 0 票刷: 0 匯:0";
												data.iMoney="未收:0";
											}else{
												if (csd.getInt(9)!=0)
													data.iCountry="付現: 0 票刷: 0 匯:0 (折)"+csd.getInt(9);
												else
													data.iCountry="付現: 0 票刷: 0 匯:0";
												data.iMoney="未付:0";
												
											}
								 		}
								}
								if (chked!=0)	mAdapter.mList.add(data);	
								csd.close();
							}else if (nKind==PItemKind.TR10){//廠商進貨單
								TT10=Math.round(TT10+cursorGroup.getDouble(6));
								TT30=Math.round(TT30+cursorGroup.getDouble(4));
								StkT=StkT+Math.round(cursorGroup.getDouble(5));
								data.iFormdate=cursorGroup.getString(0); //廠商代號 做為KEY 不顯示
								data.iGoods=cursorGroup.getString(0)+"/"+cursorGroup.getString(1); //廠商代號/名稱
								data.iSort=1;
								data.iImpo="自:"+cursorGroup.getString(2);
								data.iCompany="應付:"+ new BigDecimal(Math.round(cursorGroup.getDouble(6))).toString();
								data.iMoney="至:"+cursorGroup.getString(3);
								data.iCountry="款數:"+cursorGroup.getString(4);
								data.iName="件數:"+cursorGroup.getString(5);
		 						mAdapter.mList.add(data);	
							}else{//門市出貨單 需增查 門市轉貨單為 負值
								StringBuffer bufDetail = new StringBuffer();
								Cursor csd;
								bufDetail.append("SELECT  qitems.DEPTNO, qcust.CUSTNAME," +
										"min(qitems.FORMDATE) as MINDATE,max(qitems.FORMDATE) as MAXDTE," +
										"count(distinct qitems.GOODSNO) as TOTGOODS," +
										"sum( qitems.UNIT20) as TOTCOME,sum(qitems.SUBPRICE) as TOTMONEY " +
										"FROM qitems left join qcust " +
										"on qitems.DEPTNO=qcust.CUSTNO " +
										"where qitems.FORMDATE>='"+dbStartDay+"' " +
										"and qitems.FORMDATE<='"+dbEndDay+"'");
								bufDetail.append(" and qitems.QKIND ='21'");
								bufDetail.append(" and qitems.DEPTNO ='"+cursorGroup.getString(0)+"'");
								bufDetail.append(" group by qitems.DEPTNO order by qitems.DEPTNO ");
								csd=db.rawQuery(bufDetail.toString(), null);
								if (csd.getCount()>0){
									csd.moveToFirst();
									TT10=Math.round(TT10+cursorGroup.getDouble(6)-csd.getDouble(6));
									TT30=Math.round(TT30+cursorGroup.getDouble(4));//款數以出貨為主,轉回不計
									StkT=StkT+Math.round(cursorGroup.getDouble(5)-csd.getDouble(5));
									data.iFormdate=cursorGroup.getString(0); //廠商代號 做為KEY 不顯示
									data.iGoods=cursorGroup.getString(0)+"/"+cursorGroup.getString(1); //廠商代號/名稱
									data.iSort=1;
									data.iImpo="自:"+cursorGroup.getString(2);
									data.iCompany="應付:"+ new BigDecimal(Math.round(cursorGroup.getDouble(6)-csd.getDouble(6))).toString();
									data.iMoney="至:"+cursorGroup.getString(3);
									data.iCountry="款數:"+(cursorGroup.getInt(4));//款數以出貨為主,轉回不計
									data.iName="件數:"+(cursorGroup.getDouble(5)-csd.getDouble(5));
			 						mAdapter.mList.add(data);	
								}else{
									TT10=Math.round(TT10+cursorGroup.getDouble(6));
									TT30=TT30+cursorGroup.getDouble(4);
									StkT=StkT+Math.round(cursorGroup.getDouble(5));
									data.iFormdate=cursorGroup.getString(0); //廠商代號 做為KEY 不顯示
									data.iGoods=cursorGroup.getString(0)+"/"+cursorGroup.getString(1); //廠商代號/名稱
									data.iSort=1;
									data.iImpo="自:"+cursorGroup.getString(2);
									data.iCompany="應付:"+ new BigDecimal(Math.round(cursorGroup.getDouble(6))).toString();
									data.iMoney="至:"+cursorGroup.getString(3);
									data.iCountry="款數:"+cursorGroup.getString(4);
									data.iName="件數:"+cursorGroup.getString(5);
			 						mAdapter.mList.add(data);	
								}
								csd.close();
							}
								cursorGroup.moveToNext();
	 					}	
	 				}
					cursorGroup.close();
					showTitleA();
				}
					
				db.close();
 				db = null;
				}
		}
	
	private void showTitleA(){
		if (nKind!=PItemKind.TR10){
			((TextView)findViewById(R.id.text_tot)).setText("$:"+new BigDecimal(StkT).toString());
			;  //訂金
			((TextView)findViewById(R.id.text_t10)).setText("$:"+new BigDecimal(TT10).toString());//總應收
			((TextView)findViewById(R.id.text_t30)).setText("$:"+new BigDecimal(TT30).toString()+" 墊:"+new BigDecimal(TTrcash).toString());  //現金總收&墊
		}else{
			((TextView)findViewById(R.id.text_t10)).setText("應付:"+new BigDecimal(TT10).toString());//總應收
			((TextView)findViewById(R.id.text_tot)).setText("款:"+new BigDecimal(StkT).toString())
			;  //訂金
			((TextView)findViewById(R.id.text_t30)).setText("件:"+new BigDecimal(TT30).toString());  //現金總收&墊
		}
		((TextView)findViewById(R.id.text_mtot)).setText("票刷:"+new BigDecimal(StkM).toString()); //訂卡
		((TextView)findViewById(R.id.text_r10)).setText("$:"+new BigDecimal(TR10).toString());//總前帳

		if (PSWD==0) 
			((TextView)findViewById(R.id.text_m10)).setText("("+new BigDecimal(TT10-TM10).toString()+")");//總毛利
		else
			((TextView)findViewById(R.id.text_m10)).setText("()");//總毛利

		((TextView)findViewById(R.id.text_m30)).setText("票刷:"+new BigDecimal(TM30).toString()+" 匯:"+new BigDecimal(TAtm).toString()); //卡匯總收
		((TextView)findViewById(R.id.text_r30)).setText("$:"+new BigDecimal(Profit).toString()); //本期未收
		((TextView)findViewById(R.id.text_rp0)).setText("$:"+new BigDecimal(Profits).toString());//總結欠
	}
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_02.this);
			switch (id) {
				case R.id.btn_exit:
				{
				if (Floor==0){	
		        	Intent intentS = new Intent();
		        	USERN=null;
		        	intentS.putExtra("REP_02USER",USERN);
		        	intentS.putExtra("REP_02MODE",KeySet.SearchMode.ACTION);
		    		mStartDay = DateUtil.getCurrentDate(); //2012/10/17 
		    		int mDefaultCtime=05;  //##預設營業打烊時間為 隔日清晨05點
	    			int Ttime=Utilis.toInt(DateUtil.getSystemTime().substring(8, 10));  //取得目前幾點
	   				if (Ttime<=mDefaultCtime)  mStartDay = DateUtil.addDate(mStartDay, -1);
	   				//表示要回到昨天
					mEndDay = mStartDay;
		        	intentS.putExtra("REP_02SDAY",mStartDay);
		        	intentS.putExtra("REP_02EDAY",mEndDay);
		        	QRep_02.this.setResult(RESULT_CANCELED ,intentS);
		        	finish();
				}else if (Floor==1){
					Floor=0;
			        ((Button)findViewById(R.id.btn_btn0)).setVisibility(View.VISIBLE);	//日
			        ((Button)findViewById(R.id.btn_btn1)).setVisibility(View.VISIBLE);	//週        
			        ((Button)findViewById(R.id.btn_btn2)).setVisibility(View.VISIBLE);  //月
			        ((Button)findViewById(R.id.btn_btn3)).setVisibility(View.VISIBLE);//季
			        ((Button)findViewById(R.id.btn_btn4)).setVisibility(View.VISIBLE);
			        ((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);//上一
			        ((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);//下一

					((TextView)findViewById(R.id.text_t10t)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_m10)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_r10t)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_t30t)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_m30)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_r30t)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_tott)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_tot)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_mtot)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_rp0t)).setVisibility(View.VISIBLE);
					((TextView)findViewById(R.id.text_rp0)).setVisibility(View.VISIBLE);

					((ListView)findViewById(R.id.list_item)).setVisibility(View.VISIBLE);
					((ListView)findViewById(R.id.list_item1)).setVisibility(View.GONE);
					mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
					showTitleA();
				}else if (Floor==2){
					((ListView)findViewById(R.id.list_item1)).setVisibility(View.VISIBLE);
					((ListView)findViewById(R.id.list_item2)).setVisibility(View.GONE);
					Floor=1;
				}

					break;
				}
				case R.id.btn_btn0:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.DAY;
					chkMode();
					break;
				}
				case R.id.btn_btn1:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.WEEK;
					chkMode();
					break;
				}
				case R.id.btn_btn2:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.MONTH;
					chkMode();
					break;
				}
				case R.id.btn_btn3:  //只能在銷貨/預購/暫存狀態 進行新增
				{
					mMode=KeySet.SearchMode.SEASON;
					chkMode();
					break;
				}
				case R.id.btn_btn4:  //輸出
				{
					//未來應有雙層作用
					StringBuffer sPrintB = new StringBuffer();
						sepa="\r\n";
						sPrintB=PosUtilis.getPrintKind(QRep_02.this,1);
						Loca=0;
						Loca=Loca+2;sPrintB.append("AZ,10,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
						Loca=Loca+50;sPrintB.append("AZ,50,"+Loca+",2,2,0,0,"+menu_E[(int)(nKind/10)-1]+"總帳對帳單"+sepa);
						Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,期間: 自"+mStartDay+"~"+mEndDay+sepa);
						if (nKind!=PItemKind.TR10){
							if(nKind!=11){
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總前帳:$"+new BigDecimal(TR10).toString()+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總應收:$"+new BigDecimal(TT10+TTrcash).toString()+"("+new BigDecimal(T11).toString()+")'"+sepa);
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總入金:$"+new BigDecimal(TT30).toString()+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總票刷:"+new BigDecimal(TM30).toString()+sepa);
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總匯款:"+new BigDecimal(TAtm).toString()+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總代運:"+new BigDecimal(TTrcash).toString()+sepa);
								Loca=Loca+50;	//sPrintB.append("AZ,30,"+Loca+",1,2,0,0,本未收:$"+Profit+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總未收:$"+new BigDecimal(Profits).toString()+sepa);
							}else{
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總前帳:$"+new BigDecimal(TR10).toString()+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總應付:$"+new BigDecimal(TT10+TTrcash).toString()+"("+new BigDecimal(T11).toString()+")'"+sepa);
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總入金:$"+new BigDecimal(TT30).toString()+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總票刷:"+new BigDecimal(TM30).toString()+sepa);
								Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總匯款:"+new BigDecimal(TAtm).toString()+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總代運:"+new BigDecimal(TTrcash).toString()+sepa);
								Loca=Loca+50;	//sPrintB.append("AZ,30,"+Loca+",1,2,0,0,本未收:$"+Profit+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總未付:$"+new BigDecimal(Profits).toString()+sepa);
							}
						}
						Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);
						SQLiteDatabase db = Utilis.getDB(QRep_02.this);
						for (int ij=0;ij<mAdapter.getCount();ij++){
							RepData datas = (RepData) mAdapter.getItem(ij);
							if (nKind!=PItemKind.TR10){
								if (datas.iSort>0){
									Cursor cs=null;
									if(nKind!=11){
										cs=db.rawQuery("select MOBIL from qcust where CUSTNO='"+datas.iFormdate+"' and TR='"+(nKind/10)+"0'", null);
										if (cs.getCount()>0 ){
											cs.moveToFirst();
											Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,寶號:"+datas.iGoods+"("+cs.getString(0)+")"+sepa);
										}else {
											Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,寶號:"+datas.iGoods+sepa);
										}
									}else{
										Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,寶號:"+datas.iGoods+sepa);
									}
									cs.close();
									Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iImpo+sepa);
																sPrintB.append("AZ,232,"+Loca+",1,1,0,0,"+datas.iName+sepa);
									Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iCountry+sepa);
									Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iMoney+sepa);
																sPrintB.append("AZ,290,"+Loca+",1,1,0,0,"+datas.iCompany+sepa);
								}
							}else{
								Cursor cs=db.rawQuery("select MOBIL from qfact where FACTNO='"+datas.iFormdate+"' and TR='"+(nKind/10)+"0'", null);
								if (cs.getCount()>0 ){
									cs.moveToFirst();
									Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,廠商:"+datas.iGoods+"("+cs.getString(0)+")"+sepa);
								}else {
									Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,廠商:"+datas.iGoods+sepa);
								}
								cs.close();
								Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iImpo+sepa);
															sPrintB.append("AZ,232,"+Loca+",1,1,0,0,"+datas.iMoney+sepa);
								Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iCountry+sepa);
															sPrintB.append("AZ,150,"+Loca+",1,1,0,0,"+datas.iName+sepa);
															sPrintB.append("AZ,290,"+Loca+",1,1,0,0,"+datas.iCompany+sepa);
								
							}
							if (Loca>2400){
								PosUtilis.startPartPrint(QRep_02.this,sPrintB,Loca );
								sPrintB.delete(0, sPrintB.toString().length());
								SystemClock.sleep(3000);
								sPrintB=PosUtilis.getPrintKind(QRep_02.this,1);
								Loca=0;
							}
						}
							db.close();
						Loca=Loca+25;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);
						if (sPrintB.toString().length()>0){
							Loca=Loca+65;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+"[管制單]:這是一份內部結算明細清冊，"+sepa);
							Loca=Loca+30;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,"+"並由相關人員檢視後,進行催帳事宜。"+sepa);
							Loca=Loca+30;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,印製:"+DateUtil.getCurrentTime()+sepa);
							Loca=Loca+150;
							PosUtilis.startPrint(QRep_02.this,sPrintB,Loca);
						}
					
					//無條件全印
					//只印欠款
					break;
				}

				
				case R.id.btn_prev_date:  //當按了上一??
				{
					switch(mMode){
						case KeySet.SearchMode.DAY:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -1);
							mEndDay = mStartDay;
			    			break;
			    		}
						case KeySet.SearchMode.MONTH:  //就是31筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
						case KeySet.SearchMode.WEEK:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -7);
							mEndDay = DateUtil.addDate(mEndDay, -7);
			    			break;
			    		}
					}
					setCondition();
					getGroupData(QRep_02.this,mStartDay, mEndDay, null, null);
					mAdapter.notifyDataSetChanged();
					break;
				}
				case R.id.btn_next_date:
				{
					switch(mMode){
			    		case KeySet.SearchMode.DAY: //就是日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 1);
							mEndDay = mStartDay;
			    			break;
			    		}
			    		case KeySet.SearchMode.MONTH: //就是日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, 1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
			    			break;
			    		}
			    		case KeySet.SearchMode.WEEK:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 7);
							mEndDay = DateUtil.addDate(mEndDay, 7);
			    			break;
			    		}
					}
					setCondition();
					getGroupData(QRep_02.this,mStartDay, mEndDay, null, null);
					mAdapter.notifyDataSetChanged();
					break;

				}
			}
		}
	}
	

	// 搜尋日期 Dialog
    private View makeDateDialog() {
    	View view = LayoutInflater.from(this).inflate(R.layout.search_date, null, false);
    	Calendar c = Calendar.getInstance();
    	c.set(Calendar.DAY_OF_MONTH, 1); // 關鍵
    	
	    mYear1 = c.get(Calendar.YEAR);
		mMonth1 = c.get(Calendar.MONTH) + 1;
		mDay1 = c.get(Calendar.DAY_OF_MONTH);
		c.add(Calendar.MONTH, 1);
		c.add(Calendar.DATE, -1);   // 關鍵
		mYear2 = c.get(Calendar.YEAR);
		mMonth2 = c.get(Calendar.MONTH) + 1;
		mDay2 = c.get(Calendar.DAY_OF_MONTH);
		
		dp1 = (DatePicker)view.findViewById(R.id.dp1);
		dp1.init(mYear1, mMonth1 - 1, mDay1, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear1 = year;
				mMonth1 = monthOfYear + 1;
				mDay1 = dayOfMonth;
			}
		});
		
		dp2 = (DatePicker)view.findViewById(R.id.dp2);
		dp2.init(mYear2, mMonth2 - 1, mDay2, new DatePicker.OnDateChangedListener() {
			@Override
			public void onDateChanged(DatePicker view, int year,
					int monthOfYear, int dayOfMonth) {
				mYear2 = year;
				mMonth2 = monthOfYear + 1;
				mDay2 = dayOfMonth;
			}
		});
		
		return view;
	}
    
    private void chkMode(){        
        switch(mMode){ //剛進入主程式的狀態,初始的模式
        
	    	case KeySet.SearchMode.DAY:
	    	{
	    		mStartDay = DateUtil.getCurrentDate();
	    		mEndDay = mStartDay;
	    		
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一日");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一日");
	    		setTitle(getString(R.string.app_name)+menu_E[(int)(nKind/10)-1]+":[每日結算]");
	        	getGroupData(QRep_02.this, mStartDay, mEndDay, null, null);
	    		mAdapter.notifyDataSetChanged();        
	    		break;
	    	}    		
	    	case KeySet.SearchMode.WEEK:
	    	{
	    		String day = Utilis.getWeekDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
//@@				mGroupMode = GroupMode.TOP2;
	    		
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下一週");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上一週");
	    		setTitle(getString(R.string.app_name)+menu_E[(int)(nKind/10)-1]+":[每週結算]");
	        	getGroupData(QRep_02.this, mStartDay, mEndDay, null, null);
	    		mAdapter.notifyDataSetChanged();        
	    		break;
	    	}
	    	case KeySet.SearchMode.MONTH:
	    	{
	    		String day = Utilis.getMonthDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		
	    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_next_date)).setText("下個月");
	    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.btn_prev_date)).setText("上個月");
	    		setTitle(getString(R.string.app_name)+menu_E[(int)(nKind/10)-1]+":[每月結算]");
	        	getGroupData(QRep_02.this, mStartDay, mEndDay, null, null);
	    		mAdapter.notifyDataSetChanged();        
	    		break;
	    	}
	    	case KeySet.SearchMode.SEASON:  //自定日期範圍
	    	{
	    		new AlertDialog.Builder(QRep_02.this).setTitle(menu_E[(nKind/10)-1]+"對帳單 (起始、結束日期)")
				.setView(makeDateDialog())
				.setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            	String startDay = "" + mYear1 + "/" + Utilis.formatDate(mMonth1) + "/" + Utilis.formatDate(mDay1);
		            	String endDay = "" + mYear2 + "/" + Utilis.formatDate(mMonth2) + "/" + Utilis.formatDate(mDay2);
		            	
		            	mStartDay = startDay;
		            	mEndDay = endDay;
//		            	mTextDuration.setText(getString(R.string.str_duration) + " : " + mStartDay + "~" + mEndDay);
		            	mTextDuration.setText( mStartDay + "~" + mEndDay);
		            	
		            	setTitle(getString(R.string.app_name)+":[日期範圍]");
			    		((Button)findViewById(R.id.btn_next_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_next_date)).setText("自訂");
			    		((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.VISIBLE);
			    		((Button)findViewById(R.id.btn_prev_date)).setText("範圍");
			        	getGroupData(QRep_02.this, mStartDay, mEndDay, null, null);
			    		mAdapter.notifyDataSetChanged();        
		            }
		          }).show();
	    		break;
	    	}
	    	
        }
        setCondition();
    }
    
   private void ListPrintTitle(RepData datas){

	   	sPrintB.delete(0,sPrintB.toString().length());
		sPrintB=PosUtilis.getPrintKind(QRep_02.this,1);
		Loca=0;
		
		Loca=Loca+2;sPrintB.append("AZ,30,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
		Loca=Loca+50;sPrintB.append("AZ,40,"+Loca+",2,2,0,0,<<"+menu_E[(int)(nKind/10)-1]+"對帳單>>"+sepa);
		Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,期間: "+mStartDay+" ~ "+mEndDay+sepa);
		Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,寶號: "+datas.iGoods+sepa);
		Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,======================================"+sepa);
		Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+datas.iImpo+sepa);
									sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+datas.iName+sepa);
		Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+datas.iCountry+sepa);
		Loca=Loca+50;	//sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+datas.iMoney+sepa);
									sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+datas.iCompany+sepa);
		Loca=Loca+25;
	   
   }
   
    private void ListDetailPrintLocal(SQLiteDatabase db,StringBuffer mBuf,RepData datas,Cursor cs){
		mBuf.delete(0, mBuf.toString().length());
		Cursor csi=null;

		if (barStr[8].equalsIgnoreCase("4") || barStr[8].equalsIgnoreCase("5")) 
			mBuf.append("select SOURCENO,GOODSNAME,sum(UNIT"+mKind.substring(0,1)+"0),max(UNITPRICE),sum(SUBPRICE),max(PS),USER");
		else
			mBuf.append("select GOODSNO,GOODSNAME,sum(UNIT"+mKind.substring(0,1)+"0),max(UNITPRICE),sum(SUBPRICE),max(PS),USER");

		mBuf.append(" from qitems where FORMNO='"+cs.getString(0)+"'");
		if (nKind==PItemKind.TR10) mBuf.append(" and SUPPLY='"+USERN+"'");
		if (barStr[8].equalsIgnoreCase("4") || barStr[8].equalsIgnoreCase("5")) 
			mBuf.append(" group by SOURCENO,GOODSNAME");
		else
			mBuf.append(" group by GOODSNO,GOODSNAME");
		
		mBuf.append(" order by CREATEDATETIME");
		csi=db.rawQuery(mBuf.toString(), null);
		if (csi.getCount()>0){
			Loca=Loca+8;
			while (csi.moveToNext()){
				sPrintB.append("AZ,20,"+Loca+",1,1,0,0,"+csi.getString(0)+"-"+csi.getString(1)+sepa);
				Loca=Loca+25;
				if ((nKind==PItemKind.TR20 ||nKind==PItemKind.TR21) && (!csi.getString(6).equalsIgnoreCase(USERN))){//轉出
				sPrintB.append("AZ,30,"+Loca+",1,1,0,0,(轉"+csi.getString(6)+")"+csi.getInt(2)*-1+"X"+sepa);
				sPrintB.append("AZ,130,"+Loca+",1,1,0,0,"+Math.round(csi.getDouble(3))+sepa);
				sPrintB.append("AZ,230,"+Loca+",1,1,0,0,="+new BigDecimal(Math.round(csi.getDouble(4)*-1)).toString()+sepa);
				}else{				
					sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+csi.getString(2)+"件 X"+sepa);
					sPrintB.append("AZ,130,"+Loca+",1,1,0,0,"+Math.round(csi.getDouble(3))+sepa);
					sPrintB.append("AZ,230,"+Loca+",1,1,0,0,="+new BigDecimal(Math.round(csi.getDouble(4))).toString()+sepa);
				}
				sPrintB.append("AZ,330,"+Loca+",1,1,0,0,"+csi.getString(5)+sepa);
				Loca=Loca+25;
			}
		}
		csi.close();
   }
   
   private String ListDetailPrintLocalA4(SQLiteDatabase db,RepData datas,Cursor cs){
	   StringBuffer returnStr=new StringBuffer();
	   StringBuffer mBuf=new StringBuffer();
		Cursor csi=null;

		if (barStr[8].equalsIgnoreCase("4") || barStr[8].equalsIgnoreCase("5")) 
			mBuf.append("select SOURCENO,GOODSNAME,sum(UNIT"+mKind.substring(0,1)+"0),max(UNITPRICE),sum(SUBPRICE),max(PS),USER");
		else
			mBuf.append("select GOODSNO,GOODSNAME,sum(UNIT"+mKind.substring(0,1)+"0),max(UNITPRICE),sum(SUBPRICE),max(PS),USER");
			
		//mBuf.append(" from qitems where FORMNO='"+cs.getString(0)+"' and USER='"+datas.iFormdate+"'");
		mBuf.append(" from qitems where FORMNO='"+cs.getString(0)+"'");
		if (nKind==PItemKind.TR10) mBuf.append(" and SUPPLY='"+USERN+"'");
		if (barStr[8].equalsIgnoreCase("4") || barStr[8].equalsIgnoreCase("5")) 
			mBuf.append(" group by SOURCENO,GOODSNAME");
		else
			mBuf.append(" group by GOODSNO,GOODSNAME");
		
		mBuf.append(" order by CREATEDATETIME");
		csi=db.rawQuery(mBuf.toString(), null);
		if (csi.getCount()>0){
			while (csi.moveToNext()){
				if ((nKind==PItemKind.TR20 ||nKind==PItemKind.TR21) && (!csi.getString(6).equalsIgnoreCase(USERN))){//轉出
					returnStr.append(csi.getString(0)+";");
					returnStr.append(csi.getString(1)+";");
					returnStr.append("(轉"+csi.getString(6)+")"+csi.getInt(2)*-1+";");
					returnStr.append(""+Math.round(csi.getDouble(3))+";");
					returnStr.append(""+new BigDecimal(Math.round(csi.getDouble(4)*-1)).toString()+";");
					returnStr.append(csi.getString(5)+";");
				}else{
					returnStr.append(csi.getString(0)+";");
					returnStr.append(csi.getString(1)+";");
					returnStr.append(""+Math.round(csi.getDouble(2))+";");
					returnStr.append(""+Math.round(csi.getDouble(3))+";");
					returnStr.append(""+new BigDecimal(Math.round(csi.getDouble(4))).toString()+";");
					returnStr.append(csi.getString(5)+";");
				}
				returnStr.append("SSSS"+"\r\n");
			}
		}
		csi.close();
	return returnStr.toString();	
   }
   
   private String makeSQLstr(RepData datas,StringBuffer mBuf){
	    mBuf = new StringBuffer();
		if (mAdapter1.mList != null) {
			mAdapter1.mList.clear();
		}
		if (mAdapter.getCount()>0){
			datas = (RepData) mAdapter.getItem(locations);
			USERN=datas.iFormdate; //指定對象
			
			if(mStartDay != null && mStartDay.length() > 0)	mStartDay = mStartDay.replace("/", "-");
			if(mEndDay != null && mEndDay.length() > 0) mEndDay = mEndDay.replace("/", "-");
			
			if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 || nKind==11){
				mBuf.append("select FORMNO,FORMDATE,HANDNO,BSUM,CASH,CARD,ORDCASH,ORDCARD,ASUM,DISMONEY,ATM,TRCASH");
				mBuf.append(" from qhead where ");
			    mBuf.append("((( FORMDATE >= '").append(mStartDay).append("' and FORMDATE <= '").append(mEndDay).append("') and ISCONFIRM='Y' and ISCHECK='N' )")
			    .append(" or ( (FINEDATE<>'' and FINEDATE>='").append(mStartDay).append("' and FINEDATE <= '").append(mEndDay).append("') and ISCONFIRM='Y' and ISCHECK='N' )")
		    	;
			  //@@@20211212含現金票刷匯款純入金  
			    if (ORS!=2){ //含預購帳 
			    	mBuf.append(" or ( (ORDDATE<>'' and ORDDATE>='").append(mStartDay).append("' and ORDDATE <= '").append(mEndDay).append("')  and ((ISCONFIRM='Y') or (ISCONFIRM='N' and ISCHECK='Y' ) )))");
			    }else{
			    	mBuf.append(")");
			    }
			    
				if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31)													
					mBuf.append(" and DEPTNO='"+mDept+"'  and QKIND like '"+mKind.substring(0,1)+"%'");
				else
					mBuf.append("  and QKIND like '"+mKind.substring(0,1)+"%'");
					
				mBuf.append(" and USER ='"+USERN+"'");
				mBuf.append(" order by FORMDATE,FORMNO");

			}else if (nKind==PItemKind.TR10){//廠商進貨單
				
				mBuf.append("select FORMNO,FORMDATE,sum(SUBPRICE),sum(UNIT10),count(GOODSNO)");
				mBuf.append(" from qitems where ");
			    mBuf.append("( FORMDATE >= '").append(mStartDay).append("' and FORMDATE <= '").append(mEndDay).append("')");
				mBuf.append(" and ISCONFIRM='Y' ");
				mBuf.append(" and QKIND like '"+mKind.substring(0,1)+"%'");
				mBuf.append(" and SUPPLY ='"+USERN+"'");
				mBuf.append(" group by FORMDATE,FORMNO");
				
			}else{//門市對帳單
				mBuf.append("select FORMNO,FORMDATE,HANDNO,BSUM,CASH,CARD,ORDCASH,ORDCARD,ASUM,DISMONEY,ATM,TRCASH,USER,DEPTNO");
				mBuf.append(" from qhead where ");
			    mBuf.append("(( (FORMDATE >= '").append(mStartDay).append("' and FORMDATE <= '").append(mEndDay).append("') and ISCONFIRM='Y' and ISCHECK='N'  )");
			    mBuf.append(" or ( (FINEDATE<>'' and FINEDATE>='").append(mStartDay).append("' and FINEDATE <= '").append(mEndDay).append("') and ISCONFIRM='Y' and ISCHECK='N' )");
			   if (ORS!=2){
				   mBuf.append(" or ( (ORDDATE<>'' and ORDDATE>='").append(mStartDay).append("' and ORDDATE <= '").append(mEndDay).append("')  and ((ISCONFIRM='Y') or (ISCONFIRM='N' and ISCHECK='Y' ) )))");
			   }else{
				   mBuf.append(")");
			   }
				//含門市出貨單 及 門市轉貨單
				mBuf.append(" and QKIND like '"+mKind.substring(0,1)+"%'");
				mBuf.append(" and (USER ='"+USERN+"' or DEPTNO ='"+USERN+"')");
				mBuf.append(" order by FORMDATE,FORMNO");
			}
		}
	   return mBuf.toString();
   }
   
   private String makeSQLstr2(){
		StringBuffer mBuf=new StringBuffer();
		Cursor csi=null;

		if (barStr[8].equalsIgnoreCase("4") || barStr[8].equalsIgnoreCase("5")) 
			mBuf.append("select SOURCENO,GOODSNAME,sum(UNIT"+mKind.substring(0,1)+"0),max(UNITPRICE),sum(SUBPRICE),max(PS)");
		else
			mBuf.append("select GOODSNO,GOODSNAME,sum(UNIT"+mKind.substring(0,1)+"0),max(UNITPRICE),sum(SUBPRICE),max(PS)");
			
		mBuf.append(" from qitems where FORMNO='%AFORMNO'");
		if (barStr[8].equalsIgnoreCase("4") || barStr[8].equalsIgnoreCase("5")) 
			mBuf.append(" group by SOURCENO,GOODSNAME");
		else
			mBuf.append(" group by GOODSNO,GOODSNAME");
		
		mBuf.append(" order by CREATEDATETIME");
		
	  return mBuf.toString(); 
   }
   
   
   private void ListPrint(){
		RepData datas = (RepData) mAdapter.getItem(locations);											
		mBuf = new StringBuffer();
		mBuf.append(makeSQLstr(datas,mBuf));
		StringBuffer mBuf2 = new StringBuffer();
		mBuf2.append(makeSQLstr2());
		
		if  (Utilis.haveInternet(QRep_02.this) && Utilis.toInt(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 3))==1 && mCloud>0){
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			ListPrintTitle(datas);//熱感列印台頭

				bfstr.append(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(mKind).append(";");
				bfstrF.append("QKIND").append(";");
				bfstr.append(USERN).append(";");
				bfstrF.append("USER").append(";");
				bfstr.append(mDept).append(";");
				bfstrF.append("DEPTNO").append(";"); 
				bfstr.append(mStartDay).append(";");
				bfstrF.append("STARTDAY").append(";");
				bfstr.append(mEndDay).append(";");
				bfstrF.append("ENDDAY").append(";"); 
				bfstr.append(mBuf2).append(";");
				bfstrF.append("SQLSECOND").append(";"); 
				bfstr.append(mBuf.toString());
				bfstrF.append("SQLADD");  //總倉代號 名稱
				
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(QRep_02.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							HttpPost httpRequest = new HttpPost(uriAPIP);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPIP);

							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								// 若狀態碼為200 ok 
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									//Toast.makeText(QRep_12.this, "取得前200", Toast.LENGTH_LONG).show();
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									//Toast.makeText(QRep_12.this, "取得"+strResult, Toast.LENGTH_LONG).show();
									mHandlerQDR_2P.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
									
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); 
			}else{	//單機
					SQLiteDatabase db = Utilis.getDB(QRep_02.this);
					Cursor cs=db.rawQuery(mBuf.toString(), null);
				if (cs.getCount()>0){
					ListPrintTitle(datas);//熱感列印台頭
					if (nKind!=PItemKind.TR10){
						
							cs.moveToFirst();
							for (int ij=0;ij<cs.getCount();ij++){
								Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);																			
								Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,日期:"+cs.getString(1)+sepa);
									sPrintB.append("AZ,212,"+Loca+",1,1,0,0,"+"單號:"+cs.getString(0)+sepa);
								if (nKind!=PItemKind.TR21 && nKind!=PItemKind.TR20){
									Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,金額:"+new BigDecimal(Math.round(cs.getDouble(8))).toString()+sepa);
								}else{
//2021_0FORMNO,1FORMDATE,2HANDNO,3BSUM,4CASH,5CARD,6ORDCASH,7ORDCARD,8ASUM,9DISMONEY,10ATM,11TRCASH,12USER,13DEPTNO
									if (cs.getString(12).equalsIgnoreCase(USERN)){
										Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,金額:"+new BigDecimal(Math.round(cs.getDouble(8))).toString()+sepa);
									}else{	//轉出
											Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,(轉:"+cs.getString(12)+")"+cs.getInt(8)*-1+sepa);
									}
								}
									if(cs.getInt(9)!=0){							
										if (nKind!=PItemKind.TR21 && nKind!=PItemKind.TR20){
											sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"數量:"+cs.getInt(2)+"(折)"+cs.getInt(9)+sepa);
										}else{											
											if (cs.getString(12).equalsIgnoreCase(USERN))
												sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"數量:"+cs.getInt(2)+"(折)"+cs.getInt(9)+sepa);
											else
												sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"轉量:"+cs.getInt(2)*-1+"(折)"+cs.getInt(9)+sepa);
										}
									}else
										if (nKind!=PItemKind.TR21 && nKind!=PItemKind.TR20){
											sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"數量:"+cs.getInt(2)+sepa);
										}else{											
										if (cs.getString(12).equalsIgnoreCase(USERN))
											sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"數量:"+cs.getInt(2)+sepa);
										else
											sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"轉量:"+cs.getInt(2)*-1+sepa);
									}									
								int addLine=0;
								if ((cs.getDouble(4)+cs.getDouble(5)+cs.getDouble(6)+cs.getDouble(7))!=0){																			
									Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,入金:"+new BigDecimal(cs.getDouble(4)+cs.getDouble(6)).toString()+sepa);
									sPrintB.append("AZ,232,"+Loca+",1,1,0,0,"+"票刷:"+new BigDecimal(cs.getDouble(5)+cs.getDouble(7)).toString()+sepa);
									addLine=1;
								}
								if (cs.getInt(10)!=0 || cs.getInt(11)!=0){
									if (addLine==1) {Loca=Loca+25;
										sPrintB.append("AZ,30,"+Loca+",1,1,0,0,匯款:"+new BigDecimal(cs.getDouble(10)).toString()+sepa);
										sPrintB.append("AZ,232,"+Loca+",1,1,0,0,"+"代運:"+new BigDecimal(cs.getDouble(11)).toString()+sepa);
									}else{ Loca=Loca+50;
										sPrintB.append("AZ,170,"+Loca+",1,1,0,0,匯款:"+new BigDecimal(cs.getDouble(10)).toString()+sepa);
										sPrintB.append("AZ,310,"+Loca+",1,1,0,0,"+"代運:"+new BigDecimal(cs.getDouble(11)).toString()+sepa);
									}
								}else{//沒有入帳
									if (addLine==0) Loca=Loca+25;
								}
								//判斷是否繼續開出明細對帳單(主貨號)(來原編號)
								if (isPrintDetail==1){
									Loca=Loca+22;
									ListDetailPrintLocal(db,mBuf,datas,cs);
								}
								if (Loca>2400){
									PosUtilis.startPartPrint(QRep_02.this,sPrintB,Loca );
									sPrintB.delete(0, sPrintB.toString().length());
									SystemClock.sleep(3000);
									sPrintB=PosUtilis.getPrintKind(QRep_02.this,1);
									Loca=0;
								}
							cs.moveToNext();
							}
						
					}else{
							//FORMNO,FORMDATE,sum(SUBPRICE),sum(UNIT10),count(GOODSNO)											
							cs.moveToFirst();
							for (int ij=0;ij<cs.getCount();ij++){
								Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);																			
								Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,日期:"+cs.getString(1)+sepa);
															sPrintB.append("AZ,212,"+Loca+",1,1,0,0,"+"單號:"+cs.getString(0)+sepa);
								Loca=Loca+28;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+"款數:"+cs.getString(4)+sepa);
															sPrintB.append("AZ,150,"+Loca+",1,2,0,0,"+"件數:"+cs.getString(3)+sepa);
															sPrintB.append("AZ,290,"+Loca+",1,2,0,0,應付:"+new BigDecimal(Math.round(cs.getDouble(2))).toString()+sepa);
								
								if (isPrintDetail==1)	{
									Loca=Loca+50;
									ListDetailPrintLocal(db,mBuf,datas,cs);
								}else{
									Loca=Loca+22;
								}
								if (Loca>2400){
									PosUtilis.startPartPrint(QRep_02.this,sPrintB,Loca );
									sPrintB.delete(0, sPrintB.toString().length());
									SystemClock.sleep(3000);
									sPrintB=PosUtilis.getPrintKind(QRep_02.this,1);
									Loca=0;
								}
							cs.moveToNext();
							}
					}
					if (Loca>0){
						sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);											
						Loca=Loca+40;sPrintB.append("AZ,10,"+Loca+",1,1,0,0, TEL:"+compStr[3]+"/FAX:"+compStr[4]+sepa);
						Loca=Loca+30;sPrintB.append("AZ,10,"+Loca+",1,1,0,0, 地址:"+compStr[2]+sepa);
						Loca=Loca+30;sPrintB.append("AZ,10,"+Loca+",1,1,0,0, 印製:"+DateUtil.getCurrentTime()+sepa);			
						Loca=Loca+100;sPrintB.append("AZ,20,"+Loca+",1,2,0,0, 簽收人:____________________"+sepa);
						Loca=Loca+150;
						PosUtilis.startPrint(QRep_02.this,sPrintB,Loca);
					}
				}
				db.close();
				cs.close();
			}
   }
    
   private void ListPrintA4(){
		RepData datas = (RepData) mAdapter.getItem(locations);											
		StringBuffer mSQLstr = new StringBuffer();
		mSQLstr.append(makeSQLstr(datas,mBuf));
		
		if  (Utilis.haveInternet(QRep_02.this) && Utilis.toInt(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 3))==1 && mCloud>0){
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			//ListPrintTitleA4(datas);//熱感列印台頭

				bfstr.append(Utilis.getIni(QRep_02.this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(mKind).append(";");
				bfstrF.append("QKIND").append(";");
				bfstr.append(datas.iFormdate).append(";");
				bfstrF.append("USER").append(";");
				bfstr.append(barStr[8]).append(";");
				bfstrF.append("ISSOURCENO").append(";"); 
				bfstr.append(mStartDay).append(";");
				bfstrF.append("STARTDAY").append(";");
				bfstr.append(mEndDay).append(";");
				bfstrF.append("ENDDAY").append(";"); 
				bfstr.append(mSQLstr.toString());
				bfstrF.append("SQLADD");  //總倉代號 名稱
				
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(QRep_02.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							HttpPost httpRequest = new HttpPost(uriAPIPA4);
							// Post運作傳送變數必須用NameValuePair[]陣列儲存
							Log.i("CALL_PHP_2A4", "呼叫執行緒PHP___到此一遊"+uriAPIPA4);

							List<NameValuePair> params = new ArrayList<NameValuePair>();
							for(int x=0;x<fields.length;x++){
								params.add(new BasicNameValuePair(fieldFs[x], fields[x]));
							}
							try {
								// 發出HTTP request(請求) 
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								// 取得HTTP response(回傳) 
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								// 若狀態碼為200 ok 
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									//Toast.makeText(QRep_12.this, "取得前200", Toast.LENGTH_LONG).show();
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									//Toast.makeText(QRep_12.this, "取得"+strResult, Toast.LENGTH_LONG).show();
									mHandlerQDR_2PA4.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
									
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); 
			}else{	//單機
					SQLiteDatabase db = Utilis.getDB(QRep_02.this);
					Cursor cs=db.rawQuery(mSQLstr.toString(), null);
					StringBuffer mBufA4=new StringBuffer();  
				if (cs.getCount()>0){
					if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 || nKind ==11){
						cs.moveToFirst();
						for (int ij=0;ij<cs.getCount();ij++){
							for (int jj=0;jj<=11;jj++){
								mBufA4.append(cs.getString(jj)+";");
							}
							mBufA4.append("SSSS"+"\r\n");
							//判斷是否繼續開出明細對帳單(主貨號)(來原編號)
							if (isPrintDetail==4){
								mBufA4.append(ListDetailPrintLocalA4(db,datas,cs));
							}
							mBufA4.append(";HHHH"+"\r\n");
						cs.moveToNext();
						}
						
					}else if (nKind==PItemKind.TR10){
							cs.moveToFirst();
							for (int ij=0;ij<cs.getCount();ij++){
									for (int jj=0;jj<=4;jj++){
										mBufA4.append(cs.getString(jj)+";");
									}
									mBufA4.append("SSSS"+"\r\n");
									//判斷是否繼續開出明細對帳單(主貨號)(來原編號)
									if (isPrintDetail==4){
										mBufA4.append(ListDetailPrintLocalA4(db,datas,cs));
									}
									mBufA4.append(";HHHH"+"\r\n");
							cs.moveToNext();
							}
					}else{ //20.21
						cs.moveToFirst();
						for (int ij=0;ij<cs.getCount();ij++){

//0FORMNO,1FORMDATE,2HANDNO,3BSUM,4CASH,5CARD,6ORDCASH,7ORDCARD,8ASUM,9DISMONEY,10ATM,11TRCASH,12USER,13DEPTNO

							for (int jj=0;jj<=12;jj++){
								mBufA4.append(cs.getString(jj)+";");
							}
							mBufA4.append("SSSS"+"\r\n");
							//判斷是否繼續開出明細對帳單(主貨號)(來原編號)
							if (isPrintDetail==4){
								mBufA4.append(ListDetailPrintLocalA4(db,datas,cs));
							}
							mBufA4.append(";HHHH"+"\r\n");
						cs.moveToNext();
						}
						
					}
				}
				db.close();
				cs.close();

				Intent intent = new Intent();
				//bundle.putString("Mkqrs",""+datas.iFormdate+","+mKind+","+isPrintDetail+","+mDept+","+mBufA4.toString()+","
				//+datas.iGoods+";"+datas.iImpo+";"+datas.iName+";"+datas.iCountry+";"+datas.iMoney+";"+datas.iCompany+","+mStartDay+","+mEndDay);
				intent.putExtra("SERCH",datas.iFormdate);
				intent.putExtra("QKIND",""+nKind);
				intent.putExtra("MODE",isPrintDetail);
				intent.putExtra("DEPTNO",mDept);
				intent.putExtra("BUFSTR",mBufA4.toString());
				intent.putExtra("BUFTITLE",datas.iGoods+";"+datas.iImpo+";"+datas.iName+";"+datas.iCountry+";"+datas.iMoney+";"+datas.iCompany);
				intent.putExtra("STARTDAY",mStartDay);
				intent.putExtra("ENDDAY",mEndDay);

				intent.setClass(QRep_02.this, MkqrSt.class);
				startActivity(intent);
				
			}
   }
    
	Handler mHandlerQDR_2PA4 = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			RepData datas = (RepData) mAdapter.getItem(locations);											
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
					Log.i("DOWNLOAD_2PA4", Hresult.substring(Hresult.indexOf("rep02;")+6));
						
					if (Hresult.indexOf("HHHH\r\n")>2){
						Hresult=	Hresult.substring(Hresult.indexOf("rep02;")+6);

						Intent intent = new Intent();
						//bundle.putString("Mkqrs",""+datas.iFormdate+","+mKind+","+isPrintDetail+","+mDept+","+Hresult+","
						//+datas.iGoods+";"+datas.iImpo+";"+datas.iName+";"+datas.iCountry+";"+datas.iMoney+";"+datas.iCompany+","+mStartDay+","+mEndDay);

						intent.putExtra("SERCH",datas.iFormdate);
						intent.putExtra("QKIND",""+nKind);
						intent.putExtra("MODE",isPrintDetail);
						intent.putExtra("DEPTNO",mDept);
						intent.putExtra("BUFSTR",Hresult);
						intent.putExtra("BUFTITLE",datas.iGoods+";"+datas.iImpo+";"+datas.iName+";"+datas.iCountry+";"+datas.iMoney+";"+datas.iCompany);
						intent.putExtra("STARTDAY",mStartDay);
						intent.putExtra("ENDDAY",mEndDay);
						
						intent.setClass(QRep_02.this, MkqrSt.class);
						startActivity(intent);
 						
					}							
				}						
			}
		}
};
	
    

	Handler mHandlerQDR_2P = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;
				if (Hresult != null ){
						
					if (Hresult.indexOf("SSSS\r\n")>2){
						Log.i("DOWNLOAD_2P", Hresult.substring(Hresult.indexOf("rep02;")+6));

						Hresult=	Hresult.substring(Hresult.indexOf("rep02;")+6);
						String Linea [] = Hresult.split("SSSS\r\n");
							
						for (int xx=0;xx<Linea.length;xx++){
							String Lines[] =Linea [xx].split(";");

								if (nKind!=PItemKind.TR10){
									Loca=Loca+5;sPrintB.append("AZ,10"+Loca+",1,2,0,0,--------------------------------------"+sepa);																			
									Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,日期:"+Lines[1]+sepa);
																sPrintB.append("AZ,212,"+Loca+",1,1,0,0,"+"單號:"+Lines[0]+sepa);
									if (nKind!=11){
										Loca=Loca+28;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,應收:"+new BigDecimal(Utilis.toDouble(Lines[9])+Utilis.toDouble(Lines[10])).toString()+sepa);
									}else{
										Loca=Loca+28;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,應收:"+new BigDecimal(Utilis.toDouble(Lines[9])+Utilis.toDouble(Lines[10])).toString()+sepa);
									}	
									if(Utilis.toInt(Lines[10])!=0)							
										sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"數量:"+Lines[2]+"(折)"+Utilis.toInt(Lines[10])+sepa);
									else
										sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"數量:"+Lines[2]+sepa);
									int addLine=0;
									if ((Utilis.toDouble(Lines[4])+Utilis.toDouble(Lines[5])+Utilis.toDouble(Lines[7])+Utilis.toDouble(Lines[8]))!=0){																			
										Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,入金:"+new BigDecimal(Utilis.toDouble(Lines[4])+Utilis.toDouble(Lines[7])).toString()+sepa);
										sPrintB.append("AZ,232,"+Loca+",1,1,0,0,"+"票刷:"+new BigDecimal(Utilis.toDouble(Lines[5])+Utilis.toDouble(Lines[8]))+sepa);
										addLine=1;
									}
									if (Utilis.toDouble(Lines[6])!=0 || Utilis.toDouble(Lines[11])!=0){
										if (addLine==1){ Loca=Loca+25;
										sPrintB.append("AZ,30,"+Loca+",1,1,0,0,匯款:"+new BigDecimal(Utilis.toDouble(Lines[11])).toString()+sepa);
										sPrintB.append("AZ,232,"+Loca+",1,1,0,0,"+"代運:"+Utilis.toInt(Lines[6])+sepa);
										}else{Loca=Loca+50;
											sPrintB.append("AZ,170,"+Loca+",1,1,0,0,匯款:"+new BigDecimal(Utilis.toDouble(Lines[11])).toString()+sepa);
											sPrintB.append("AZ,310,"+Loca+",1,1,0,0,"+"代運:"+Utilis.toInt(Lines[6])+sepa);
										}
									}else{//沒有入帳
										if (addLine==0) Loca=Loca+25;
									}
							
								}else{
									Loca=Loca+5;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);																			
									Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,日期:"+Lines[1]+sepa);
																sPrintB.append("AZ,212,"+Loca+",1,1,0,0,"+"單號:"+Lines[0]+sepa);
									Loca=Loca+28;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,"+"款數:"+Lines[4]+sepa);
																sPrintB.append("AZ,150,"+Loca+",1,2,0,0,"+"件數:"+Lines[3]+sepa);
																sPrintB.append("AZ,290,"+Loca+",1,2,0,0,應付:"+new BigDecimal(Math.round(Utilis.toDouble(Lines[2]))).toString()+sepa);
									Loca=Loca+22;
								}
								//雲端明細對帳單尚未寫出
								//if (isPrintDetail==1){
								//	Loca=Loca+22;
								//ListDetailPrintLocal(db,mBuf,datas,cs);
								//}
								if (Loca>2400){
									PosUtilis.startPartPrint(QRep_02.this,sPrintB,Loca );
									sPrintB.delete(0, sPrintB.toString().length());
									SystemClock.sleep(3000);
									sPrintB=PosUtilis.getPrintKind(QRep_02.this,1);
									Loca=0;
								}
						}
						if (Loca>0){
							sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);											
							Loca=Loca+40;sPrintB.append("AZ,10,"+Loca+",1,1,0,0, TEL:"+compStr[3]+"/FAX:"+compStr[4]+sepa);
							Loca=Loca+30;sPrintB.append("AZ,10,"+Loca+",1,1,0,0, 地址:"+compStr[2]+sepa);
							Loca=Loca+30;sPrintB.append("AZ,10,"+Loca+",1,1,0,0, 印製:"+DateUtil.getCurrentTime()+sepa);			
							Loca=Loca+100;sPrintB.append("AZ,20,"+Loca+",1,2,0,0, 簽收人:____________________"+sepa);
							Loca=Loca+150;
							PosUtilis.startPrint(QRep_02.this,sPrintB,Loca);
						}
					}							
				}						
			}
		}
};
	

    
	Handler mHandlerQDR_21 = new Handler()
	{
		@Override
		public  void handleMessage(Message msg)
		{
			//傳回的//upup_1-30_系統時間
			
			String Hresult=null;
			switch (msg.what)
			{
			// 顯示網路上抓取的資料
			case REFRESH_DATA:
				if (msg.obj instanceof String) 
					Hresult = (String) msg.obj;

				if (Hresult != null ){
					if (Hresult.indexOf("SSSS\r\n")>2){
						Log.i("DOWNLOAD_21", Hresult.substring(Hresult.indexOf("rep02;")+6));

						Hresult=	Hresult.substring(Hresult.indexOf("rep02;")+6);
						String Linea [] = Hresult.split("SSSS\r\n");
							
						for (int xx=0;xx<Linea.length;xx++){
							String Lines[] =Linea [xx].split(";");

							int chked=0;
							RepData data = new RepData();
							if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 || nKind==11){
								//先試算有否欠款者,有欠款的才需列出對帳單 sumOwl=0 表示不欠0
								//再來取得每個成員的目前的帳,就可算出前帳
								data.iFormdate=Lines[0]; //客戶代號 做為KEY 不顯示
								data.iGoods=Lines[0]+"/"+Lines[1]; //客戶代號/名稱
								double sumOwl=Math.round(Utilis.toDouble(Lines[13]));
								//double sumOwl2=Math.round(Utilis.toDouble(Lines[2])-(Utilis.toDouble(Lines[4])+Utilis.toDouble(Lines[5]))+Utilis.toDouble(Lines[6])+Utilis.toDouble(Lines[7])+Utilis.toDouble(Lines[11]));
								double sumOwl2=Math.round(Utilis.toDouble(Lines[14]));
								
								if (sumOwl !=0 || sumOwl2!=0 || mWho.equalsIgnoreCase("QCustff") || mWho.equalsIgnoreCase("QFactff")) { 
									data.iSort=1;//做為未來是否傳送資料依據
									chked=1;
									TR10=TR10+Math.round(sumOwl-sumOwl2); //前欠
									Profits=Math.round(Profits+sumOwl);  //總結欠
									data.iImpo="前帳:"+new BigDecimal(Math.round(sumOwl-sumOwl2)).toString();
									
									T10=Math.round(Utilis.toDouble(Lines[2])); //本期應收(BSUM)(2)
									T11=Math.round(T11+Utilis.toDouble(Lines[2])); //本期總應收(ASUM)(2);
									TT10=TT10+T10;  //
									M10=Utilis.toDouble(Lines[3]);//成本
									TM10=TM10+M10;//成本
									T30=Utilis.toDouble(Lines[4]); //現金收入
									TT30=TT30+T30;
									M30=Utilis.toDouble(Lines[5]); //票卡收入
									TM30=TM30+M30;
									S30=Math.round(Utilis.toDouble(Lines[6])); //訂現收入
									StkT=StkT+S30;
									R10=Utilis.toDouble(Lines[7]); //訂刷收入
									StkM=StkM+R10;
									MAtm=Math.round(Utilis.toDouble(Lines[11]));//匯款統計 
									TAtm=TAtm+MAtm;
									MTrcash=Math.round(Utilis.toDouble(Lines[12]));//代運統計
									TTrcash=TTrcash+MTrcash;
									Profit=Math.round(Profit+((T10)-(T30+M30+S30+R10+MAtm)));
									data.iCompany="未結:"+new BigDecimal(sumOwl).toString();
									
									 if (nKind!=11) data.iName="應收:"+new BigDecimal(T10).toString();// if (PSWD==0) data.iName=data.iName+"("+(T10-M10)+")";  //毛利
									 else data.iName="應付:"+new BigDecimal(T10).toString();
									 
									if (Utilis.toInt(Lines[9])!=0){
										if(nKind!=11)
											data.iCountry="收現:"+new BigDecimal(T30+S30).toString()+" 票:"+Math.round(M30+R10)+" 匯:"+new BigDecimal(MAtm).toString()+"(折)"+Utilis.toInt(Lines[9]);
										else
											data.iCountry="付現:"+new BigDecimal(T30+S30).toString()+" 票:"+new BigDecimal(Math.round(M30+R10)).toString()+" 匯:"+new BigDecimal(MAtm).toString()+"(折)"+Utilis.toInt(Lines[9]);
									}else{
										if(nKind!=11)
											data.iCountry="收現:"+new BigDecimal(T30+S30).toString()+" 票:"+new BigDecimal(M30+R10).toString()+" 匯:"+new BigDecimal(MAtm).toString();
										else
											data.iCountry="付現:"+new BigDecimal(T30+S30).toString()+" 票:"+(M30+R10)+" 匯:"+new BigDecimal(MAtm).toString();
									}
									if (nKind!=11)
										 data.iMoney="未收:"+new BigDecimal(T10-(T30+M30+S30+R10+MAtm)).toString()+" 代運:"+MTrcash;
									else
										 data.iMoney="未付:"+new BigDecimal(T10-(T30+M30+S30+R10+MAtm)).toString()+" 代運:"+MTrcash;

						 		} else if (sumOwl!=0){ //沒有本期帳單,卻有欠款
						 			chked=1;
									TR10=TR10+Math.round(sumOwl); //前欠
									Profits=Math.round(Profits+sumOwl);  //總結欠
						 			data.iImpo="前帳:"+new BigDecimal(Math.round(sumOwl)).toString();
									data.iCompany="未結:"+new BigDecimal(Math.round(sumOwl)).toString();
									if(nKind!=11){
										data.iName="應收:0(0)";  //毛利
										if (Utilis.toInt(Lines[9])!=0)
											data.iCountry="收現: 0 票刷: 0 匯:0 (折)"+Utilis.toInt(Lines[9]);
										else
											data.iCountry="收現: 0 票刷: 0 匯:0";
										data.iMoney="未收:0";
									}else{
										data.iName="應付:0(0)";  //毛利
										if (Utilis.toInt(Lines[9])!=0)
											data.iCountry="付現: 0 票刷: 0 匯:0 (折)"+Utilis.toInt(Lines[9]);
										else
											data.iCountry="付現: 0 票刷: 0 匯:0";
										data.iMoney="未付:0";
									}
						 		}

						}else{//廠商進貨單 門市出貨單
							TT10=(int) (TT10+Math.round(Utilis.toDouble(Lines[6])));
							TT30=TT30+Utilis.toDouble(Lines[4]);
							StkT=StkT+Math.round(Utilis.toDouble(Lines[5]));
							data.iFormdate=Lines[0]; //廠商代號 做為KEY 不顯示
							data.iGoods=Lines[0]+"/"+Lines[1]; //廠商代號/名稱
							data.iSort=1;
							data.iImpo="自:"+Lines[2];
							data.iCompany="應付:"+ new BigDecimal(Math.round(Utilis.toDouble(Lines[6]))).toString();
							data.iMoney="至:"+Lines[3];
							data.iCountry="款數:"+Lines[4];
							data.iName="件數:"+Lines[5];
				 			chked=1;
						}
						if (chked!=0)	mAdapter.mList.add(data);	
					}							
				}						
						Floor=0;
						showTitleA();
			}
		}
	}
};
	
Handler mHandlerQDR_22 = new Handler()
{
	@Override
	public  void handleMessage(Message msg)
	{
		//傳回的//upup_1-30_系統時間
		
		String Hresult=null;
		switch (msg.what)
		{
		// 顯示網路上抓取的資料
		case REFRESH_DATA:
			if (msg.obj instanceof String) 
				Hresult = (String) msg.obj;
			if (Hresult != null ){
					
				if (Hresult.indexOf("SSSS\r\n")>2){
					Log.i("DOWNLOAD_22", Hresult.substring(Hresult.indexOf("rep02;")+6));

					
					RepData datas = (RepData) mAdapter.getItem(locations);
					Hresult=	Hresult.substring(Hresult.indexOf("rep02;")+6);
					String Linea [] = Hresult.split("SSSS\r\n");
						
					for (int xx=0;xx<Linea.length;xx++){
						String Lines[] =Linea [xx].split(";");
						
						RepData data = new RepData();
						if (nKind==PItemKind.TR30 || nKind==PItemKind.TR31 || nKind==PItemKind.TR40 || nKind==PItemKind.TR41 || nKind==11){
							//先試算有否欠款者,有欠款的才需列出對帳單 sumOwl=0 表示不欠0
							//再來取得每個成員的目前的帳,就可算出前帳
							
							data.iGoods=Lines[1];
							data.iName=Lines[0];
							data.iCountry=Lines[2];
							if(nKind!=11){
								if (Utilis.toDouble(Lines[9])!=0)
									data.iImpo="應收:"+new BigDecimal(Utilis.toDouble(Lines[3])).toString()+"(折"+Utilis.toInt(Lines[9])+")";
								else
									data.iImpo="應收:"+new BigDecimal(Utilis.toDouble(Lines[3])).toString();
							}else{
								if (Utilis.toDouble(Lines[9])!=0)
									data.iImpo="應付:"+new BigDecimal(Utilis.toDouble(Lines[3])).toString()+"(折"+Utilis.toInt(Lines[9])+")";
								else
									data.iImpo="應付:"+new BigDecimal(Utilis.toDouble(Lines[3])).toString();
							}
							data.iMoney="現金:";data.iCompany="訂金";
							if (Utilis.toDouble(Lines[4])!=0) data.iMoney=data.iMoney+new BigDecimal(Lines[4]).toString();
							if (Utilis.toDouble(Lines[5])!=0) data.iMoney=data.iMoney+" 票刷:"+new BigDecimal(Lines[5]).toString();
							if (Utilis.toDouble(Lines[10])!=0) data.iMoney=data.iMoney+" 匯:"+new BigDecimal(Lines[10]).toString();
							
							if (Utilis.toDouble(Lines[6])!=0) data.iCompany=data.iCompany+new BigDecimal(Lines[6]).toString();
							if (Utilis.toDouble(Lines[7])!=0) data.iCompany=data.iCompany+" 票刷:"+new BigDecimal(Lines[7]).toString();
							if (Utilis.toDouble(Lines[11])!=0) data.iCompany=data.iCompany+" 墊:"+new BigDecimal(Lines[11]).toString();
							
						}else if (nKind==PItemKind.TR10 ){
							data.iGoods=Lines[1];
							data.iName=Lines[0];
							data.iImpo="應付:"+new BigDecimal(Math.round(Utilis.toDouble(Lines[2]))).toString();
							data.iMoney="件數:"+Lines[3];
							data.iCompany="款數:"+Lines[4];
							
						}else{
							data.iGoods=Lines[1];
							data.iName=Lines[0];
							data.iCountry=Lines[2];
							if (datas.iFormdate.equalsIgnoreCase(Lines[0]))
								data.iImpo="出貨:"+new BigDecimal(Utilis.toDouble(Lines[8])+Utilis.toDouble(Lines[11])).toString();
							else
								data.iImpo="轉給("+Lines[12]+")"+new BigDecimal(Utilis.toDouble(Lines[8])+Utilis.toDouble(Lines[11])).toString();
							
							data.iMoney="現金:";data.iCompany="訂金";
							if (Utilis.toDouble(Lines[4])!=0) data.iMoney=data.iMoney+new BigDecimal(Utilis.toDouble(Lines[4])).toString();
							if (Utilis.toDouble(Lines[5])!=0) data.iMoney=data.iMoney+" 票刷:"+new BigDecimal(Utilis.toDouble(Lines[5])).toString();
							if (Utilis.toDouble(Lines[10])!=0) data.iMoney=data.iMoney+" 匯:"+new BigDecimal(Utilis.toDouble(Lines[10])).toString();
							
							if (Utilis.toDouble(Lines[6])!=0) data.iCompany=data.iCompany+new BigDecimal(Lines[6]).toString();
							if (Utilis.toDouble(Lines[7])!=0) data.iCompany=data.iCompany+" 票刷:"+new BigDecimal(Lines[7]).toString();
							if (Utilis.toDouble(Lines[11])!=0) data.iCompany=data.iCompany+" 墊:"+Lines[11];
						
						}
						
						mAdapter1.mList.add(data);	
							
				}							
					Floor=1;
					((TextView)findViewById(R.id.text_t10t)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_m10)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_r10t)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_t30t)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_m30)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_r30t)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_tott)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_tot)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_mtot)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_rp0t)).setVisibility(View.GONE);
					((TextView)findViewById(R.id.text_rp0)).setVisibility(View.GONE);
					
					((TextView)findViewById(R.id.text_r10)).setText(datas.iImpo);//總前帳
					((TextView)findViewById(R.id.text_t10)).setText(datas.iName);//總應收 				
					((TextView)findViewById(R.id.text_t30)).setText(datas.iCountry);  //現金總收
					((TextView)findViewById(R.id.text_r30)).setText(datas.iCompany);//總結欠
					
			        ((Button)findViewById(R.id.btn_btn1)).setVisibility(View.INVISIBLE);	//週        
			        ((Button)findViewById(R.id.btn_btn2)).setVisibility(View.INVISIBLE);  //月
			        ((Button)findViewById(R.id.btn_btn3)).setVisibility(View.INVISIBLE);//季
			        ((Button)findViewById(R.id.btn_btn4)).setVisibility(View.INVISIBLE);
			        ((Button)findViewById(R.id.btn_prev_date)).setVisibility(View.INVISIBLE);//上一
			        ((Button)findViewById(R.id.btn_next_date)).setVisibility(View.INVISIBLE);//下一

					((ListView)findViewById(R.id.list_item)).setVisibility(View.GONE);
					((ListView)findViewById(R.id.list_item1)).setVisibility(View.VISIBLE);
					
					mAdapter1.notifyDataSetChanged();
					mTextDuration.setText(datas.iFormdate+"/ "+ mStartDay + "~" + mEndDay);
			}
		}
	}
}
};

Handler mHandlerQDR_23 = new Handler()
{
	@Override
	public  void handleMessage(Message msg)
	{
		//傳回的//upup_1-30_系統時間
		
		String Hresult=null;
		switch (msg.what)
		{
		// 顯示網路上抓取的資料
		case REFRESH_DATA:
			if (msg.obj instanceof String) 
				Hresult = (String) msg.obj;
			if (Hresult != null ){
				
				Log.i("DOWNLOAD_23", Hresult.substring(Hresult.indexOf("rep02;")+6));
					
				if (Hresult.indexOf("SSSS\r\n")>2){

					Hresult=	Hresult.substring(Hresult.indexOf("rep02;")+6);
					String Linea [] = Hresult.split("SSSS\r\n");
						
					for (int xx=0;xx<Linea.length;xx++){
						String Lines[] =Linea [xx].split(";");

						RepData data = new RepData();							
						data.iGoods=Lines[0]+"/"+Lines[1];
						data.iPic=Lines[4];
						data.iName=Lines[2];
						data.iCountry=Lines[3];
						data.iImpo="件數:"+Lines[6];
						data.iMoney="單價:"+Lines[5]+" 折:"+Lines[7];
						data.iCompany="小計:"+new BigDecimal(Lines[8]).toString();
						
						mAdapter2.mList.add(data);	
							
				}							
					Floor=2;
					mAdapter2.notifyDataSetChanged();
					((ListView)findViewById(R.id.list_item1)).setVisibility(View.GONE);
					((ListView)findViewById(R.id.list_item2)).setVisibility(View.VISIBLE);
					
			}
		}
	}
}
};

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

		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;
		}
		
		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();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			RepData data = mList.get(position);
			if (Floor==2 && data.iPic.length()>0) 	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;
			
		}

	}

}
