package com.cwbuyer.lib;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.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.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
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;

//程式名稱_各門市業績統計
@SuppressLint("HandlerLeak")
@SuppressWarnings("unused")
public class QRep_12 extends Activity{
	
	ReportAdapter mAdapter = null;
	ReportAdapter mAdapter1 = null;
	ReportAdapter mAdapter2 = null;
	
	TextView mTextDuration = null;

//ACTION 預設模式 POS定義為 銷貨單;預購單;暫存單;單頭+單身	
	
	int mMode = KeySet.SearchMode.MONTH;
	
	private final int RESULT_GALLERY=6666; 		//GALLERY
	
	int mGroupMode = GroupMode.TOP1;  //預設初始到新品 
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	final String myPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	
	/** State :  true 正式 , false 樣品*/
	String mEndDay = null;
	String mStartDay = null;
	private int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5)); //0OK 1密碼不符
	int nPart=0;
	String USER;
	int locations=0;
	int locationa=0;
	String SQLADM="";  //
	String SQLADD="(a.QKIND ='30' OR a.QKIND ='31' OR a.QKIND ='40' OR a.QKIND ='41')";  //補充條件 零售業績 非零售業績
	public ProgressDialog myDialog = null;
	String uriAPI=null;
	protected static final int REFRESH_DATA = 0x00000001;

	//發展為長按而啟動的功能
	String[] menu_E={"廠商", "出貨","銷貨","員購"};
	String[] menu_S={"月報表","列印月報表","列印A4月報表", "返回"};
	String[] menu_A={"月報表","列印月報表","列印A4月報表", "返回"};
	
	String[] menu_B={ "交易明細", "返回"};
	String mKind=null; //單別 102030405060

	int nKind=0;
	DatePicker dp1;
	DatePicker dp2;
	
   	String[] compStr = Utilis.getIni(this,"USER","COMPANY",9).split("!&!");
	String[] deptStr =Utilis.getIni(this,"SYS","DEPT",9).split("!&!");	
	String[] ImportStr =Utilis.getIni(this,"SYS","IMPORT",9).split("!&!");	
   	int mCloud=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT_SEND",4));
	int ORS=Utilis.toInt(Utilis.getIni(this, "SYS","DEPT_SEND", 6));
	
	String listDeptno="";
	String listDeptname="";
	String listPic="";

   	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;  	//本進貨量
   	double M10=0; 	//本進貨額
   	double T30=0;		//本銷貨量
   	double M30=0;	//本銷貨額
   	double S30=0;	//本銷貨額
   	double Profit=0; 	//本期毛利
   	double Profits=0; //本期利率
   	double Trcash=0;
   	double TTrcash=0;
   	double Tmacc=0;
   	double TTmacc=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;
		
	}

