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.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.BaseAdapter;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pwbuyer.main.R;

//銷售王的核心2層式ADAPTER,複製自 MANAGEITEM採購王
@SuppressLint({ "UseSparseArrays", "InflateParams", "HandlerLeak" })
public class QRep_05 extends Activity{
	
	
	//private LinkedList<RepData> mList = new LinkedList<RepData>();
	ReportAdapter mAdapter = null;
	ListView mListView = null;
	TextView mTextDuration = null;
    private int mRestoreChoice = 0;	
	private String[] list;	

	StringBuffer bfstr = new StringBuffer();
	StringBuffer bfstrF = new StringBuffer();
	
	String mWho ="";
	String mWhoName ="";
	final String myImportPath =android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+Utilis.getIni(this, "SYS", "YEAR",7);	
	private final String[] compStr =Utilis.getIni(this,"USER","COMPANY",9).split("!&!");
	protected static final int REFRESH_DATA = 0x00000001;
	String uriAPI=null;
	public ProgressDialog myDialog = null;
	
	/** State :  true 正式 , false 樣品*/
	String mEndDay = null;
	String mStartDay = null;
	String SQLday=null;
	 int Wday=0;
	private static final String[] WeekStr = { "(六)","(日)","(一)","(二)","(三)","(四)","(五)","(六)"};	 
	//發展為長按而啟動的功能
	
   	String btns=null;
   	String[] bttns;

