package com.cwbuyer.lib;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
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.ProgressDialog;
import android.content.Context;
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.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.pwbuyer.main.R;

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
@SuppressLint({ "UseSparseArrays", "HandlerLeak", "InflateParams" })
@SuppressWarnings("unused")
public class QRep_08 extends Activity{
	
	ReportAdapter mAdapter = null;
	TextView mTextDuration = null;
	int of_line=Utilis.toInt(Utilis.getIni(this, "SYS", "IMPORT", 3));
	String Mknd []={"","廠進","出貨","銷貨","員購"};	
	String clouds="http://"+Utilis.getIni(this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(this, "SYS", "IMPORT", 2)+File.separator;
	String uriAPI1=clouds+"qrep08_1.php";
   	String bankn=Utilis.getIni(this,"SYS","DEPT",1)+Utilis.getIni(this,"SYS","DEPT",2);
	public ProgressDialog myDialog = null;  	

	//發展為長按而啟動的功能
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	protected static final int REFRESH_DATA = 0x00000001;
	
	int nKind=30;
	DatePicker dp1;
	DatePicker dp2;
	
   	String btns=null;
   	String[] bttns;
	
	ListView mListView = null;
	ExpandableListView mExpandListView = null;
	
//For  Table
	int Wheight;
	int Wwidth;
	int tableHeight=30;
	int tabless=6;

	HashMap<Integer,Integer> mCountRow = new HashMap<Integer,Integer>(); // 顏色行資料
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 尺寸欄資料
	

	public class RepData{ 
		public String iPic;  
		public String iTopLeft; 		//日期/單號
		public String iTopRight; 	//應收/現金
		public String iMLeft;			//會員/名稱 
		public String iMRight;		//票刷/ATM
		public String iDLeft;			//經手/異動
		public String iDMiddle;		//門市/單別
		public String iDRight;		//時間/件數
		public String iFormdate;	//單號	
		public String iUnit2;
		public int iSort;
		
	}

	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrep08);
        mTextDuration = (TextView)findViewById(R.id.text_duration);

        ((Button)findViewById(R.id.btn_exit)).setOnClickListener(new MainClick());		//離開
        ((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);

        mListView = (ListView)findViewById(R.id.list_item);
        mAdapter = new ReportAdapter(this);
        mListView.setAdapter(mAdapter);
        
        if (Utilis.haveInternet(this) && of_line==1){
			StringBuffer bfstr = new StringBuffer();
			StringBuffer bfstrF = new StringBuffer();
			
				bfstr.append(Utilis.getIni(QRep_08.this, "SYS", "IMPORT", 2)).append(";");
				bfstrF.append("UID").append(";");

				//$qdept=@$_REQUEST['QDEPT'];  	//AA1,A11
				//$qyears=@$_REQUEST['QYEARS']; 	//20123
				
				bfstr.append(bankn).append(";"); 
				bfstrF.append("QDEPT").append(";"); 
				
				bfstr.append(Utilis.getIni(QRep_08.this, "SYS", "YEAR", 1)+Utilis.getIni(QRep_08.this, "SYS", "YEAR", 2));
				bfstrF.append("QYEARS");
				final String []fields=bfstr.toString().split(";");
				final String []fieldFs=bfstrF.toString().split(";");
				
			      myDialog = ProgressDialog.show(QRep_08.this,"資料處理中.....","請稍候.............",true);//		setAutoRotationMode();			  
				  
			      new Thread()
			      { 
			        public void run()
			        { 
			          try
			          { 
							HttpPost httpRequest = new HttpPost(uriAPI1);
							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 {
								httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
								HttpResponse httpResponse = new DefaultHttpClient()
										.execute(httpRequest);
								if (httpResponse.getStatusLine().getStatusCode() == 200)
								{
									String strResult = EntityUtils.toString(httpResponse	.getEntity());
									mHandlerQDR_81.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
								}
							} catch (Exception e)
							{
								e.printStackTrace();
							}
			          }
			          catch (Exception e)
			          {
			            e.printStackTrace();
			          }
			          finally
			          {
			            // 卸載所建立的myDialog物件。
			            myDialog.dismiss();
			          }
			        }
			      }.start(); 
        }else{
        	
        	finish();
        }
        
}	
	