//@@日後需補充用ITEM檢測HEAD是否漏掉的清單,並自動修補	
	interface GroupMode{//EVERYDAY/WEEK/MONTH 以FORMDATE
		int TOP1=1;		//到新品
		int TOP2 = 2;  	//暢銷品
		int TOP3 = 3; 	//預購區
		int TOP4 = 4; 	//追加品
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent dataR) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, dataR);
		
		switch(requestCode){
		
		case 1001:
			{
				if (resultCode == RESULT_OK) {
				}else{
					finish();
				}
				break;
			}
		case RESULT_GALLERY:
			{
				
			}
		}	
    }

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrep01);
        
        mTextDuration = (TextView)findViewById(R.id.text_duration);
        //@@應增加營業時間的判斷而視為當日或前一天
        mStartDay =DateUtil.getCurrentDate();  //2012/10/15 將 batch 視為當日的關鍵"/"
        mEndDay=mStartDay;
        mMode = getIntent().getIntExtra("search_mode", KeySet.SearchMode.SEASON);
        
        //暫時不開放外部決定哪一種方式 預設為 週
        
        if (!deptStr[0].equalsIgnoreCase(deptStr[5])) nPart=1;  //門市版        
        if (nPart==1){
        	mKind="31";
        	nKind=31;
        }else{
        	mKind="3%";
        	nKind=30;
        }
        
        ((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_tott)).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("未收:");
        } else {
        	((TextView)findViewById(R.id.text_t10t)).setText("應付:");
        	((TextView)findViewById(R.id.text_t30t)).setText("已付:");
        	((TextView)findViewById(R.id.text_r30t)).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);
        
        //原先就是執行一遍 因為不會中途改變模式
        //現在是可以切換
        //只要一切換,都會從最近日期範圍貨最近一批最近一季起算
        chkMode();
        
        mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View v,
					int position, long ids) {
				// TODO Auto-generated method stub
				locationa=position;
				
				Utilis.runVibrate(QRep_12.this);
				DialogUtilis.showDialog(QRep_12.this, "請選擇以下功能", -1,
						menu_S, new IDialog() {
							@Override
							public void onDialogFinish(int pos, String choice) {
			switch (pos) {
				case 0: //月報表顯示於畫面二樓
				{
					if (mAdapter1.mList != null) {
						mAdapter1.mList.clear();
					}
					if (mAdapter.getCount()>0){
						RepData datas = (RepData) mAdapter.getItem(locationa);
						String dbStartDay="";
						String dbEndDay="";
						listDeptno=datas.iFormdate;
						listDeptname=datas.iGoods;
						listPic=datas.iPic;

						if(mStartDay != null && mStartDay.length() > 0)	dbStartDay = mStartDay.replace("/", "-");
						if(mEndDay != null && mEndDay.length() > 0) dbEndDay = mEndDay.replace("/", "-");
						StringBuffer mBuf = new StringBuffer();
						mBuf.append("select a.FORMDATE,a.DEPTNO,sum(a.ATOT),sum(a.BSUM),sum(a.CASH),sum(a.CARD),sum(a.ORDCASH),sum(a.ORDCARD),sum(a.ATM),b.MINTO");
						mBuf.append(" from qhead as a left join qmacc as b on ( a.DEPTNO=b.DEPTNO and a.FORMDATE=b.FORMDATE and b.QNOM='0000')");
					    mBuf.append(" where  (( a.FORMDATE >= '").append(dbStartDay).append("' and a.FORMDATE <= '").append(dbEndDay)	.append("' and a.ISCONFIRM='Y' ) or ")
						.append(" ( a.FINEDATE<>'' and a.FINEDATE>='").append(dbStartDay)	.append("' and a.FINEDATE <= '").append(dbEndDay).append("' and a.ISCONFIRM='Y' )");
						if (ORS!=2){
							mBuf.append(" or ( a.ORDDATE<>'' and a.ORDDATE>='").append(dbStartDay).append("' and a.ORDDATE <= '").append(dbEndDay).append("' and a.ISCHECK='Y' and a.ISCONFIRM='N')) ");
						}else{
							mBuf.append(")");
						}
							mBuf.append(" and a.DEPTNO='").append(datas.iFormdate).append("' and ");
							
					    	if  (Utilis.haveInternet(QRep_12.this) && Utilis.toInt(ImportStr[2])==1 && mCloud>0)
					    		mBuf.append(" a.TR<>'Y2' and ");
					    	
							mBuf.append(SQLADD);
						mBuf.append(" group by a.DEPTNO,a.FORMDATE");
						
						if  (Utilis.haveInternet(QRep_12.this) && Utilis.toInt(ImportStr[2])==1 && mCloud>0){
							StringBuffer bfstr = new StringBuffer();
							StringBuffer bfstrF = new StringBuffer();
							
								bfstr.append(ImportStr[1]).append(";");
								bfstrF.append("UID").append(";");
								bfstr.append(dbStartDay).append(";");
								bfstrF.append("BGDAY").append(";");
								bfstr.append(dbEndDay).append(";");
								bfstrF.append("ENDAY").append(";");

								bfstr.append(datas.iFormdate).append(";");
								bfstrF.append("DEPTNO").append(";"); 
								bfstr.append(deptStr[5]).append(";");
								bfstrF.append("DEPTAA").append(";");  //總倉代號 名稱
								bfstr.append(mBuf.toString());
								bfstrF.append("SQLADD");//搜尋的語法,直接交給CLOUD
								
								final String []fields=bfstr.toString().split(";");
								final String []fieldFs=bfstrF.toString().split(";");
								
							      myDialog = ProgressDialog.show(QRep_12.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
								  
							      new Thread()
							      { 
							        public void run()
							        { 
							          try
							          { 
											uriAPI="http://"+ImportStr[0]+File.separator+ImportStr[1]+File.separator+"qdeptrep_31_N.php";
											HttpPost httpRequest = new HttpPost(uriAPI);
											// Post運作傳送變數必須用NameValuePair[]陣列儲存
											Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);

											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_31.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_12.this);
						Cursor cs=db.rawQuery(mBuf.toString(), null);
						 //Toast.makeText(QRep_12.this, "Found__"+cs.getCount(), Toast.LENGTH_LONG).show();
						//FORMDATE,DEPTNO,ATOT,BSUM,CASH,CARD,ORDCASH,ORDCARD,ATM,MINTO,
						if (cs.getCount()>0){
							String Report31="reporting;SSSS\r\n";
							while (cs.moveToNext()){
								for (int xx=0;xx<9;xx++){
									if (xx<=1)	Report31+=cs.getString(xx)+",";
									else
										Report31+=Math.round(cs.getDouble(xx))+",";
								}	
								Report31+=cs.getString(9)+";SSSS\r\n";	
							}
							showList31(datas.iFormdate,Report31.split(";SSSS\r\n"));							
						}
						cs.close();
						db.close();
						}
					}										
					break;
				}
				case 1: //列印月報表 
				{
					RepData datas = (RepData) mAdapter.getItem(locationa);
					String dbStartDay="";
					String dbEndDay="";
					
					if(mStartDay != null && mStartDay.length() > 0)	dbStartDay = mStartDay.replace("/", "-");
					if(mEndDay != null && mEndDay.length() > 0) dbEndDay = mEndDay.replace("/", "-");
					
					StringBuffer mBuf = new StringBuffer();
					
					mBuf.append(makeSQLforPrinter(dbStartDay,dbEndDay, datas.iFormdate));
					
					//LocalHost
					SQLiteDatabase db = Utilis.getDB(QRep_12.this);
					StringBuffer sPrintB = new StringBuffer();
					Cursor cs=db.rawQuery(mBuf.toString(), null);
						String sepa="\r\n";
						int Loca=0;
						sPrintB.append("^QXXXX,0,0"+sepa);
						sPrintB.append("^W56"+sepa+"^H6"+sepa+"^P1"+sepa+"^S4"+sepa+"^AD"+sepa+"^C1"+sepa+"^R0"+sepa+"~Q+0"+sepa
						+"^O0"+sepa+"^D0"+sepa+"^E11"+sepa+"~R20"+sepa+"^L"+sepa+"Dy2-me-dd"+sepa+"Th:m:s"+sepa);
						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,期間: "+dbStartDay+" ~ "+dbEndDay+sepa);
						Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,門市: "+datas.iGoods+sepa);
						Loca=Loca+35;sPrintB.append("AZ,12,"+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.substring(0, datas.iName.indexOf("("))+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.iCompany+sepa);
													sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+datas.iMoney.substring(datas.iMoney.indexOf("收支:"))+sepa);
					if (cs.getCount()>0){
						cs.moveToFirst();
						for (int ij=0;ij<cs.getCount();ij++){
							Loca=Loca+30;sPrintB.append("AZ,12,"+Loca+",1,2,0,0,--------------------------------------"+sepa);																			
							Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,日期:"+cs.getString(0)+sepa);
														sPrintB.append("AZ,212,"+Loca+",1,1,0,0,件數:"+Math.round(cs.getDouble(2))+sepa);
							Loca=Loca+35;sPrintB.append("AZ,20,"+Loca+",1,1,0,0,應收:"+Math.round(cs.getDouble(3))+sepa);
							if (cs.getString(14)!=null && cs.getInt(14)!=0)
								sPrintB.append("AZ,212,"+Loca+",1,1,0,0,收支:"+Math.round(cs.getDouble(14))+sepa);
							else
								sPrintB.append("AZ,212,"+Loca+",1,1,0,0,收支:0.0"+sepa);
							
							Loca=Loca+35;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,入金:"+Math.round(cs.getDouble(4)+cs.getDouble(6))+sepa);
														sPrintB.append("AZ,232,"+Loca+",1,2,0,0,"+"票刷匯:"+Math.round(cs.getDouble(5)+cs.getDouble(7)+cs.getDouble(8))+sepa);
						cs.moveToNext();
						}
					}
					db.close();
					cs.close();
					
					Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,======================================"+sepa);
//											Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);											
						String lenS="0000"+(int)((Loca+100)/7.32);
						sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
						sPrintB.append("E"+sepa);

				 		String batchFile=myImportPath+File.separator+"cwbuyer_barprint.txt";  //預設為分色尺寸
				        File myFile = new File(batchFile); //其目的是為了產生一個新檔案或資料夾
				        if (myFile.exists()){
				        	myFile.delete();
				        }
						boolean Succed=false;
						BufferedWriter bw;
						try {
							bw = new BufferedWriter(new FileWriter(myFile));
			                 if (sPrintB.toString() !=null && sPrintB.toString().length()>0)
			                 { bw.write(sPrintB.toString()); }
			                 bw.close();
						} catch (IOException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}
						
						
						String address=null;
						int port=0;
						int success=1;
						   address = Utilis.getIni(QRep_12.this, "SYS","BAR_IP", 4);// 連線的ip
						   port =Utilis.toInt(Utilis.getIni(QRep_12.this, "SYS","BAR_IP", 5));// 連線的port
							 InetAddress serverAddr = null;
						        SocketAddress sc_add = null;
						        Socket socket = null;
			
									 try {
										 serverAddr = InetAddress.getByName(address);
										 sc_add= new InetSocketAddress(serverAddr,port);
											 socket = new Socket();
											 socket.connect(sc_add,2000);
											 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
											 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
											 out.write(data, 0, data.length);
											 socket.close();
											 Toast.makeText(QRep_12.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
											 Succed=true;
									 } catch (UnknownHostException e) {
										 success=0;
									 } catch (SocketException e) {
										 success=0;
									 } catch(IOException e) {
										 success=0;
									 }
					break;
				}
				case 2: //列印A4月報表 
				{
					RepData datas = (RepData) mAdapter.getItem(locationa);
					String dbStartDay="";
					String dbEndDay="";
					
					if(mStartDay != null && mStartDay.length() > 0)	dbStartDay = mStartDay.replace("/", "-");
					if(mEndDay != null && mEndDay.length() > 0) dbEndDay = mEndDay.replace("/", "-");
					
					StringBuffer mBuf = new StringBuffer();
					
					mBuf.append(makeSQLforPrinter(dbStartDay,dbEndDay, datas.iFormdate));
					
					if  (Utilis.haveInternet(QRep_12.this) && Utilis.toInt(ImportStr[2])==1 && mCloud>0){
						StringBuffer bfstr = new StringBuffer();
						StringBuffer bfstrF = new StringBuffer();
						
							bfstr.append(ImportStr[1]).append(";");
							bfstrF.append("UID").append(";");
							bfstr.append(dbStartDay).append(";");
							bfstrF.append("BGDAY").append(";");
							bfstr.append(dbEndDay).append(";");
							bfstrF.append("ENDAY").append(";"); 
							bfstr.append(datas.iFormdate).append(";");
							bfstrF.append("DEPTNO").append(";"); 
							bfstr.append(""+nKind).append(";");
							bfstrF.append("QKIND").append(";");  //單別
							bfstr.append(mBuf.toString());
							bfstrF.append("SQLADD");  //總倉代號 名稱
							
							final String []fields=bfstr.toString().split(";");
							final String []fieldFs=bfstrF.toString().split(";");
							
						      myDialog = ProgressDialog.show(QRep_12.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
							  
						      new Thread()
						      { 
						        public void run()
						        { 
						          try
						          { 
										uriAPI="http://"+ImportStr[0]+File.separator+ImportStr[1]+File.separator+"qrep12_pA4.php";
										HttpPost httpRequest = new HttpPost(uriAPI);
										// Post運作傳送變數必須用NameValuePair[]陣列儲存
										Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);

										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_3A4.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
												
											}
										} catch (Exception e)
										{
											e.printStackTrace();
										}

						          }
						          catch (Exception e)
						          {
						            e.printStackTrace();
						          }
						          finally
						          {
						            // 卸載所建立的myDialog物件。
						            myDialog.dismiss();
						          }
						        }
						      }.start();
					}else{ //非雲端A4 印報表
						SQLiteDatabase db = Utilis.getDB(QRep_12.this);
						//StringBuffer sPrintB = new StringBuffer();
						Cursor cs=db.rawQuery(mBuf.toString(), null);
						StringBuffer bBuf = new StringBuffer();
						if (cs.getCount()>0){
							while (cs.moveToNext()){
								//$returnstr.=$rowC[0].";".$rowC[1].";".$rowC[2].";".$rowC[3].";".$rowC[4].";".$rowC[5].";".$rowC[6].";".$rowC[7].";".$rowC[8].";".$rowC[9].";".$rowC[10].";".$rowC[11].";".$rowC[12].";".$rowC[13].";SSSS"."\r\n";
								//0                ,1            ,2      ,3        ,4       ,5       ,6              ,7               ,8     ,9        ,10         ,11           ,12             ,13              ,14 
								//FORMDATE,DEPTNO,ATOT,BSUM,CASH,CARD,ORDCASH,ORDCARD,ATM,ASUM,TRCASH,FORMNO,TRUESUM,DISMONEY,MINTO
								for (int i=0;i<=13;i++){
									if (i<=1)
										bBuf.append(cs.getString(i)).append(";");
									else
										bBuf.append(Math.round(cs.getDouble(i))).append(";");
										
								}
								bBuf.append(";SSSS"+"\r\n");
							}
							cs.close();
							bBuf.append(";HHHH"+"\r\n");
							
							/*							
							String ASK="select a.FORMDATE,a.PS1,sum(a.BSUM) from qhead as a where";
							ASK+=" ((a.FORMDATE >= '"+dbStartDay+"' and a.FORMDATE <= '"+dbEndDay+"' and a.ISCONFIRM='Y' ) or ";
							ASK+=" ( a.FINEDATE<>'' and a.FINEDATE>='"+dbStartDay+"' and a.FINEDATE <= '"+dbEndDay+"' and a.ISCONFIRM='Y' )";
							if (ORS!=2){
							ASK+=" or ( a.ORDDATE<>null and a.ORDDATE<>'' and a.ORDDATE>='"+dbStartDay+"' and a.ORDDATE <= '"+dbEndDay+"' and a.ISCHECK='Y' and a.ISCONFIRM='N'))";
							}else{
								ASK+=")";
							}
							
							ASK+=" and a.DEPTNO = '"+datas.iFormdate+"' and "+SQLADD;
							ASK+=" group by a.FORMDATE,a.PS1 order by a.FORMDATE,a.PS1";

							Cursor csi=db.rawQuery(ASK, null);
							if (csi.getCount()>0){
								while (csi.moveToNext()){
									for (int i=0;i<=2;i++){
									bBuf.append(csi.getString(i)).append(";");
									}
									bBuf.append(";SSSS"+"\r\n");
								}
							}
							
							csi.close();
*/							
						
						}
						db.close();
						if (bBuf.toString().length()>0){
							Intent intent = new Intent();
							intent.putExtra("SERCH",datas.iFormdate);
							intent.putExtra("QKIND",""+nKind);
							intent.putExtra("MODE",5);
							intent.putExtra("DEPTNO",datas.iFormdate);
							intent.putExtra("BUFSTR",bBuf.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_12.this, MkqrSt.class);
							startActivity(intent);
						}
					}
					break;
				}
				
				case 3: //返回
				{
					break;
				}
			}//end of switch
							}//end of showDialogFinish	
				});//end of showDialog
			}//end of onItemClick
		});//end of onItemClickListener

        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_12.this);
				DialogUtilis.showDialog(QRep_12.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);
											listDeptno=datas.iFormdate;
											listDeptname=datas.iGoods;
											listPic=datas.iPic;
											
											StringBuffer mBuf = new StringBuffer();
											mBuf.append("select a.FORMNO,a.USER,a.USERNAME,a.HANDNO,a.BSUM,a.CASH,a.CARD,a.ORDCASH,a.ORDCARD,a.ATM,b.PIC");
											mBuf.append(" from qhead as a left join qcust as b on (a.USER=b.CUSTNO)");
										    mBuf.append(" where  (( a.FORMDATE = '").append(datas.iName).append("' and a.ISCONFIRM='Y' ) or ")
											.append(" ( a.FINEDATE<>'' and a.FINEDATE='").append(datas.iName).append("' and a.ISCONFIRM='Y')");
											if (ORS!=2){
												mBuf.append(" or ( a.ORDDATE<>'' and a.ORDDATE='").append(datas.iName).append("' and a.ISCHECK='Y' and a.ISCONFIRM='N' )) ");
											}else{
												mBuf.append(")");
											}
											mBuf.append(" and a.DEPTNO='").append(datas.iFormdate).append("' and ");
											
									    	if  (Utilis.haveInternet(QRep_12.this) && Utilis.toInt(ImportStr[2])==1 && mCloud>0)
									    		mBuf.append(" a.TR<>'Y2' and ");

											
											mBuf.append(SQLADD)
											.append(" order by a.FORMNO");
											
											if  (Utilis.haveInternet(QRep_12.this) && Utilis.toInt(ImportStr[2])==1 && mCloud>0){
												StringBuffer bfstr = new StringBuffer();
												StringBuffer bfstrF = new StringBuffer();
												
													bfstr.append(ImportStr[1]).append(";");
													bfstrF.append("UID").append(";");
													bfstr.append(datas.iName).append(";");
													bfstrF.append("BGDAY").append(";");
													bfstr.append(datas.iName).append(";");
													bfstrF.append("ENDAY").append(";"); 
													bfstr.append(datas.iFormdate).append(";");
													bfstrF.append("DEPTNO").append(";"); 
													bfstr.append(deptStr[5]).append(";");
													bfstrF.append("DEPTAA").append(";");  //總倉代號 名稱
													bfstr.append(mBuf.toString()); //直接的SQL_String
													bfstrF.append("SQLADD");
													
													final String []fields=bfstr.toString().split(";");
													final String []fieldFs=bfstrF.toString().split(";");
													
												      myDialog = ProgressDialog.show(QRep_12.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
													  
												      new Thread()
												      { 
												        public void run()
												        { 
												          try
												          { 
																uriAPI="http://"+ImportStr[0]+File.separator+ImportStr[1]+File.separator+"qdeptrep_32_N44.php";
																HttpPost httpRequest = new HttpPost(uriAPI);
																// Post運作傳送變數必須用NameValuePair[]陣列儲存
																Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);

																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);
																	if (httpResponse.getStatusLine().getStatusCode() == 200)
																	{
																		String strResult = EntityUtils.toString(httpResponse	.getEntity());
																		mHandlerQDR_32.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
																		
																	}
																} catch (Exception e)
																{
																	e.printStackTrace();
																}

												          }
												          catch (Exception e)
												          {
												            e.printStackTrace();
												          }
												          finally
												          {
												            // 卸載所建立的myDialog物件。
												            myDialog.dismiss();
												          }
												        }
												      }.start(); 
											}else{ //local DB
												
												SQLiteDatabase db = Utilis.getDB(QRep_12.this);
												String Report32="reporting;SSSS\r\n";
												Cursor cs=db.rawQuery(mBuf.toString(), null);
												if (cs.getCount()>0){
													while (cs.moveToNext()){
														for (int xx=0;xx<10;xx++)
															Report32+=cs.getString(xx)+",";
														Report32+=cs.getString(10)+";SSSS\r\n";
													}
												}
												cs.close();
												db.close();
												showList32(Report32.split(";SSSS\r\n"));
											}
										}
										break;
									}
									case 1: //返回
									{
										break;
									}
								}
							}				
				});
			}
		});
        
}	
	
	public void onResume(){
		super.onResume();
		
		//表示非外來程式 
//			getGroupData(QRep_01.this, mStartDay, mEndDay, null, null);
		
		DBCloud.aa0_aa1_auto_qmacc(this);
		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);
		
		
			mAdapter.notifyDataSetChanged();
		}
	
	private void setCondition(){
		mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
	}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	public void getGroupData(Context context, String dbStartDay, String dbEndDay, String condition, String conditionValue) {
					
			if (mAdapter.mList != null) {
				mAdapter.mList.clear();
			}
			if(dbStartDay != null && dbStartDay.length() > 0)	dbStartDay = dbStartDay.replace("/", "-");
			if(dbEndDay != null && dbEndDay.length() > 0) dbEndDay = dbEndDay.replace("/", "-");
			
			TT10=0;  TM10=0; 	TT30=0;	TM30=0;
			TS30=0;	 StkT=0;		StkM=0;	
			Profit=0; Profits=0;	TR10=0;
			Trcash=0;TTrcash=0;
			Tmacc=0;TTmacc=0;
			
			StringBuffer bufCategory = new StringBuffer();
			StringBuffer bufSecond = new StringBuffer();
			
			 Toast.makeText(QRep_12.this, "對帳自_"+dbStartDay+"至_"+dbEndDay+"為止", Toast.LENGTH_LONG).show();

			//第一層[前帳] 以日期範圍先算出 
			bufCategory=bufCategory.delete(0, bufCategory.toString().length());
	    	bufCategory.append("select a.DEPTNO,b.CUSTNAME,b.PIC,") //
	    	.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.ATM),sum(a.TRCASH)")
	    	.append(" from qhead as a left join qcust as b on (a.DEPTNO=b.CUSTNO)");
