package com.cwbuyer.lib;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
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.content.Context;
import android.content.DialogInterface;
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.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Button;

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

@SuppressLint({ "InflateParams", "HandlerLeak" })
@SuppressWarnings("unused")

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
public class QHis extends Activity{
	
	private int mMode = KeySet.SearchMode.WEEK;
	private String mEndDay = null;
	private String mStartDay = null;
	private int isGoodsUser=0; //0User1Goods2Goods&User
	
	private int mYear1 = 0;
	private int mYear2 = 0;
	private int mMonth1 = 0;
	private int mMonth2 = 0;
	private int mDay1 = 0;
	private int mDay2 = 0;

	private int PSWD=Utilis.toInt(Utilis.getIni(this,"SYS","DEPT",5)); //0OK 1密碼不符
	String mCloud=Utilis.getIni(this,"SYS","DEPT_SEND",4);
	String clouds="http://"+Utilis.getIni(this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(this, "SYS", "IMPORT", 2)+File.separator;
	String uriAPI1=clouds+"qrephisn.php";
	protected static final int REFRESH_DATA = 0x00000001;

	private ExpandItemAdapter mExpandAdapter = null;

//ACTION 預設模式 POS定義為 銷貨單;預購單;暫存單;單頭+單身	
	private String[] tradeStr =Utilis.getIni(this,"SYS","TRADENAME",9).split("!&!");
	private String[] SQLSTR={
		"",
		" ISCONFIRM='Y' and ISCHECK='N' and (QKIND='30' or QKIND='31') ",
		" ISCONFIRM='Y' and ISCHECK='N' and (QKIND='20' or QKIND='21') ",
		" ISCONFIRM='Y' and ISCHECK='N' and (QKIND='40' or QKIND='41') ",
		" ISCONFIRM='Y' and ISCHECK='N' and QKIND='10' ",
		" (ISCONFIRM='N' or ISCONFIRM='O') and ISCHECK='Y' and (QKIND='30' or QKIND='31') ",
		" ISCONFIRM='R' and ISCHECK='Y' and (QKIND='30' or QKIND='31') "
		};
	//Top1 銷貨2出貨3員購4進貨5預購6留貨
	private String[] Qkinds={"","sum(UNIT30)","sum(UNIT20)","sum(UNIT40)","sum(UNIT10)","sum(UNIT30)","sum(UNIT30)"};
	private String[] Qkind={"","UNIT30","UNIT20","UNIT40","UNIT10","UNIT30","UNIT30"};
	private String[] Trade={"","銷貨","出貨","員購","進貨","預購","留貨"};
	private String SqlUserGoods="";
	
	private LinkedList<GroupData> mGroupList = new LinkedList<GroupData>();
	
	private int nKind=0;
	private int nMode=0;
	private DatePicker dp1;
	private DatePicker dp2;
	
	private String mUser=null;
	private String mGoods=null;
	
	private ExpandableListView mExpandListView = null;
	
	private class GroupData{ //第一層版面
		private String strTextG1;  // 左上
		private String strPic;  // 左中
		private String strText1; // 左中 會員編號/名稱 USER/USERNAME
		private String strText2; // 右上  		ASUM/BSUM
		private String strMoney; // 右中 		CASH/CARD
		private String strOriMoney;  //右下ORDCASH/ORDCARD
		private String strTextG2;  // 左下		
		private String SEARCH; //KEY 
	}
	
	private class PxData{ //第二層版面
		private String iPic;  
		private String iGoods; 
		private String iImpo; 
		private String iName; 
		private String iMoney;
		private String iCountry;
		private String iNumber;
		private String iCompany;
		private String iFormdate;
		
	}
	
//@@日後需補充用ITEM檢測HEAD是否漏掉的清單,並自動修補	

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qhis);
        
        //@@應增加營業時間的判斷而視為當日或前一天
        
        nKind =getIntent().getIntExtra("QHis_kind", PItemKind.TR30); //
        nMode =getIntent().getIntExtra("QHis_mode", 0); //1銷貨2出貨3員購4進貨5預購6留貨
        mUser =getIntent().getStringExtra("QHis_User"); //預設單一USER
        mGoods =getIntent().getStringExtra("QHis_Goods"); //預設商品 但還要參 nMode
        
        if (nKind==10) nMode=4; else if (nKind==20 || nKind==21 ) nMode=2; else if (nKind>=40) nMode=3; 
        