	public class RepData{ 
		public String iLla; 
//		public String iLlb; 
		public String iLlu; 
		public String iLld; 
		public String iRla; 
//		public String iRlb; 
		public String iRlu; 
		public String iRld; 
		
	}

//	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>(); // 顏色行資料
	@SuppressLint("UseSparseArrays")
	HashMap<Integer,String> mCountCell = new HashMap<Integer,String>();  // 尺寸欄資料
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.qrepclock);
        
		String day = Utilis.getMonthDate();
		String[] days = day.split("~");
		mStartDay = days[0];
		mEndDay = days[1];
        
        mWho = getIntent().getStringExtra("WHO");  //傳過來的
        mWhoName = getIntent().getStringExtra("WHONAME");  //傳過來的
        
        //本單元就 上月 下月 2個 紐
        //和 列印 離開
        ((Button)findViewById(R.id.btn_prev_date)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_next_date)).setOnClickListener(new MainClick());
        ((TextView)findViewById(R.id.text_duration)).setOnClickListener(new MainClick());
        ((TextView)findViewById(R.id.text_duration)).setText(mWho+"/"+mWhoName);
        ((TextView)findViewById(R.id.text_momday)).setText(mStartDay.substring(0, 7));
        ((Button)findViewById(R.id.btn_rprint)).setOnClickListener(new MainClick());
        ((Button)findViewById(R.id.btn_rexit)).setOnClickListener(new MainClick());        

        mListView = (ListView)findViewById(R.id.list_clockitem);
        mAdapter = new ReportAdapter(this);
        mListView.setAdapter(mAdapter);
        
        //chkMode();
	}        
	
	public void onResume(){
		super.onResume();

		 chkMode();
		}
	
	// 特別處理 日結單 GROUPS第一層 是以(日/週/月)為統計結算 childs第二層 才是單頭
	//如何分開 日結+單頭  及 單頭+單身 的製作就是關鍵
	public 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("/", "-");
		SQLday=startDay.substring(0, 7);
		
		String SQL="";
		SQL="select * from qemp where QEMPID='"+mWho+"' and MOBIL like '"+SQLday+"%' order by MOBIL";

		
		if  (Utilis.haveInternet(QRep_05.this) && Utilis.toInt(Utilis.getIni(QRep_05.this, "SYS", "IMPORT", 3))==1){
			bfstr.delete(0, bfstr.toString().length());
			bfstrF.delete(0, bfstrF.toString().length());
			bfstr.append(Utilis.getIni(QRep_05.this, "SYS", "IMPORT", 2)).append(";");
			bfstrF.append("UID").append(";");
			bfstr.append(SQL);
			bfstrF.append("SQLADD");
			cloudClock( bfstr, bfstrF);
			
		}else{
			SQLiteDatabase db = Utilis.getDB(context);
			try {
					Cursor cs = null;
	 				cs = db.rawQuery(SQL, null);
					if (cs != null) {
						if (cs.getCount() > 0) {
							cs.moveToFirst();
							for (int i = 0; i < cs.getCount(); i++) {
								String theD=cs.getString(cs.getColumnIndex("MOBIL"));
								int Di=Utilis.toInt(theD.substring(8,10));  //取得日
								int DD=Di;	if (Di>16) DD=Di-17; else DD=Di-1;  //
								RepData data =mAdapter.mList.get(DD);
								if (Di>16){
									data.iRlu=cs.getString(cs.getColumnIndex("EMAIL"));
									data.iRld=cs.getString(cs.getColumnIndex("GMAIL"));
								}else{
									data.iLlu=cs.getString(cs.getColumnIndex("EMAIL"));
									data.iLld=cs.getString(cs.getColumnIndex("GMAIL"));
								}
								mAdapter.mList.set(DD,data);
								cs.moveToNext();
							}	
	 					}	
	 				}
					cs.close();
			}
			catch (Exception e)
	        {
	            e.printStackTrace();
	        }
            finally{db.close();}
			
		}	
	}
	
	
	class MainClick implements OnClickListener { //所有的觸發事件,在此集中管理
		@SuppressWarnings("unused")
		@Override
		public void onClick(View v) {
			int id = v.getId();
			Utilis.runVibrate(QRep_05.this);
			switch (id){
				//切換櫃員
				case R.id.text_duration:
				{
			        SQLiteDatabase db = Utilis.getDB(QRep_05.this);		
					Cursor cs = null;
					String mySqlBuf = "select CUSTNO,CUSTNAME from qcust where TR='40' order by CUSTNO";
					cs=db.rawQuery(mySqlBuf, null);
					if (cs.getCount()>0){
						Toast.makeText(QRep_05.this, "共有幾個櫃員:"+cs.getCount(), Toast.LENGTH_SHORT).show();
						
						cs.moveToFirst();
						list=new String[cs.getCount()];
						for (int i=0;i<cs.getCount();i++){
							list[i]=cs.getString(0)+"/"+cs.getString(1);
							cs.moveToNext();
						}
						AlertDialog.Builder sortDlg = new AlertDialog.Builder(QRep_05.this);
				        sortDlg.setTitle("請選擇一個櫃員,進入出勤查詢")
				        .setSingleChoiceItems(list, 0, new DialogInterface.OnClickListener() {
				            public void onClick(DialogInterface dialog, int item) {
				            	mRestoreChoice = item;
				            }
				        }) 
				        .setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
				            public void onClick(DialogInterface dialog, int which) { //確認
								//"search_dept",list[mRestoreChoice].substring(0,  list[mRestoreChoice].indexOf("_")));
				            	mWho=list[mRestoreChoice].substring(0,  list[mRestoreChoice].indexOf("/"));
				            	mWhoName=list[mRestoreChoice].substring( list[mRestoreChoice].indexOf("/")+1);
				            	((TextView)findViewById(R.id.text_duration)).setText(mWho+"/"+mWhoName);
				            	chkMode();
				            }
				          })
				        .setNegativeButton(getString(R.string.str_cancel), new DialogInterface.OnClickListener() {
				            public void onClick(DialogInterface dialog, int which) { //取消

				            }
				          }).show();
				          
					}
					db.close();
					cs.close();
					break;
				}
			//上月
				case R.id.btn_prev_date:  //當按了上一??
				{
	    			mStartDay = DateUtil.addMonth(mStartDay, -1,true);
					mEndDay = DateUtil.addMonth(mStartDay, 1);
					chkMode();
					break;
				}	
				//下月
				case R.id.btn_next_date:
				{
	    			mStartDay = DateUtil.addMonth(mStartDay, 1,true);
					mEndDay = DateUtil.addMonth(mStartDay, 1);
					chkMode();
	    			break;
				}			
				case R.id.btn_rprint:{

					StringBuffer sPrintB = new StringBuffer();
					String sepa="\r\n";
					sPrintB.append("^QXXXX,0,0"+sepa);
					sPrintB.append("^W56"+sepa+"^H10"+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);			
					int Loca=0;
					Loca=Loca+20;
					if (Utilis.toInt(compStr[8])==0){
						Loca=Loca+2;sPrintB.append("AZ,8,"+Loca+",2,2,0,0,"+compStr[0]+sepa);
						Loca=Loca+70;
					}else{
						Loca=Loca+2;sPrintB.append("Y8,"+Loca+",STYLEKEY"+sepa);
						Loca=Loca+230;
					}
					sPrintB.append("AZ,8,"+Loca+",1,2,0,0,"+mWho+"/"+mWhoName+" "+((TextView)findViewById(R.id.text_momday)).getText().toString()+" 打卡紀錄"+sepa);
					Loca=Loca+23;
					sPrintB.append("AZ,8,"+Loca+",1,2,0,0,------------------------------------"+sepa);
					Loca=Loca+50;sPrintB.append("AZ,8,"+Loca+",1,2,0,0,日    上班  下班  日    上班  下班"+sepa);
					Loca=Loca+20;	sPrintB.append("AZ,8,"+Loca+",1,2,0,0,------------------------------------"+sepa);
					for (int xx=0;xx<mAdapter.mList.size();xx++){
						RepData data =mAdapter.mList.get(xx);
						Loca=Loca+30;
						sPrintB.append("AZ,8,"+Loca+",1,2,0,0,"+data.iLla+sepa);
						sPrintB.append("AZ,80,"+Loca+",1,2,0,0,"+data.iLlu+sepa);
						sPrintB.append("AZ,155,"+Loca+",1,2,0,0,"+data.iLld+sepa);
						sPrintB.append("AZ,223,"+Loca+",1,2,0,0,"+data.iRla+sepa);
						sPrintB.append("AZ,295,"+Loca+",1,2,0,0,"+data.iRlu+sepa);
						sPrintB.append("AZ,370,"+Loca+",1,2,0,0,"+data.iRld+sepa);
						Loca=Loca+25;
						sPrintB.append("AZ,8,"+Loca+",1,2,0,0,------------------------------------"+sepa);
					}
					Loca=Loca+110;sPrintB.append("AZ,20,"+Loca+",1,2,0,0,"+"簽收人:____________________"+sepa);
					Loca=Loca+60;
					
					sPrintB.append("E"+sepa);
					
					String lenS="0000"+(int)(Loca/7.2);
					sPrintB.replace(2, 6,lenS.substring(lenS.length()-4,lenS.length()));
					
			 		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_05.this, "SYS","BAR_IP", 4);// 連線的ip
					   port =Utilis.toInt(Utilis.getIni(QRep_05.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_05.this, "已成功傳送資訊到條碼機!!", Toast.LENGTH_LONG).show();
										 Succed=true;
								 } catch (UnknownHostException e) {
									 success=0;
								 } catch (SocketException e) {
									 success=0;
								 } catch(IOException e) {
									 success=0;
								 }
								 sPrintB.delete(0, sPrintB.toString().length());
								 sPrintB.append("^QXXXX,0,0"+sepa);
								 sPrintB.append("^W80"+sepa+"^H7"+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=0;
					

					break;
				}
				case R.id.btn_rexit:{
					finish();
				}

			}
		}
	}
	
    
    private void chkMode(){        
        ((TextView)findViewById(R.id.text_momday)).setText(mStartDay.substring(0, 7));
        
        int lastdayofmonth=Utilis.toInt(mEndDay.substring(8, 10));
		if (mAdapter.mList != null) {
			mAdapter.mList.clear();
		}
		  Calendar calendar = Calendar.getInstance();
		  //指定日期,找出是星期幾
		  calendar.set(Calendar.YEAR, Integer.valueOf(mStartDay.substring(0, 4)));
		  calendar.set(Calendar.MONTH, Integer.valueOf(mStartDay.substring(5, 7))-1);
		  calendar.set(Calendar.DATE, Integer.valueOf(mStartDay.substring(8, 10)));
		  //未來在報表時,很有用
		  Wday = calendar.get(Calendar.DAY_OF_WEEK);

		//STR.substring(STR.length()-2);
        for (int d=1;d<17;d++){
        	RepData data = new RepData();
        	String RD=("00"+d);	
        	data.iLla=RD.substring(RD.length()-2)+WeekStr[(Wday % 7)];
        	data.iLlu="__:__";
        	data.iLld="__:__";
        	if ((d+16)<=lastdayofmonth){
        		RD=("00"+(d+16));data.iRla=RD.substring(RD.length()-2)+WeekStr[((Wday+16) % 7)];
        	}else{
            	data.iRla="__:__";
        	}
        	data.iRlu="__:__";
        	data.iRld="__:__";
        	mAdapter.mList.add(data);
        	Wday +=1;
        }
	    		
    	getGroupData(QRep_05.this, mStartDay, mEndDay, null, null);
		    	
        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);
		}

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

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

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		@SuppressWarnings("unused")
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.list_clock_rep1, null);
				holder = new ViewHolder();
				holder.text_lla = (TextView) convertView.findViewById(R.id.text_lla);
				holder.text_llu = (TextView) convertView.findViewById(R.id.text_llu);
				holder.text_lld = (TextView) convertView.findViewById(R.id.text_lld);
				holder.text_rla = (TextView) convertView.findViewById(R.id.text_rla);
				holder.text_rlu = (TextView) convertView.findViewById(R.id.text_rlu);
				holder.text_rld = (TextView) convertView.findViewById(R.id.text_rld);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.00");
			RepData data = mList.get(position);
			
			holder.text_lla.setText(data.iLla);
			holder.text_llu.setText(data.iLlu);
			holder.text_lld.setText(data.iLld);
			holder.text_rla.setText(data.iRla);
			holder.text_rlu.setText(data.iRlu);
			holder.text_rld.setText(data.iRld);
			return convertView;
		}

		/* class ViewHolder */
		private class ViewHolder {
			TextView text_lla;
			TextView text_llu;
			TextView text_lld;
			TextView text_rla;
			TextView text_rlu;
			TextView text_rld;
			
		}
	}//end of Report_adapter