//3BSUM,4COSTS,5CASH,6CARD,7ORDCASH,8ORDCARD,9ATOT,10DISMONEY,11ATM,12TRCASH
	    	bufCategory.append(" where  (( a.FORMDATE < '").append(dbEndDay).append("' and a.ISCONFIRM='Y' ) or ")
			.append(" ( a.FINEDATE<>'' and a.FINEDATE < '").append(dbEndDay).append("' and a.ISCONFIRM='Y' )");
	    	if (ORS!=2){
	    		bufCategory.append(" or ( a.ORDDATE<>'' and a.ORDDATE < '").append(dbEndDay).append("' and a.ISCHECK='Y'  and a.ISCONFIRM='N')) and ");
	    	}else{
	    		bufCategory.append(") and ");
	    	}
	    	
    		bufCategory.append(" a.TR<>'Y2' and ");
	    	
			bufCategory.append(SQLADD)
	    	.append(" group by a.DEPTNO order by a.DEPTNO");
			
			
			//第二層[本期]預設SQL 可以針對 Cloud or Local
			bufSecond.append("select a.DEPTNO,") //
	    	.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.ATM),sum(a.TRCASH),(select sum(b.MINTO) from qmacc as b where b.FORMDATE >= '"+dbStartDay+"' and b.FORMDATE <= '"+dbEndDay+"' and b.DEPTNO= '%SDEPTNO' and b.QNOM='0000' ) ")
	    	//0DEPTNO,1BSUM,2COSTS,3CASH,4CARED,5ORDCASH,6ORDCARD,7ATOT,8DISMINEY,9ATM,10TRCASH
	    	.append(" from qhead as a ");
			bufSecond.append(" where  (( a.FORMDATE >= '").append(dbStartDay).append("' and a.FORMDATE <= '").append(dbEndDay)
			.append("' and a.ISCONFIRM='Y' ) or ")
			.append(" ( a.FINEDATE<>'' and a.FINEDATE >= '").append(dbStartDay).append("' and a.FINEDATE <= '").append(dbEndDay).append("' and a.ISCONFIRM='Y' )");
			if (ORS!=2){
				bufSecond.append(" or ( a.ORDDATE<>'' and a.ORDDATE>='").append(dbStartDay).append("' and a.ORDDATE <= '").append(dbEndDay).append("' and a.ISCHECK='Y' and a.ISCONFIRM='N' ))");
			}else{
				bufSecond.append(")");
			}
			bufSecond.append(" and a.DEPTNO= '%SDEPTNO' and ");
			
    		bufSecond.append(" a.TR<>'Y2' and ");
			
	    	bufSecond.append(SQLADD)
			.append(" group by a.DEPTNO");
			
			
			
			
			if  (Utilis.haveInternet(context) && Utilis.toInt(ImportStr[2])==1 && mCloud>0){
				StringBuffer bfstr = new StringBuffer();
				StringBuffer bfstrF = new StringBuffer();
				
					bfstr.append(ImportStr[1]).append(";");
					bfstrF.append("UID").append(";");
					bfstr.append(dbStartDay).append(";");
					bfstrF.append("BGDAY").append(";");
					bfstr.append(dbEndDay).append(";");
					bfstrF.append("ENDAY").append(";");
					bfstr.append(deptStr[0]).append(";");
					bfstrF.append("DEPTNO").append(";");  //門市代號
					bfstr.append(deptStr[5]).append(";");
					bfstrF.append("DEPTAA").append(";");  //總倉代號
					bfstr.append(bufCategory.toString()).append(";");
					bfstrF.append("SQLADM").append(";");
					bfstr.append(bufSecond.toString());
					bfstrF.append("SQLADD");  //總倉代號 名稱
					
					final String []fields=bfstr.toString().split(";");
					final String []fieldFs=bfstrF.toString().split(";");
					
				      myDialog = ProgressDialog.show(this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
					  
				      new Thread()
				      { 
				        public void run()
				        { 
				          try
				          { 
								uriAPI="http://"+ImportStr[0]+File.separator+ImportStr[1]+File.separator+"qdeptrep_30_N44.php";
								HttpPost httpRequest = new HttpPost(uriAPI);
								// Post運作傳送變數必須用NameValuePair[]陣列儲存
								Log.i("DOWNLOAD_2", "呼叫執行緒PHP___到此一遊"+uriAPI);

								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_30.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);
			try {
				Cursor cursorGroup = null;

			    //已上取得所有成員,至今所有帳,不包括後面日期的帳
			    //只要再算出本期的帳,相減就得到本期帳
			    
 				cursorGroup = db.rawQuery(bufCategory.toString(), null);
				int chked=0;
 				
				if (cursorGroup != null) {
					if (cursorGroup.getCount() > 0) {
						cursorGroup.moveToFirst();
						
						//如何製作與 CLOUD 傳回的格式一致
						String ReportStr="DEPTREP_30_REPORTING;SSSS\r\n";
						
						for (int i = 0; i < cursorGroup.getCount(); i++) {
							RepData data = new RepData();
							
							//data.iFormdate=cursorGroup.getString(0); //門市代號
							//data.iGoods=cursorGroup.getString(0)+cursorGroup.getString(1); //門市代號/名稱
							//後製圖檔路徑
							//data.iPic=cursorGroup.getString(2);
							
							double sumOwl=cursorGroup.getDouble(3)-(cursorGroup.getDouble(5)+cursorGroup.getDouble(6)+cursorGroup.getDouble(7)+cursorGroup.getDouble(8)+cursorGroup.getDouble(11));
							//3BSUM,4COSTS,5CASH,6CARD,7ORDCASH,8ORDCARD,9ATOT,10DISMONEY,11ATM,12TRCASH

							Cursor csd;
							String SQL=bufSecond.toString();
							String SQLL=SQL.replace("%SDEPTNO", cursorGroup.getString(0));
							csd=db.rawQuery(SQLL, null);
							
							if (csd.getCount()>0){
								ReportStr+=cursorGroup.getString(0)+","+cursorGroup.getString(1)+","+cursorGroup.getString(2);
								csd.moveToFirst();
								chked=1;
								double sumOwl2=csd.getDouble(1)-(csd.getDouble(3)+csd.getDouble(4)+csd.getDouble(5)+csd.getDouble(6)+csd.getDouble(9));
						    	//0DEPTNO,1BSUM,2COSTS,3CASH,4CARED,5ORDCASH,6ORDCARD,7ATOT,8DISMINEY,9ATM,10TRCASH
								//if (sumOwl !=0 || sumOwl2!=0 ) {data.iSort=1;} else data.iSort=0;  //做為未來是否傳送資料依據
								//TR10=TR10+(sumOwl-sumOwl2); //前欠
								//Profits=Profits+(sumOwl);  //總結欠
								//data.iImpo="前帳:"+(sumOwl-sumOwl2);

									for (int xx=1;xx<=11;xx++)
									ReportStr+=(","+csd.getDouble(xx));
									
									ReportStr+=","+sumOwl+","+sumOwl2+";SSSS\r\n";

							}
								cursorGroup.moveToNext();
								csd.close();
						}
							showList(ReportStr.split(";SSSS\r\n"));
 					}
 				}
					cursorGroup.close();
	 				db.close();
	 				db = null;
					
					showTitleA();
					
			} catch (Exception e) {
				e.printStackTrace();
			}
			}								
		}
	
	private void showList(String dataS[]){
		
		
		for (int xx=1;xx<dataS.length;xx++){
			String Lines[] =dataS [xx].split(",");

			RepData data = new RepData();							
			data.iGoods=Lines[0].trim()+"/"+Lines[1].trim();
			data.iFormdate=Lines[0].trim();
			data.iPic=Lines[2].trim();
			TR10=Math.round(TR10)+Math.round(Utilis.toDouble(Lines[14])-Utilis.toDouble(Lines[15])); //前欠
			Profits=Math.round(Profits)+Math.round(Utilis.toDouble(Lines[14]));  //總結欠
			data.iImpo="前帳:"+Math.round(Utilis.toDouble(Lines[14])-Utilis.toDouble(Lines[15]));
/*
0          1        2     3          4            5            6          7               8               9              10              11          12          13    (14)(15)          
a.DEPTNO,a.CUSTNAME,a.PIC,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.ATM),sum(a.TRCASH),(select sum(b.MINTO) from qmacc as b where b.FORMDATE >= '"+startDayX+"' and b.FORMDATE <= '"+endDayX+"' and b.DEPTNO= '%SDEPTNO' and b.QNOM='0000' ) ")
*/
			//@@@
			if (!Lines[3].equalsIgnoreCase("null") && Lines[3].length()>0) T10=Utilis.toDouble(Lines[3]); else T10=0; //本期應收
			TT10=Math.round(TT10+T10);  //
			if (!Lines[4].equalsIgnoreCase("null") && Lines[4].length()>0) M10=Utilis.toDouble(Lines[4]); else M10=0;//成本
			TM10=Math.round(TM10+M10);//成本
			if (!Lines[5].equalsIgnoreCase("null") && Lines[5].length()>0) T30=Utilis.toDouble(Lines[5]); //現金收入
			TT30=Math.round(TT30+T30);
			if (!Lines[6].equalsIgnoreCase("null") && Lines[6].length()>0) M30=Utilis.toDouble(Lines[6]); else M30=0; 
			if (!Lines[11].equalsIgnoreCase("null") && Lines[11].length()>0) M30+=Utilis.toDouble(Lines[11]); //票卡收入
			TM30=Math.round(TM30+M30);
			if (!Lines[7].equalsIgnoreCase("null") && Lines[7].length()>0) S30=Utilis.toDouble(Lines[7]); else S30=0;//訂現收入
			StkT=Math.round(StkT+S30);
			if (!Lines[8].equalsIgnoreCase("null") && Lines[8].length()>0) R10=Utilis.toDouble(Lines[8]); else R10=0;//訂刷收入
			StkM=Math.round(StkM+R10);
			
			if (!Lines[12].equalsIgnoreCase("null") && Lines[12].length()>0) Trcash=Utilis.toDouble(Lines[12]); else Trcash=0;
			TTrcash=Math.round(TTrcash+Trcash);
			
			if (!Lines[13].equalsIgnoreCase("null") && Lines[13].length()>0) Tmacc=Utilis.toDouble(Lines[13]); else Tmacc=0; 
			TTmacc=Math.round(TTmacc+Tmacc);
			
			Profit=Math.round(Profit+(T10-(T30+M30+S30+R10)));

			data.iCompany="結欠:"+Math.round(Utilis.toInt(Lines[14])); //到目前為止
			
			if (PSWD==1)
				data.iName="應收:"+Math.round(T10);  //毛利
			else
				data.iName="應收:"+Math.round(T10)+"("+Math.round(T10-M10-Trcash)+")";

				data.iCountry="已收:"+Math.round(T30+S30)+" 卡:"+Math.round(M30+R10);
				data.iMoney="未收:"+(Math.round(T10-(T30+M30+S30+R10)))+"收支:"+Math.round(Tmacc);
				
				mAdapter.mList.add(data);	
		}
			mAdapter.notifyDataSetChanged();
	}
	
	private void showList31(String Adeptno,String dataS[]){//顯示月報表(每一日)

		for (int xx=1;xx<dataS.length;xx++){
			String Lines []=dataS[xx].split(",");
//0				1		2			3			4			5			6				7				8		9		
//a.FORMDATE,a.DEPTNO,sum(a.ATOT),sum(a.BSUM),sum(a.CASH),sum(a.CARD),sum(a.ORDCASH),sum(a.ORDCARD),sum(a.ATM),b.MINTO
			
			RepData data = new RepData();							
			data.iGoods=listDeptname;
			data.iName=Lines[0];
			data.iCountry=Lines[2];
			data.iPic=listPic;
			data.iFormdate=Lines[1];
			
			if (Lines.length>9 && Lines[9].length()>0 && !Lines[9].equalsIgnoreCase("null"))
				data.iImpo="應收:"+Math.round(Utilis.toDouble(Lines[3]))+"/收支:"+Math.round(Utilis.toDouble(Lines[9]));
			else
				data.iImpo="應收:"+Math.round(Utilis.toDouble(Lines[3]));
			
			data.iMoney="現金:"+Math.round(Utilis.toDouble(Lines[4]))+" 卡:"+Math.round(Utilis.toDouble(Lines[5]))+" 匯:"+Math.round(Utilis.toDouble(Lines[8]));
			data.iCompany="訂金:"+Math.round(Utilis.toDouble(Lines[6]))+" 卡:"+Math.round(Utilis.toDouble(Lines[7]));
			mAdapter1.mList.add(data);
		}
		
		Floor=1;
        ((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(Adeptno+"/ "+ mStartDay + "~" + mEndDay);
		
	}
	
	private void showList32(String dataS[]){
		
		for (int xx=1;xx<dataS.length;xx++){
			String Lines []=dataS[xx].split(",");
		
			RepData data = new RepData();							
			data.iGoods=Lines[1]+"/"+Lines[2];//USER/USERNAME
			data.iName=Lines[0];//FORMNO
			data.iCountry=Lines[3];
			data.iPic=Lines[10];
			data.iImpo="應收:"+Math.round(Utilis.toDouble(Lines[4]));
			data.iMoney="現金:"+Math.round(Utilis.toDouble(Lines[5]))+" 卡:"+Math.round(Utilis.toDouble(Lines[6]))+" 匯:"+Math.round(Utilis.toDouble(Lines[9]));
			data.iCompany="訂金:"+Math.round(Utilis.toDouble(Lines[7]))+" 卡:"+Math.round(Utilis.toDouble(Lines[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);
		mTextDuration.setText(listDeptname+"/ "+ mStartDay + "~" + mEndDay);
	}
	
	private void showTitleA(){
			((TextView)findViewById(R.id.text_tot)).setText("$:"+Math.round(StkT));  //訂金
			((TextView)findViewById(R.id.text_mtot)).setText("卡:"+Math.round(StkM)); //訂卡
			((TextView)findViewById(R.id.text_r10)).setText("$:"+Math.round(TR10));//總前帳

			((TextView)findViewById(R.id.text_t10)).setText("$:"+Math.round(TT10));//總應收
			 if (PSWD==1) ((TextView)findViewById(R.id.text_m10)).setText("");
			 	else ((TextView)findViewById(R.id.text_m10)).setText("("+Math.round(TT10-TM10-TTrcash)+")");//總毛利
			 
			((TextView)findViewById(R.id.text_t30)).setText("$:"+Math.round(TT30)+" 收支$:"+Math.round(TTmacc));  //現金總收
			((TextView)findViewById(R.id.text_m30)).setText("卡:"+Math.round(TM30)); //卡總收
			((TextView)findViewById(R.id.text_r30)).setText("$:"+Math.round(Profit)); //本期未收
			((TextView)findViewById(R.id.text_rp0)).setText("$:"+Math.round(Profits));//總結欠
	}
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_12.this);
			switch (id) {
				case R.id.btn_exit:
				{
				if (Floor==0){	
		        	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);//下一
					
					((ListView)findViewById(R.id.list_item)).setVisibility(View.VISIBLE);
					((ListView)findViewById(R.id.list_item1)).setVisibility(View.GONE);
					mTextDuration.setText(" "+ mStartDay + "~" + mEndDay);
				}else if (Floor==2){
					Floor=1;
					((ListView)findViewById(R.id.list_item1)).setVisibility(View.VISIBLE);
					((ListView)findViewById(R.id.list_item2)).setVisibility(View.GONE);
				}
					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();
						String sepa="\r\n";
						int Loca=0;
						sPrintB.append("^QXXXX,0,0"+sepa);
						sPrintB.append("^W56"+sepa+"^H6"+sepa+"^P1"+sepa+"^S4"+sepa+"^AD"+sepa+"^C1"+sepa+"^R0"+sepa+"~Q+0"+sepa
						+"^O0"+sepa+"^D0"+sepa+"^E11"+sepa+"~R20"+sepa+"^L"+sepa+"Dy2-me-dd"+sepa+"Th:m:s"+sepa);
						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);
						Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總前帳:$"+TR10+sepa);
													sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總應收:$"+Math.round(TT10)+sepa);
						Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,總入金:$"+Math.round(TT30)+sepa);
													sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總票刷:"+Math.round(TM30)+sepa);
						Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,本未收:$"+Math.round(Profit)+sepa);
													sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總未收:$"+Math.round(Profits)+sepa);
						Loca=Loca+50;sPrintB.append("AZ,30,"+Loca+",1,2,0,0,本收支:$"+TTmacc+sepa);
													sPrintB.append("AZ,232,"+Loca+",1,2,0,0,總現存:$"+Math.round(TT30+TTmacc)+sepa);
													
						Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,2,0,0,--------------------------------------"+sepa);
						SQLiteDatabase db = Utilis.getDB(QRep_12.this);
						for (int ij=0;ij<mAdapter.getCount();ij++){
							RepData datas = (RepData) mAdapter.getItem(ij);
									Cursor cs=db.rawQuery("select CUSTNAME,MOBIL from qcust where CUSTNO='"+datas.iFormdate+"' and TR='20'", null);
								if (cs.getCount()>0 ){
									cs.moveToFirst();
									Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,門市:"+datas.iGoods+"/"+cs.getString(0)+" ("+cs.getString(1)+")"+sepa);
								}else {
									Loca=Loca+35;sPrintB.append("AZ,10,"+Loca+",1,1,0,0,門市:"+datas.iGoods+sepa);
								}
								cs.close();
							    int sep1= datas.iMoney.indexOf("收支:");
							    sPrintB.append("AZ,300,"+Loca+",1,1,0,0,"+(datas.iMoney.substring(sep1)).trim()+sepa);
							    
								Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iImpo+sepa);
								sPrintB.append("AZ,200,"+Loca+",1,1,0,0,"+datas.iName+sepa);
							    int sep= datas.iCountry.indexOf("卡:");
								Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iCountry.substring(0,sep)+sepa);
								sPrintB.append("AZ,200,"+Loca+",1,1,0,0,"+datas.iMoney.substring(0,sep1)+sepa);
								Loca=Loca+25;sPrintB.append("AZ,30,"+Loca+",1,1,0,0,"+datas.iCountry.substring(sep)+sepa);
								sPrintB.append("AZ,200,"+Loca+",1,1,0,0,"+datas.iCompany+sepa);
	
						}
							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+60;
							String lenS="0000"+(int)(Loca/7.2);
							sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
							sPrintB.append("E"+sepa);

					 		String batchFile=myImportPath+File.separator+"cwbuyer_barprint.txt";  //預設為分色尺寸
					        File myFile = new File(batchFile); //其目的是為了產生一個新檔案或資料夾
					        if (myFile.exists()){
					        	myFile.delete();
					        }
					        boolean Succed=false;
							BufferedWriter bw;
							try {
								bw = new BufferedWriter(new FileWriter(myFile));
				                 if (sPrintB.toString() !=null && sPrintB.toString().length()>0)
				                 { bw.write(sPrintB.toString()); }
				                 bw.close();
							} catch (IOException e1) {
								// TODO Auto-generated catch block
								e1.printStackTrace();
							}
							
							
							String address=null;
							int port=0;
							int success=1;
							   address = Utilis.getIni(QRep_12.this, "SYS","BAR_IP", 4);// 連線的ip
							   port =Utilis.toInt(Utilis.getIni(QRep_12.this, "SYS","BAR_IP", 5));// 連線的port
								 InetAddress serverAddr = null;
							        SocketAddress sc_add = null;
							        Socket socket = null;
				
										 try {
											 serverAddr = InetAddress.getByName(address);
											 sc_add= new InetSocketAddress(serverAddr,port);
												 socket = new Socket();
												 socket.connect(sc_add,2000);
												 DataOutputStream out = new DataOutputStream(socket.getOutputStream());
												 byte data[] = new String(sPrintB.toString().getBytes("UTF8")).getBytes("BIG5");
												 out.write(data, 0, data.length);
												 socket.close();
												 Toast.makeText(QRep_12.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
												 Succed=true;
										 } catch (UnknownHostException e) {
											 success=0;
										 } catch (SocketException e) {
											 success=0;
										 } catch(IOException e) {
											 success=0;
										 }
							}
						
					
					//無條件全印
					//只印欠款
					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_12.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_12.this,mStartDay, mEndDay, null, null);
					mAdapter.notifyDataSetChanged();
					break;

				}
			}
		}
	}
	

	Handler mHandlerQDR_30 = 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_5_mHandlerQC===", ""+Hresult);						
					if (Hresult.indexOf(";SSSS\r\n")>2){
						String Linea [] = Hresult.split(";SSSS\r\n");
						showList(Linea);
					}
				}
				showTitleA();
			}
		}
	};
	

	Handler mHandlerQDR_31 = 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_6_mHandlerQC===", ""+Hresult);						
					if (Hresult.indexOf(";SSSS\r\n")>2){
						String Linea [] = Hresult.split(";SSSS\r\n");
						if (Linea.length>1){
							String Lines[] =Linea[1].split(",");
							showList31(Lines[1],Linea);
						}
					}
				}
			}
		}
	};
	

	Handler mHandlerQDR_32 = 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_6_mHandlerQC===", ""+Hresult);						
					if (Hresult.indexOf(";SSSS\r\n")>2){
							String Linea [] = Hresult.split(";SSSS\r\n");
							if (Linea.length>1){
								String Lines[] =Linea[1].split(",");
								showList32(Linea);
							}
					}
				}
			}
		}
	};
	
	Handler mHandlerQDR_3A4= 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_6_mHandlerQC===", ""+Hresult);						
					if (Hresult.indexOf("\r\n")>2){
						RepData datas = (RepData) mAdapter.getItem(locations);											
						
						Hresult=	Hresult.substring(Hresult.indexOf("rep12;")+6);

						Intent intent = new Intent();

						intent.putExtra("SERCH",datas.iFormdate);
						intent.putExtra("QKIND",""+nKind);
						intent.putExtra("MODE",5);
						intent.putExtra("DEPTNO",datas.iFormdate);
						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_12.this, MkqrSt.class);
						startActivity(intent);
 						
					}
				}
			}
		}
	};
	
	//雲端版 將依FORMDATE,PS1,sum(BSUM) 取得後 填入PS1 分類欄
	private String makeSQLforPrinter(String Bg,String En, String mDept){

		StringBuffer mBuf = new StringBuffer();
		//0                ,1            ,2      ,3        ,4       ,5       ,6              ,7               ,8     ,9        ,10         ,11           ,12             ,13              ,14 
		//FORMDATE,DEPTNO,ATOT,BSUM,CASH,CARD,ORDCASH,ORDCARD,ATM,ASUM,TRCASH,FORMNO,TRUESUM,DISMONEY,MINTO
		mBuf.append("select a.FORMDATE,a.DEPTNO,sum(a.ATOT),sum(a.BSUM),sum(a.CASH),sum(a.CARD),sum(a.ORDCASH),sum(a.ORDCARD),sum(a.ATM),sum(a.ASUM),sum(a.TRCASH),count(a.FORMNO),sum(a.TURESUM),sum(a.DISMONEY),b.MINTO");
		mBuf.append(" from qhead as a left join qmacc as b on(a.DEPTNO=b.DEPTNO and a.FORMDATE=b.FORMDATE and QNOM='0000') ");
	    mBuf.append(" where  ((( a.FORMDATE >= '").append(Bg)
		.append("' and a.FORMDATE <= '").append(En)	.append("' ) and a.ISCONFIRM='Y' ) or ")
		.append(" (( a.FINEDATE<>'' and a.FINEDATE>='").append(Bg).append("' and a.FINEDATE <= '").append(En).append("' ) and a.ISCONFIRM='Y' )");
	    if (ORS!=2){
	    	mBuf.append(" or (( a.ORDDATE<>'' and a.ORDDATE>='").append(Bg).append("' and ORDDATE <= '").append(En).append("' ) and a.ISCHECK='Y' and a.ISCONFIRM='N' ))");
	    }else{
		    mBuf.append(")");
	    }
	    
	    mBuf.append(" and a.DEPTNO='").append(mDept).append("' and ");
   		mBuf.append(" a.TR<>'Y2' and ");

    	mBuf.append(SQLADD);
		mBuf.append(" group by a.DEPTNO,a.FORMDATE");

		return mBuf.toString();
	}
	
	// 搜尋日期 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_12.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_12.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_12.this, mStartDay, mEndDay, null, null);
	    		mAdapter.notifyDataSetChanged();        
	    		break;
	    	}
	    	case KeySet.SearchMode.SEASON:  //自定日期範圍
	    	{
	    		new AlertDialog.Builder(QRep_12.this).setTitle("銷貨單 搜尋(起始、結束日期)")
				.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_12.this, mStartDay, mEndDay, null, null);
			    		mAdapter.notifyDataSetChanged();        
		            }
		          }).show();
	    		break;
	    	}
	    	
        }
        setCondition();
    }

	/**
	 *  Menu 使用
	 */
	
	private static final int MENU_MAIN = Menu.FIRST;
	private static final int MENU_DETAIL = Menu.FIRST+1;
	private static final int MENU_S1S2 = Menu.FIRST+2;
	private static final int MENU_S1 = Menu.FIRST+3;
	private static final int MENU_S2 = Menu.FIRST+4;
	@Override
    public boolean onCreateOptionsMenu(Menu menu){
    	super.onCreateOptionsMenu(menu);
    	menu.add(0, MENU_MAIN, 0, "銷貨+員購");
    	menu.add(0, MENU_DETAIL, 1, "銷貨(不計員購)");
    	menu.add(0, MENU_S1S2, 2, "員購(不計銷貨)");
    	menu.add(0, MENU_S1, 3, "零售(不計員購)");
    	menu.add(0, MENU_S2, 4, "零售(含員購)");
    	return true;
    }
	
    @Override
	public boolean onOptionsItemSelected(MenuItem item) {			
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {
			case MENU_MAIN:
			{
				SQLADD="(a.QKIND ='30' OR a.QKIND ='31' OR a.QKIND ='40' OR a.QKIND ='41')";
				break;
			}
			case MENU_DETAIL:
			{
				SQLADD="(a.QKIND ='30' OR a.QKIND ='31')";
				break;
			}
			case MENU_S1S2:{
				SQLADD="(a.QKIND ='40' OR a.QKIND ='41')";
				break;
			}
			case MENU_S1:{
				SQLADD="a.TRADETYPE='5' and (a.QKIND ='30' OR a.QKIND ='31')";
				break;
			}
			case MENU_S2:{
				SQLADD="a.TRADETYPE='5' and (a.QKIND ='30' OR a.QKIND ='31' OR a.QKIND ='40' OR a.QKIND ='41')";
				break;
			}
					
		}
		if (Floor==0){
			setCondition();
			getGroupData(QRep_12.this,mStartDay, mEndDay, null, null);				
			mAdapter.notifyDataSetChanged();
		}else{
			Toast.makeText(QRep_12.this, "請返回第一層,才可以這些選項!!", Toast.LENGTH_LONG).show();
		}
		return true;
    }
    
    
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);
			
			String ppic=data.iPic;
			if (data.iPic!=null && data.iPic.length()>10 && data.iPic.indexOf("/cwbuyer")>0)
				ppic=data.iPic.replace(data.iPic.substring(0,data.iPic.indexOf("/cwbuyer")), myPath);  //圖片
			
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(ppic, 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;
			
		}
	}

}