        if (mGoods.length()>0 && mGoods.indexOf("-")>0)
        	SqlUserGoods=" GOODSNOS='"+mGoods+"' and ";
        else if (mGoods.length()>0) SqlUserGoods=" GOODSNO='"+mGoods+"' and ";
        
        if (mUser.length()>0) SqlUserGoods+=" USER='"+mUser+"' and ";
        
        if (mGoods.length()>0 && mUser.length()>0) 
        	isGoodsUser=2;
        else if (mGoods.length()>0)
        	isGoodsUser=1;
        
        
        //理論上一樣的組合
        //第二層 只取SQLSTR 且 USER GOODSNO 或 GOODSNOS 取自 Group User & Goodsno 
        //在Cloud 需一樣的條件
        //組合條件順序 需 SqlUserGoods+SQLSTR
        //5預購6留貨 不限日期條件 全抓
        //由自動判斷 決定 isGoodsUser=0USer1Goods2Goods&User 
		((Button)findViewById(R.id.b_til1)).setText(getGoodsUserTitle(mGoods,mUser));
        


		switch (nMode){
			case 1:
				resetButton(R.id.btn_sort_top1);
				break;
			case 2:
				resetButton(R.id.btn_sort_top2);
				break;
			case 3:
				resetButton(R.id.btn_sort_top3);
				break;
			case 4:
				resetButton(R.id.btn_sort_top4);
				break;
			case 5:
				resetButton(R.id.btn_sort_top5);
				break;
			case 6:
				resetButton(R.id.btn_sort_top6);
				break;
		}
        
        mExpandListView = (ExpandableListView)findViewById(R.id.list_item_expandh);
        mExpandAdapter = new ExpandItemAdapter(this);
        
        mExpandListView.setAdapter(mExpandAdapter);
        mExpandListView.setOnChildClickListener(mChildClcik);
	
		((Button)findViewById(R.id.btn_sort_top1)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_sort_top2)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_sort_top3)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_sort_top4)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_sort_top5)).setOnClickListener(new MainClick());
		((Button)findViewById(R.id.btn_sort_top6)).setOnClickListener(new MainClick());
		
		
        ((Button)findViewById(R.id.b_til2)).setOnClickListener(new MainClick());		
        ((Button)findViewById(R.id.b_til3)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn00)).setOnClickListener(new MainClick());        
        ((Button)findViewById(R.id.btn_btn1h)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn2h)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_btn3h)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_exith)).setOnClickListener(new MainClick());
		
        chkMode();

		mExpandListView.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {
				// TODO Auto-generated method stub
				Utilis.runVibrate(QHis.this);
				//Toast.makeText(QPosff.this, "輕按ITEM"+position, Toast.LENGTH_SHORT).show();
				//無法偵測事件				
			}
        });
		