private void cloudClock(StringBuffer bfstr,StringBuffer bfstrF){
	final String []fields=bfstr.toString().split(";");
	final String []fieldFs=bfstrF.toString().split(";");
//      myDialog = ProgressDialog.show(QRep_05.this,"資料處理中.....","請稍候.............",true);			  
	  
      new Thread()
      { 
        public void run()
        { 
          try
          {
        	  String uriH="http://"+Utilis.getIni(QRep_05.this, "SYS", "IMPORT", 1)+File.separator+Utilis.getIni(QRep_05.this, "SYS", "IMPORT", 2)+File.separator;
				uriAPI=uriH+"qrepclock02.php";
				HttpPost httpRequest = new HttpPost(uriAPI);
				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());
						mHandlerQRC_02.obtainMessage(REFRESH_DATA, strResult).sendToTarget();
					}
				} catch (Exception e)
				{
					e.printStackTrace();
				}
          }
          catch (Exception e)
          {
            e.printStackTrace();
          }
          finally
          {
            // 卸載所建立的myDialog物件。
//            myDialog.dismiss();
          }
        }
      }.start(); 

}

	Handler mHandlerQRC_02 = new Handler()
{//目的是 取得 櫃員打卡的 代號 名稱 MSN='0123456789'班別
	@Override
	public  void handleMessage(Message msg)
	{
		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_mHandler_QEMP_CLOCK__00===", Hresult);
						if (Hresult.indexOf("SSSS\r\n")>2){
								String Line[] =Hresult.split("SSSS\r\n");
								
							for (int j = 0; j< Line.length; j++) {
								String Lines[] =Line[j].split(";");
									String theD=Lines[3];
									int Di=Utilis.toInt(theD.substring(8,10));  //取得日
									int DD=Di;	if (Di>16) DD=Di-17; else DD=Di-1;  //
									RepData data =mAdapter.mList.get(DD);
									if (Di>16){
										data.iRlu=Lines[4];
										data.iRld=Lines[6];
									}else{
										data.iLlu=Lines[4];
										data.iLld=Lines[6];
									}
									mAdapter.mList.set(DD,data);
							        mAdapter.notifyDataSetChanged();        
							}
								
						}
			}
		}
	}
};


}