	public void onResume(){
		super.onResume();
		}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_08.this);
			switch (id) {
				case R.id.btn_exit:
				{
					finish();
					break;
				}
			}
		}
	}
	
	Handler mHandlerQDR_81 = 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;
					Log.i("DOWNLOAD_5", "QRep_08_1"+Hresult);
				if (Hresult != null ){
					if (Hresult.indexOf("_okok")>2){

						if (mAdapter.mList != null) {
							mAdapter.mList.clear();
						}
						//開始以FTP 接收 rep_08_file csv
						String  FileH=android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(QRep_08.this, "SYS", "YEAR",7)+File.separator+"AA0_"+bankn+"_QHEAD_DEL.csv";
						
						final File localFileH = new File(FileH);
						final String serverFileH =FileH.replace(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+"/cwbuyer/", "/");
			        	boolean success=false;
						try {
							success=DBCloud.ftpDownloadAndSaveFile(QRep_08.this,Utilis.getIni(QRep_08.this, "SYS", "IMPORT",1), 21,Utilis.getIni(QRep_08.this, "SYS", "IMPORT",4), Utilis.getIni(QRep_08.this, "SYS", "IMPORT",5), serverFileH, localFileH);												
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
				          finally
				        {
					     try{
				        	  if (success){ //表示已存入LOCAL端

				        		  if (localFileH.exists()){  //檔案存在
				      					String encodout = "UTF8";
										StringBuffer buffers = new StringBuffer();  //buffer 讀取檔案全文
										FileInputStream fis = new FileInputStream(localFileH);
										InputStreamReader isr = new InputStreamReader(fis, encodout);
										Reader in = new BufferedReader(isr);
										int ch;
										
										while ((ch = in.read()) > -1) {
												buffers.append((char)ch);
											if(buffers.toString().indexOf("SSSS\r\n")>0){
												String fields=buffers.toString().substring(0,buffers.toString().length()-2);
												String[] arrayField = fields.toString().split(";");
												RepData data = new RepData();
// 0`FORMDATE`,1`FORMNO`,2`HANDNO`,3`CREATEDATETIME`,
//	4`QKIND`,5`DEPTNO`,6`USER`,7`USERNAE`,8`EMPID`,9`EMPNAME`,
//	10`BSUM`,11(`CASH`+`ORDCASH`),12(`CARD`+`ORDCARD`+`ATM`),
//	13`TRCASH`,14`PS2`,`TR`,'SSSS'
												data.iFormdate=arrayField[1];
												data.iTopLeft=arrayField[0]+"/No: "+arrayField[1];
												data.iTopRight="應"+arrayField[10]+"/現"+arrayField[11];
												data.iMLeft=arrayField[5]+"店/"+arrayField[6]+"/"+arrayField[7];
												data.iMRight="ATM刷"+arrayField[12];
												data.iDLeft="經手"+arrayField[8]+"/"+arrayField[9];
												if (!arrayField[15].equalsIgnoreCase("Y2"))
													data.iDMiddle=arrayField[14]+"改了"+":"+Mknd[Utilis.toInt(arrayField[4].substring(0,1))];
												else
													data.iDMiddle=arrayField[14]+"刪了"+":"+Mknd[Utilis.toInt(arrayField[4].substring(0,1))];
												
												data.iDRight="("+arrayField[3].substring(0,10)+")"+arrayField[2];
						 						mAdapter.mList.add(data);	
												buffers.delete(0, buffers.toString().length());	
											}
										}
										in.close();  //
				        		  }
				        	  }
				        	} catch (Exception e) {
				        		Log.i("DB", "DB_DIR_Exception:_1 " + e.toString());
				        		success=false;
				        	}
						mAdapter.notifyDataSetChanged();
				        }
					}
				}
			}
		}
	};
	
	
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();
				((ImageView)convertView.findViewById(R.id.img_ppic)).setVisibility(View.GONE);
				holder.textTopLeft = (TextView) convertView.findViewById(R.id.text_pgoodsno);
				holder.textTopRight = (TextView) convertView.findViewById(R.id.text_pimpo);
				holder.textMLeft = (TextView) convertView.findViewById(R.id.text_pname);
				holder.textMRight = (TextView) convertView.findViewById(R.id.text_pmoney);
				holder.textDMiddle = (TextView) convertView.findViewById(R.id.text_pnumber);
				holder.textDLeft = (TextView) convertView.findViewById(R.id.text_pcountry);
				holder.textDRight = (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);
			//holder.imageItem.setImageBitmap(Utilis.getLimitBitmap(data.iPic, 80, 80));
			
			holder.textTopLeft.setText(data.iTopLeft);
			
			holder.textMLeft.setText(data.iMLeft);
			holder.textDLeft.setText(data.iDLeft);
			holder.textDRight.setText(data.iDRight);
			holder.textMRight.setText(data.iMRight);
			holder.textDMiddle.setText(data.iDMiddle);
			holder.textTopRight.setText(data.iTopRight);			
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			ImageView imageItem;
			TextView textTopLeft;
			TextView textTopRight;
			TextView textMLeft;
			TextView textMRight;
			TextView textDLeft;
			TextView textDMiddle;
			TextView textDRight;
			
		}

	}
    
    
}