//		mExpandListView.setOnChildClickListener(mChildClcik);
//		mExpandAdapter.notifyDataSetChanged();
		
    }
	
	public void onResume(){
		super.onResume();
	}
	
	private void setCondition(){
		
		//台頭:CWBuyer銷售王+[進貨]
		//(APos.java)[新增][查詢][編輯] 帶過去的引數
		//現階段可分為:[交易中][統計中]
		
    	switch(mMode){ 
    	
			case KeySet.SearchMode.DAY:
			{
				((Button)findViewById(R.id.b_til2)).setText(mStartDay);
				((Button)findViewById(R.id.b_til3)).setText(mEndDay);
    			setTitle(getString(R.string.app_name)+":[依每日]");
				break;
			}
			case KeySet.SearchMode.WEEK:
			{
				((Button)findViewById(R.id.b_til2)).setText(mStartDay);
				((Button)findViewById(R.id.b_til3)).setText(mEndDay);
    			setTitle(getString(R.string.app_name)+":[依每週]");
				break;
			}
			case KeySet.SearchMode.MONTH:
			{
				((Button)findViewById(R.id.b_til2)).setText(mStartDay);
				((Button)findViewById(R.id.b_til3)).setText(mEndDay);
				setTitle(getString(R.string.app_name)+":[依每月]");
				break;
			}
			case KeySet.SearchMode.SEASON:
			{
				((Button)findViewById(R.id.b_til2)).setText(mStartDay);
				((Button)findViewById(R.id.b_til3)).setText(mEndDay);
				setTitle(getString(R.string.app_name)+":[自訂]");
				break;
			}
    	}
	}
	

	
	private void getGroupData(Context context, String startDay, String endDay, String condition, String conditionValue) {
		
		if(startDay != null && startDay.length() > 0)	startDay = startDay.replace("/", "-");
		if(endDay != null && endDay.length() > 0) endDay = endDay.replace("/", "-");
		
		StringBuffer bufCategory = new StringBuffer();
		//第一層大概的模型 (會有價別的問題)(單別)
		
		//nMode56 不要日期範圍
		if (mGroupList != null)	mGroupList.clear();
		
		if (isGoodsUser!=0)  //依商品,所有USER 依QKIND交易
			bufCategory.append("select USER,USERNAME,COLORS,SIZES,PIC,");
		else
			bufCategory.append("select GOODSNO,GOODSNAME,COLORS,SIZES,PIC,");
			
		bufCategory.append(Qkinds[nMode]+",sum(SUBPRICE),avg(UNITPRICE),max(FORMDATE),ISCONFIRM,ISCHECK from qitems where ");
		bufCategory.append(SqlUserGoods+SQLSTR[nMode]);
		//USER && GOODSNO
		
		if (nMode<5) bufCategory.append(" and FORMDATE >='").append(startDay).append("' and FORMDATE <='").append(endDay).append("'");
			
		if (isGoodsUser!=0) bufCategory.append(" group by USER,USERNAME,COLORS,SIZES,PIC"); else bufCategory.append(" group by GOODSNO,GOODSNAME,COLORS,SIZES,PIC");
		
		//Toast.makeText(QHis.this, "Group_SQL="+bufCategory.toString(), Toast.LENGTH_SHORT).show();
		
		if  (Utilis.haveInternet(context) && Utilis.toInt(Utilis.getIni(context, "SYS", "IMPORT", 3))==1 && Utilis.toInt(mCloud)>0){
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
/* call CLOUD
$nMode=@$_REQUEST['MODE']; //0依GOODSNO 1依USER
$isGoodsUser=@$_REQUEST['GOODSUSER']; //交易單別代號 10.20.20.30.31.40.41
$iUSER=@$_REQUEST['USER']; //交易特定對象
$iGoods=@$_REQUEST['GOODSNO']; //改為主貨 來源編號
$startDay=@$_REQUEST['STARTDAY']; //起始日期
$endDay=@$_REQUEST['ENDDAY']; //截止日期
$query_str=@$_REQUEST['SQLSTR']; //第二層查詢條件
$query_kind=@$_REQUEST['SQLKIND']; //第二層查詢條件
$query_rsH=@$_REQUEST['SQLADD']; //查詢條件
 */
			
				bfstr.append(Utilis.getIni(context, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");
				bfstr.append(""+nMode).append(";");
				bfstrF.append("MODE").append(";");
				bfstr.append(isGoodsUser).append(";");
				bfstrF.append("GOODSUSER").append(";");
				bfstr.append(mUser).append(";");
				bfstrF.append("USER").append(";");
				bfstr.append(mGoods).append(";");
				bfstrF.append("GOODSNO").append(";");
				bfstr.append(startDay).append(";");
				bfstrF.append("STARTDAY").append(";");
				bfstr.append(endDay).append(";");
				bfstrF.append("ENDDAY").append(";");
				bfstr.append(SqlUserGoods+SQLSTR[nMode]).append(";");
				bfstrF.append("SQLSTR").append(";");
				bfstr.append(Qkind[nMode]).append(";");
				bfstrF.append("SQLKIND").append(";");
				bfstr.append(bufCategory.toString());
				bfstrF.append("SQLADD");  
				
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      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);
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									// 取出回應字串
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									mHandlerQhis.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
								}
								
							} catch (Exception e)
							{
								e.printStackTrace();
							}

			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			          }
			        }
			      }.start(); 

		}else{
			LinkedList<GroupData> groups = new LinkedList<GroupData>();
			LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
			SQLiteDatabase db = Utilis.getDB(context);
			try {
			  Cursor cursorGroup = null;
			  Cursor cursor = null;
			
			  cursorGroup = db.rawQuery(bufCategory.toString(), null);
			  if (cursorGroup != null) {
				if (cursorGroup.getCount() > 0) {
					cursorGroup.moveToFirst();
					
					//if (isGoodsUser==0) select USER,USERNAME,COLORS,SIZES,PIC,
					//else select GOODSNO,GOODSNAME,COLORS,SIZES,PIC,
					
					for (int i = 0; i < cursorGroup.getCount(); i++) {
						GroupData data = new GroupData();
						data.SEARCH = cursorGroup.getString(0);  //GOODSNO OR USER
						Cursor csC=null;
						if (nMode!=4){
							csC=db.rawQuery("select MOBIL,DISCOUNT,TRADETYPE,PIC from qcust where CUSTNO='"+cursorGroup.getString(0)+"'",null);
						}else{
							csC=db.rawQuery("select MOBIL,DISCOUNT,TRADETYPE,PIC from qfact where FACTNO='"+cursorGroup.getString(0)+"'",null);
						}
						if (csC.getCount()>0) {  //found
							csC.moveToFirst();
							data.strPic=csC.getString(3);  //USER圖片
							data.strText1 = cursorGroup.getString(1)+"("+csC.getString(1)+")";  //USERNAME
							data.strTextG2 = csC.getString(0)+"/"+tradeStr[csC.getInt(2)];  //MOBIL
						}else{	
							data.strPic=cursorGroup.getString(4);  //商品圖片
							data.strText1 = cursorGroup.getString(1);  //USERNAME
							data.strTextG2 = cursorGroup.getString(2)+"/"+cursorGroup.getString(3);  //多色尺寸
						}
						data.strText2 = Trade[nMode]+":"+cursorGroup.getDouble(5)+"件";
							
							data.strTextG1 = cursorGroup.getString(0)+"/"+cursorGroup.getString(8); //最近交易日
								//廠商進貨與出貨與銷貨都有其欄位顯示需求
							data.strMoney ="均價:"+Math.round(cursorGroup.getDouble(7));
							data.strOriMoney="合計:"+Math.round(cursorGroup.getDouble(6));
						csC.close();
						groups.add(data);
						cursorGroup.moveToNext();
					}
				}
				
				if (groups.size() > 0) {  //製作第二層因為進10出20銷30櫃40 件數 金額 預購 
					StringBuffer bufList = new StringBuffer();
					for (int i = 0; i < groups.size(); i++) {
						GroupData dataG=groups.get(i);
						if(bufList.length() > 0) bufList.delete(0, bufList.toString().length());

						bufList.append("select FORMDATE,GOODSNOS,UNITPRICE,PIC,DISCOUNT,UNIT1,")
						.append(Qkind[nMode]+",SUBPRICE,FORMNO,ISCONFIRM,ISCHECK")
						.append(" from qitems WHERE ");
						bufList.append(SqlUserGoods+SQLSTR[nMode]);
						if (isGoodsUser==0) bufList.append(" and GOODSNO='"+dataG.SEARCH+"'");
						else if (isGoodsUser==1) bufList.append(" and USER='"+dataG.SEARCH+"'");
						if (nMode<5) bufList.append(" and FORMDATE >='").append(startDay).append("' and FORMDATE <='").append(endDay).append("'");
						
						//Toast.makeText(QHis.this, "Child_SQL="+bufList.toString(), Toast.LENGTH_SHORT).show();		
						
						cursor = db.rawQuery(bufList.toString(), null);
						List<PxData> listData = new ArrayList<PxData>();							
						if (cursor != null) {
							if (cursor.getCount() > 0) {
								cursor.moveToFirst();
								for (int k = 0; k < cursor.getCount(); k++) {
									PxData data=new PxData();
									data.iFormdate = groups.get(i).SEARCH;
									data.iGoods = cursor.getString(1)+"("+cursor.getString(5)+")";  //明細貨號(色名)
									data.iName = cursor.getString(0);  //日期
									data.iCountry =cursor.getString(8);  //單號
									data.iPic=cursor.getString(3);
									data.iImpo = Trade[nMode]+":"+cursor.getString(6)+"件";
									data.iNumber = cursor.getString(4);
									data.iMoney = "單價:"+cursor.getString(2);
									data.iCompany ="小計:"+ cursor.getString(7);
									listData.add(data);
									cursor.moveToNext();
								}
								childs.add(listData);
							}
							cursor.close();
							cursorGroup.close();
						}
					}
				}
			  }
			
			} catch (Exception e) {
				e.printStackTrace();
			}
			mExpandAdapter.setData(groups, childs);
			mExpandAdapter.notifyDataSetChanged();
			db.close();
			db = null;
		}
		
	}
		
	ExpandChildClick mChildClcik = new ExpandChildClick();
	
	private class ExpandChildClick implements OnChildClickListener{
		@Override
		public boolean onChildClick(ExpandableListView parent, View v,
				final int groupPosition,final int childPosition, long id) {
			Utilis.runVibrate(QHis.this);
			return false;
		}
	}

	private class ExpandItemAdapter extends BaseExpandableListAdapter{
		private Context context;

		LinkedList<GroupData> groups = new LinkedList<GroupData>();
		LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();

		/*
		* 構造函數:
		* 參數1:context物件
		* 參數2:一級清單資料來源
		* 參數3:二級清單資料來源
		*/
		
		public ExpandItemAdapter(Context context)
		{
//			this.groups = groups;
//			this.childs = childs;
			this.context = context;

		}
		
		public void setData(LinkedList<GroupData> groups, LinkedList<List<PxData>> childs){
			if(this.groups != null){
				this.groups.clear();
			}
			if(this.childs != null){
				this.childs.clear();
			}
			this.groups = groups;
			this.childs = childs;
		}
		
//@@
		public PxData getData(int groupPosition, int childPosition){
			return childs.get(groupPosition).get(childPosition);
		}

		public Object getChild(int groupPosition, int childPosition)
		{
			return childs.get(groupPosition).get(childPosition);
		}

		public long getChildId(int groupPosition, int childPosition)
		{
		return childPosition;
		}
		
		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textName;
			TextView textMoney;
			TextView textCountry;
			TextView textNumber;
			TextView textCompany;
			TextView textGoodsNo;
			TextView textImpo;
		}
		
		/* class GroupViewHolder */
		private class GroupViewHolder {
			ImageView imageIcon;
			TextView text1;
			TextView text2;
			TextView textMoney;
			TextView textOriMoney;
			TextView textG1;
			TextView textG2;
		}

		//獲取二級清單的View物件
		public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
		ViewGroup parent)
		{
		PxData data = childs.get(groupPosition).get(childPosition);
		//
		LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			ViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.list_qhis, 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.textNumber = (TextView) convertView.findViewById(R.id.text_pnumber);
				holder.textMoney = (TextView) convertView.findViewById(R.id.text_pmoney);
				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");
			
			holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(data.iPic, 80, 80));
			holder.textName.setText(data.iName);
			holder.textGoodsNo.setText(data.iGoods);
			holder.textImpo.setText(data.iImpo);
			if((nMode==2 || nMode==4 ) && PSWD==1){
			holder.textMoney.setText("xxxxxx");
			holder.textCompany.setText("xxxxxxxx");
			}else{
				holder.textMoney.setText(data.iMoney);
				holder.textCompany.setText(data.iCompany);
			}
			holder.textCountry.setText(data.iCountry);
			holder.textNumber.setText(data.iNumber);
			return convertView;
		}

		public int getChildrenCount(int groupPosition)
		{
		return childs.get(groupPosition).size();
		}

		public Object getGroup(int groupPosition)
		{
		return groups.get(groupPosition);
		}

		public int getGroupCount()
		{
		return groups.size();
		}

		public long getGroupId(int groupPosition)
		{
		return groupPosition;
		}

		//獲取一級清單View物件
		public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent)
		{
//			String text = groups.get(groupPosition).get("group");
			GroupData data = groups.get(groupPosition);
			
			LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			GroupViewHolder holder;
			if (convertView == null) {
				convertView = layoutInflater.inflate(R.layout.plist_qhish, null);
				holder = new GroupViewHolder();
				holder.imageIcon = (ImageView)convertView.findViewById(R.id.img_icon);
				holder.text1 = (TextView) convertView.findViewById(R.id.text1);
				holder.text2 = (TextView) convertView.findViewById(R.id.text2);
				holder.textMoney = (TextView)convertView.findViewById(R.id.textMoney);
				holder.textOriMoney = (TextView)convertView.findViewById(R.id.textOriMoney);
				holder.textG1 = (TextView) convertView.findViewById(R.id.textg1);
				holder.textG2 = (TextView) convertView.findViewById(R.id.textg2);
				convertView.setTag(holder);
				
			} else {
				holder = (GroupViewHolder) convertView.getTag();
			}

			if(mMode==4){ //不顯示第一層的圖檔
				holder.imageIcon.setVisibility(View.GONE);
			}else{
				holder.imageIcon.setVisibility(View.VISIBLE);
				try{
					if(data.strPic != null && data.strPic.length() > 0){
						holder.imageIcon.setImageDrawable(Utilis.getResourceImage(QHis.this, data.strPic));
					}else{
						holder.imageIcon.setImageResource(R.drawable.icon_store);
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			holder.text1.setText(data.strText1);
			holder.text2.setText(data.strText2);
			if((nMode==2 || nMode==4 ) && PSWD==1){
				holder.textOriMoney.setText("xxxxxx");
				holder.textMoney.setText("xxxxxx");
			}else{
				holder.textOriMoney.setText(data.strOriMoney);
				holder.textMoney.setText(data.strMoney);
			}
			holder.textG1.setText(data.strTextG1);
			holder.textG2.setText(data.strTextG2);
			return convertView;
		}

		public boolean hasStableIds()
		{
		return false;
		}

		public boolean isChildSelectable(int groupPosition, int childPosition)
		{
		return true;
		}
	}

	private void resetButton(int id){
		((Button)findViewById(R.id.btn_sort_top1)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top2)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top3)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top4)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top5)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(R.id.btn_sort_top6)).setBackgroundResource(R.drawable.keypad_green);
        ((Button)findViewById(id)).setBackgroundResource(R.drawable.keypad_yellow);
        if (nMode==5 || nMode==6){
        	((Button)findViewById(R.id.b_til2)).setVisibility(View.INVISIBLE);        	
        	((Button)findViewById(R.id.b_til3)).setVisibility(View.INVISIBLE);        	
            ((Button)findViewById(R.id.btn_btn00)).setVisibility(View.INVISIBLE);        
            ((Button)findViewById(R.id.btn_btn1h)).setVisibility(View.INVISIBLE);
            ((Button)findViewById(R.id.btn_btn2h)).setVisibility(View.INVISIBLE);
            ((Button)findViewById(R.id.btn_btn3h)).setVisibility(View.INVISIBLE);
        }else{
        	((Button)findViewById(R.id.b_til2)).setVisibility(View.VISIBLE);        	
        	((Button)findViewById(R.id.b_til3)).setVisibility(View.VISIBLE);        	
            ((Button)findViewById(R.id.btn_btn00)).setVisibility(View.VISIBLE);        
            ((Button)findViewById(R.id.btn_btn1h)).setVisibility(View.VISIBLE);
            ((Button)findViewById(R.id.btn_btn2h)).setVisibility(View.VISIBLE);
            ((Button)findViewById(R.id.btn_btn3h)).setVisibility(View.VISIBLE);
        }
	}

	// 搜尋日期 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 String getGoodsUserTitle(String Goods,String User){
		SQLiteDatabase db = Utilis.getDB(this);
		Cursor cs = null;
		String listTitle="";
		if (Goods.length()>0){//一律 主貨號
			String GoodsStr="select distinct GOODSNO,GOODSNAME,COLOR,SIZE,PIC from qdetail where ";
			if (Goods.indexOf("-")>0) Goods=Goods.substring(0,Goods.indexOf("-"));
			cs = db.rawQuery(GoodsStr+" GOODSNO='"+Goods+"' order by MID desc limit 1", null);
			if (cs.getCount()>0){
				cs.moveToFirst();
				((ImageView)findViewById(R.id.i_cust)).setImageBitmap(Utilis.getLimitBitmap(cs.getString(4), 80, 80));
				listTitle=cs.getString(0)+"/"+cs.getString(1)+"追蹤("+cs.getString(2)+"/"+cs.getString(3)+")";
			}
		}else if (User.length()>0 && mMode!=4 && Goods.length()<=0){
			cs = db.rawQuery("select CUSTNO,CUSTNAME,EMAIL,MOBIL,PIC from qcust where CUSTNO='"+mUser+"'", null);				
			if (cs.getCount()>0){
				cs.moveToFirst();
				((ImageView)findViewById(R.id.i_cust)).setImageBitmap(Utilis.getLimitBitmap(cs.getString(4), 80, 80));
				listTitle=cs.getString(0)+"/"+cs.getString(1)+"追蹤("+cs.getString(2)+"/"+cs.getString(3)+")";
			}
		}
		db.close();
		cs.close();
    	
    	return listTitle;
    }
	
    private void chkMode(){        
        switch(mMode){ //剛進入主程式的狀態,初始的模式
        
	    	case KeySet.SearchMode.DAY:
	    	{
	    		String day = DateUtil.getCurrentDate();
	    		mStartDay = day;
	    		mEndDay = day;
	    		((Button)findViewById(R.id.b_til3)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.b_til3)).setText("下一日");
	    		((Button)findViewById(R.id.b_til2)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.b_til2)).setText("上一日");
	        	getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
	            mExpandAdapter.notifyDataSetChanged();        
	            setCondition();
	    		
	    		break;
	    	}
	    	case KeySet.SearchMode.WEEK:
	    	{
	    		String day = Utilis.getWeekDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		((Button)findViewById(R.id.b_til3)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.b_til3)).setText("下一週");
	    		((Button)findViewById(R.id.b_til2)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.b_til2)).setText("上一週");
	        	getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
	            mExpandAdapter.notifyDataSetChanged();        
	            setCondition();
	    		
	    		break;
	    	}
	    	case KeySet.SearchMode.MONTH:
	    	{
	    		String day = Utilis.getMonthDate();
				String[] days = day.split("~");
	    		mStartDay = days[0];
	    		mEndDay = days[1];
	    		((Button)findViewById(R.id.b_til3)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.b_til3)).setText("下個月");
	    		((Button)findViewById(R.id.b_til2)).setVisibility(View.VISIBLE);
	    		((Button)findViewById(R.id.b_til2)).setText("上個月");
	        	getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
	            mExpandAdapter.notifyDataSetChanged();        
	            setCondition();
	    		break;
	    	}
	    	case KeySet.SearchMode.SEASON:  //自定日期範圍
	    	{

	    		new AlertDialog.Builder(QHis.this).setTitle("銷貨單 搜尋(起始、結束日期)")
				.setView(makeDateDialog())
				.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;
		            	getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		                mExpandAdapter.notifyDataSetChanged();        
		                setCondition();
		            }
		          }).setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            }
		          }).show();
	    		break;
	    	}
        }
        
    	//getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
        //mExpandAdapter.notifyDataSetChanged();        
        //setCondition();
    }

	
	private class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QHis.this);
			switch (id) {
				case  R.id.btn_sort_top1:
				{
					nMode=1;
					resetButton(R.id.btn_sort_top1);
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case  R.id.btn_sort_top2:
				{
					nMode=2;
					resetButton(R.id.btn_sort_top2);
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case  R.id.btn_sort_top3:
				{
					nMode=3;
					resetButton(R.id.btn_sort_top3);					
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case  R.id.btn_sort_top4:
				{
					nMode=4;
					resetButton(R.id.btn_sort_top4);
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case  R.id.btn_sort_top5:
				{
					nMode=5;
					resetButton(R.id.btn_sort_top5);
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case  R.id.btn_sort_top6:
				{
					nMode=6;
					resetButton(R.id.btn_sort_top6);
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case R.id.b_til2:  //當按了上一??
				{
					switch(mMode){
						case KeySet.SearchMode.MONTH:  //就是31筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
				    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
				    		mExpandAdapter.notifyDataSetChanged();        
				    		setCondition();
			    			break;
			    		}
						case KeySet.SearchMode.WEEK:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -7);
							mEndDay = DateUtil.addDate(mEndDay, -7);
				    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
				    		mExpandAdapter.notifyDataSetChanged();        
				    		setCondition();
			    			break;
			    		}
						case KeySet.SearchMode.DAY:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, -1);
							mEndDay = DateUtil.addDate(mEndDay, -1);
				    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
				    		mExpandAdapter.notifyDataSetChanged();        
				    		setCondition();
			    			break;
			    		}
					}
					
					break;
				}
				case R.id.b_til3:
				{
					switch(mMode){
			    		case KeySet.SearchMode.MONTH: //就是日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addMonth(mStartDay, 1,true);
							mEndDay = DateUtil.addMonth(mStartDay, 1);
				    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
				    		mExpandAdapter.notifyDataSetChanged();        
				    		setCondition();
			    			break;
			    		}
			    		case KeySet.SearchMode.WEEK:
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 7);
							mEndDay = DateUtil.addDate(mEndDay, 7);
				    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
				    		mExpandAdapter.notifyDataSetChanged();        
				    		setCondition();
			    			break;
			    		}
						case KeySet.SearchMode.DAY:  //就是7筆日結單(日期+單頭)
			    		{
			    			mStartDay = DateUtil.addDate(mStartDay, 1);
							mEndDay = DateUtil.addDate(mEndDay, 1);
				    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
				    		mExpandAdapter.notifyDataSetChanged();        
				    		setCondition();
			    			break;
			    		}
			    		
					}
					
					break;
				}
				
				case R.id.btn_exith:
				{
					finish();
					break;
				}
				case R.id.btn_btn1h:
				{
					mMode=KeySet.SearchMode.WEEK;
					chkMode();
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case R.id.btn_btn2h:
				{
					mMode=KeySet.SearchMode.MONTH;
					chkMode();
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case R.id.btn_btn00:
				{
					mMode=KeySet.SearchMode.DAY;
					chkMode();
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
				case R.id.btn_btn3h:
				{
					mMode=KeySet.SearchMode.SEASON;
					chkMode();
		    		getGroupData(QHis.this, mStartDay, mEndDay, SqlUserGoods+SQLSTR[nMode], null);
		    		mExpandAdapter.notifyDataSetChanged();        
		    		setCondition();
					break;
				}
			}
		}
	}

	Handler mHandlerQhis = 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_His",Hresult );
					LinkedList<GroupData> groups = new LinkedList<GroupData>();
					LinkedList<List<PxData>> childs = new LinkedList<List<PxData>>();
					if (Hresult.indexOf("HHHH\r\n")>2){
						SQLiteDatabase db = Utilis.getDB(QHis.this);
						Hresult=	Hresult.substring(Hresult.indexOf("rep03;")+6);
						String LineH [] = Hresult.substring(0, Hresult.length()-6).split(";HHHH\r\n");

						
					for (int xx=0;xx<LineH.length;xx++){
							String LinesH[] =LineH[xx].substring(0, LineH[xx].length()-6).split(";SSSS\r\n");
							
							GroupData datah = new GroupData();

							String Lineshh[] =LinesH[0].split(";");
							
							datah.SEARCH = Lineshh[0];
								Cursor csC=null;
								if (nMode!=4){
									csC=db.rawQuery("select MOBIL,DISCOUNT,TRADETYPE,PIC from qcust where CUSTNO='"+Lineshh[0]+"'",null);
								}else{
									csC=db.rawQuery("select MOBIL,DISCOUNT,TRADETYPE,PIC from qfact where FACTNO='"+Lineshh[0]+"'",null);
								}
								if (csC.getCount()>0) {  //found
									csC.moveToFirst();
									datah.strPic=csC.getString(3);  //USER圖片
									datah.strText1 =Lineshh[1]+"("+csC.getString(1)+")";  //USERNAME
									datah.strTextG2 = csC.getString(0)+"/"+tradeStr[csC.getInt(2)];  //MOBIL
								}else{	
									datah.strPic=Lineshh[4];  //商品圖片
									datah.strText1 = Lineshh[1];  //USERNAME
									datah.strTextG2 = Lineshh[2]+"/"+Lineshh[3];  //多色尺寸
								}
								if ((Lineshh[9]!=null && Lineshh[9].equalsIgnoreCase("O")) || (Lineshh[9].equalsIgnoreCase("N") && Lineshh[10].equalsIgnoreCase("Y")))
									datah.strText2 = "預購:"+Lineshh[5]+"件";
								else if (Lineshh[9]!=null && Lineshh[9].equalsIgnoreCase("Y"))
									datah.strText2 = "交易:"+Lineshh[5]+"件";
								else
									datah.strText2 = "保留:"+Lineshh[5]+"件";
								
								datah.strTextG1 = Lineshh[0]+"/"+Lineshh[8]; //最近交易日
									//廠商進貨與出貨與銷貨都有其欄位顯示需求
								datah.strMoney ="均價:"+Math.round(Utilis.toDouble(Lineshh[7]));
								datah.strOriMoney="合計:"+Math.round(Utilis.toDouble(Lineshh[6]));
								datah.strText2 = Trade[nMode]+":"+Lineshh[5]+"件";
								
									//廠商進貨與出貨與銷貨都有其欄位顯示需求
								
							csC.close();
							
							groups.add(datah);
							
							//Childs
							List<PxData> listData = new ArrayList<PxData>();
							
							for (int yy=1;yy<LinesH.length;yy++){
								String Linesii[] =LinesH[yy].split(";");

								PxData data=new PxData();
								data.iFormdate = Lineshh[0];
								data.iGoods = Linesii[1]+"("+Linesii[5]+")";  //明細貨號(色名)
								data.iName = Linesii[0];  //日期
								data.iCountry =Linesii[8];  //單號
								data.iPic=Linesii[3];
								data.iImpo = Trade[nMode]+":"+Linesii[6]+"件";
								data.iNumber = Linesii[4];
								data.iMoney = "單價:"+Linesii[2];
								data.iCompany ="小計:"+ Linesii[7];
								listData.add(data);
							}
							childs.add(listData);
							
					}
							
						db.close();
					}
					mExpandAdapter.setData(groups, childs);
					mExpandAdapter.notifyDataSetChanged();
				}
			}
		}
	};
	
}
