/*
 * Created on 28 �.�. 2548
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.csc.library.databean;

import com.csc.library.utilities.MyLog;
import java.text.DecimalFormat;
import java.util.Iterator;

import org.jdom.Element;

import com.csc.library.database.DataSet;
import com.csc.library.database.MyHashMap;
import com.csc.library.formula.FormulaString;
import com.csc.library.report.ReportUDF;
import com.csc.library.session.DbInquiry;
import com.csc.library.session.DbRecord;
import com.csc.library.session.InitialEnvironment;
import com.csc.library.session.InitialInquiry;
import com.csc.library.utilities.CscCalendar;
import com.csc.library.utilities.CscTime;
import com.csc.library.utilities.ReadXml;

/**
 * @author XeroX
 * 
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
public class Simttime_current1bu2_ extends Mbu2 {
	
    private MyHashMap hm_data = new MyHashMap();
    private MyHashMap hm_emp = new MyHashMap();
    private MyHashMap hm_dateH = null; //Holiday
    private MyHashMap hm_dataL = null; //Leave Column
    private MyHashMap hm_Corperate = new MyHashMap(); //Coperate_title code
    private String  lang = "ENG";
    private boolean flag = false;

    public Simttime_current1bu2_() {
        super();
    }

    public int assignField(DataSet rs) {
        int temp = super.assignField(rs);
        if (!this.getString("bu2id").equals("")) {
        	this.setHashData();
        	this.hm_emp.clear();
        	if (this.flag==false) {
        		this.hm_dateH = new MyHashMap(); 
        	    this.hm_dataL = new MyHashMap(); 
        	     
	        	//Initial Value
	        	this.setLang();	            
	            this.setHoliday();
	            this.setMonth();
	            this.getDataML();
	            this.hm_Corperate = this.getCorperate_Title();
	            this.flag=true;
        	}
           
            //Set Data
            this.setData();
            this.countEmp();
            //this.setDecimal();
            this.setCalPerHead();
            MyLog.debug(this, "hm_data -->> "+this.hm_data);
            //MyLog.debug(this, "hm_dateH -->> "+this.hm_dateH);
        }
        return temp;
    }

    private void setLang() {
		if (this.param.containsKey("LANGUAGE")) {
			this.lang = (String) this.param.get("LANGUAGE");			
		}
	}
    
    private void setHashData() {
        for (int i = 1; i <= 16; i++) {
            this.hm_data.put("data" + i, 0);
        }
    }

    private void setData() {
        try {
        	CscCalendar csc = new CscCalendar();
            String year = String.valueOf(csc.getYear());
            String month = csc.getMM();
            String days = String.valueOf(csc.getEndDateOfMonth());
            String sql = "dateid between '" + year + "-"+month+"-01' and '"+year+"-"+month+"-"+days+"'";
            String monthFull="";
            
			if (this.lang.equals("ENG")) {
				monthFull = csc.getEngLongMonth() + " " + csc.getYear();
			} else {
				monthFull = csc.getThaiLongMonth() + " " + csc.getYear();
			}

			if (this.param.containsKey("DATE")) {
				CscCalendar csD = new CscCalendar((String) this.param.get("DATE"));
				year = String.valueOf(csD.getYear());
				month = csD.getMM();
				days = String.valueOf(csD.getEndDateOfMonth());
				sql = "dateid between '" + year + "-"+month+"-01' and '"+year+"-"+month+"-"+days+"'";
				if (this.lang.equals("ENG")) {
					monthFull = csD.getEngLongMonth() + " " + csD.getYear();
				} else {
					monthFull = csD.getThaiLongMonth() + " " + csD.getYear();
				}
			}
			
			this.hm_data.put("monthfull", monthFull);
			
			DbInquiry inqEmp = new InitialInquiry(this.getUProfile()).getDbInquiry();
			inqEmp.initMyTable("Memployee", "", "employeeid");
			inqEmp.setColumn("employeeid, companyid, corperate_title");
			
            DbInquiry in1 = new InitialInquiry(this.getUProfile()).getDbInquiry();
            in1.initMyTable("Ttime_current1", "", "bu2,employeeid, dateid");
            in1.setColumn("employeeid,companyid,dateid,sequence,lv_ty,c_dt_bg,c_dt_en,c_tm_bg,c_tm_en," +
				"m_tm_bg,m_tm_en,m_dt_bg,m_dt_en,bu1,bu2,ot1,ot5,ot3,hour_d,m_lv,lt,time0id,eventgrp");
            in1.setFilter(sql);
            in1.putChild(inqEmp);
            this.putChild(in1);
            this.refreshChild("Ttime_current1");
            
            do {
            	DbRecord rec = in1.getCurrentDbRecord();
            	if (rec.foundData()) {
            	DbInquiry child = (DbInquiry) in1.getChild("Memployee");
            	if (!this.hm_Corperate.containsKey(child.getString("corperate_title"))) {
	            	this.setDataEmp(rec);
	            	
	            	if (rec.getDouble("m_lv")>0) {
						this.setDataLeave(rec);
					}
	            	
	            	if (rec.getDouble("lt") > 0) {
						this.setDataLate(rec.getDouble("lt"));
					}
	            	
	            	if ((rec.getDouble("ot1")>0) || (rec.getDouble("ot5")>0) || (rec.getDouble("ot3")>0)) {
						this.setDataOT(rec);
					}         
            	}
            	}
            } while (in1.next());
        } catch (Exception e) {
	MyLog.error(this, e);

            
        }
    }
    
    private float getLeave(float time) {
		float result=time;
		if (time>0&&time<=2) {
			result=2;
		} else if (time>2&&time<=4) {
			result=4;
		} else if (time>4&&time<=6) {
			result=6;
		} if (time>6) {
			result=8;
		} 
		return result;
	}

    private void setDataLeave(DbRecord rec) {
        try {
        	boolean dataL = true;
			int colLv=2; //������������� Column ��� 3-8
			float lv=0f, other=0f, total=0f;
			FormulaString fs = new FormulaString();
			for (int i=1; i<=4; i++) {
				String tmp = (String) this.hm_dataL.get("col_id0" + i);
				if (tmp.equalsIgnoreCase(rec.getString("lv_ty"))) {
					colLv += i;
					lv = Float.parseFloat(this.hm_data.get("data"+colLv).toString());
					CscTime c = new CscTime(lv);
					//c.add(rec.getFloat("m_lv"));
					c.add(this.getLeave(rec.getFloat("m_lv")));
					this.hm_data.put("data"+colLv, c.getFloat());
					dataL = false;
				}
			}

			if (dataL==true) {
				other = Float.parseFloat(this.hm_data.get("data7").toString());
				CscTime c = new CscTime(other);
				//c.add(rec.getFloat("m_lv"));
				c.add(this.getLeave(rec.getFloat("m_lv")));
				this.hm_data.put("data7", c.getFloat());
			}
			
			total = Float.parseFloat(this.hm_data.get("data8").toString());
			CscTime c = new CscTime(total);
			c.add(this.getLeave(rec.getFloat("m_lv")));
			this.hm_data.put("data8", c.getFloat());
        } catch (Exception e) {
	MyLog.error(this, e);

            
        }
    }
    
    //�ӹdz������ (�繤���)
    private void setDataLate(double late) {
    	int calT = 0;
		
		if (late<=0.15) {
			calT = Integer.parseInt(this.hm_data.get("data9").toString());
			calT++;
			this.hm_data.put("data9", calT);
		} else if (late>0.15) {
			calT = Integer.parseInt(this.hm_data.get("data10").toString());
			calT++;
			this.hm_data.put("data10", calT);
		}
		if (late>0) {
			calT = Integer.parseInt(this.hm_data.get("data11").toString());
			calT++;
			this.hm_data.put("data11", calT);
		}
    }

    private void setDataOT(DbRecord rec) {
		try {
			float ot = 0f;
			if (rec.getDouble("ot1")>0) {
				ot = Float.parseFloat(this.hm_data.get("data12").toString());
				CscTime cs=new CscTime(ot);
				cs.add(rec.getFloat("ot1"));
				this.hm_data.put("data12", cs.getFloat());
			} 
			if (rec.getDouble("ot5")>0) {
				ot = Float.parseFloat(this.hm_data.get("data13").toString());
				CscTime cs=new CscTime(ot);
				cs.add(rec.getFloat("ot5"));
				this.hm_data.put("data13", cs.getFloat());
			}
			if (rec.getDouble("ot3")>0) {
				ot = Float.parseFloat(this.hm_data.get("data14").toString());
				CscTime cs=new CscTime(ot);
				cs.add(rec.getFloat("ot3"));
				this.hm_data.put("data14", cs.getFloat());
			}
			if ((rec.getDouble("ot1")>0)||(rec.getDouble("ot5")>0)||(rec.getDouble("ot3")>0)) {
				ot = Float.parseFloat(this.hm_data.get("data15").toString());
				CscTime cs=new CscTime(ot);
				cs.add(rec.getFloat("ot1"));
				cs.add(rec.getFloat("ot5"));
				cs.add(rec.getFloat("ot3"));
				this.hm_data.put("data15", cs.getFloat());
			}
		} catch (Exception e) {
			MyLog.error(this, e);

			
		}
	}

    /*
	 * �� column ����� �ҡ CODEID � param
	 * ��������� MLEAVE_REPORT �������ǡ�������
	 */
	private void getDataML() {
		try {
			String codecol="", sql="", key="", sqlMev="";
			
			if (this.param.containsKey("CODEID")) {
				String code = (String) this.param.get("CODEID");
				if (!code.trim().equals("")) {
					codecol = code;
				}
			}
			
			//�� column �ͧ�����
			if (!codecol.equals("")) {
				sql = "CODEID='" + codecol + "'";
			}
			DbInquiry in1 = new InitialInquiry(this.getUProfile()).getDbInquiry();
			in1.initMyTable("MLEAVE_REPORT", "", "");
			in1.setColumn("*");
			in1.setFilter(sql);
			in1.refresh();
			in1.next();
			for (int i=1; i<=4; i++) {
				if (!in1.getString("col0"+i).equals("")) {
					this.hm_dataL.put("col_id0" + i, in1.getString("col0" + i));
					//��� column ����ҷ���� ���㹵���� key �������������㹡�� filter ����					
					if (i==1) {
						key += "'"+in1.getString("col0" + i)+"'";
					} else {
						key += ",'"+in1.getString("col0" + i)+"'";
					}
				}
			}
			
			if (!key.equals("")) {
				sqlMev = "eventgrpid in ("+key+")";
			}
			DbInquiry in2 = new InitialInquiry(this.getUProfile()).getDbInquiry();
			in2.initMyTable("MEVENTGRP", "", "");
			in2.setColumn("*");
			in2.setFilter(sqlMev);
			in2.refresh();
			while (in2.next()) {
				if (this.lang.equalsIgnoreCase("ENG")) {
					this.hm_dataL.put(in2.getString("eventgrpid"), in2.getString("edesc"));
				} else {
					this.hm_dataL.put(in2.getString("eventgrpid"), in2.getString("tdesc"));
				}
			}

			for (int i=1; i<=4; i++) {
				//���Ҵ֧���͡��������������� "" ŧ�᷹ ����� colH ��ͪ��� �������
				if (this.hm_dataL.get(this.hm_dataL.get("col_id0" + i))!=null) {
					this.hm_data.put("colH"+i, this.hm_dataL.get(this.hm_dataL.get("col_id0"+i)));
				} else { 
					this.hm_data.put("colH"+i,"");;
				}
			}
		} catch (Exception e) {
			MyLog.error(this, e);

			
		}
	}

    //��Ŵ���ҧ�ѹ��شŧ MyHashMap
	private void setHoliday() {
		try {			 
			String filter="";
			if(this.param.containsKey("DATE")){
				String date=(String)this.param.get("DATE");
	            CscCalendar csD=new CscCalendar(date);
	            String dateS=csD.getYear()+"-"+csD.getMM()+"-01";
	            String dateE=csD.getYear()+"-"+csD.getMM()+"-"+csD.getEndDateOfMonth();
	            filter="hdate between '"+dateS+"' and '"+dateE+"'";
			}
			
			String holidayCode="";
			if (this.param.containsKey("HOLIDAY_CODE")) {
				holidayCode = (String) this.param.get("HOLIDAY_CODE");
			}
			
			if (!filter.equals("") && !holidayCode.equals("")) {
				filter += " and holidayid='"+holidayCode+"'";
			}
			
			DbInquiry inH = new InitialInquiry(this.getUProfile()).getDbInquiry();
			inH.initMyTable("Mholiday1", "", "");
			inH.setColumn("holidayid,hdate,companyid,edesc,tdesc");
			if (!filter.equals("")) 
				inH.setFilter(filter);
			inH.refresh();
			String mh = "";
			int vm = 0;
			while (inH.next()) {
				CscCalendar cs = new CscCalendar();
				cs.setDate(inH.getString("hdate"));
				this.hm_dateH.put(cs.getYYYYMMDD(), Integer.parseInt(cs.getMM()));
			}
		} catch (Exception e) {
			MyLog.error(this, e);

			
		}
	}
	
	private void setMonth() {
     	CscCalendar csc = new CscCalendar();
        String year = String.valueOf(csc.getYear());
        String month = csc.getMM();
        int days = csc.getWorkDayInM();       
        CscCalendar cs;

        if (this.param.containsKey("DATE")) {
            String date = (String) this.param.get("DATE");
            CscCalendar csD = new CscCalendar(date);
            year = String.valueOf(csD.getYear());
            month = csD.getMM();
            days = csD.getWorkDayInM();
        } 

        int size = 0;
        if (!this.hm_dateH.isEmpty()) { 
        	size = this.hm_dateH.size();
        }
        this.hm_data.put("data1", days-size);
        this.hm_data.put("dataWorkDay", days-size);
    }

     private void setDataEmp(DbRecord rec) {
        try {
            int ie=0;
			 if (this.hm_emp.containsKey(rec.getString("employeeid"))) {
				ie = Integer.parseInt(this.hm_emp.getString(rec.getString("employeeid")));
				ie++;
				this.hm_emp.put(rec.getString("employeeid"), ie);
			 } else {
			 	this.hm_emp.put(rec.getString("employeeid"), 1);
	         }
        } catch (Exception e) {
	MyLog.error(this, e);

            
        }
    }

    private void countEmp() {
		try {
			int iemp=0;
			
			Iterator it = this.hm_emp.keySet().iterator();
			while (it.hasNext()) { 
				it.next();
				iemp++;
			}
			this.hm_data.put("data2", iemp);		
		} catch (Exception e) {
			MyLog.error(this, e);

			
		}
	}

    private void setCalPerHead() {
    	ReportUDF udf = new ReportUDF();
    	DecimalFormat	df	=	new	 DecimalFormat("0.00");    	
        //double ot = Double.parseDouble(this.hm_data.getString("data15"));
    	String tmp = udf.getRoundOTEasy(this.hm_data.getString("data15"));
    	tmp = tmp.replaceAll(",","");
        double ot = Double.parseDouble(tmp);        
        String x = df.format(ot);
        ot = Double.parseDouble(x);
        int emp = Integer.parseInt(this.hm_data.getString("data2"));
        if (emp > 0) {
        	FormulaString util = new FormulaString();    	
    		//step 1
    		int OTperStaff = (int) ot/emp;
    		//MyLog.debug(this, "step 1 ==== "+OTperStaff);
    		//step 2
    		double totalOTbase100 = util.Tm_To_Dec(ot);
    		//int result2 =  (int) ((totalOTbase100*60)/emp);
    		DecimalFormat d = new DecimalFormat();
    		d.applyPattern("0");
    		int result2 = Integer.parseInt(d.format(((totalOTbase100*60)/emp)));
    		//MyLog.debug(this, "step 2 ==== "+result2);
    		//step 3		
    		int result3 = OTperStaff*60;
    		//MyLog.debug(this, "step 3 ==== "+result3);
    		//step 4
    		int result4 = result3-result2;
    		if (result4<0) { 
    			result4 = result4*(-1);
    		}
    		double result4Total = (result4*0.01);
    		//MyLog.debug(this, "step 4 ==== "+result4Total);
    		//step 5
    		double value = OTperStaff+result4Total;
    		//MyLog.debug(this, "step 5 ==== "+value);        	
        	
        	this.hm_data.put("data16", df.format(value));
        }
    }
    
    //��˹������� Hash �繷ȹ��� 2 ���˹� ����ŧ�鹰ҹ 100
	private void setDecimal(){
		double value=0;
		String data="";
		DecimalFormat	df	=	new	DecimalFormat("0.00");
		FormulaString fs = new FormulaString();		
		for (int k=3; k<=8; k++) {
			//value=Double.parseDouble(this.hm_data.getString("data"+k));
			data=df.format(Double.parseDouble(this.hm_data.getString("data"+k)));
			value = fs.Tm_To_Dec(Double.parseDouble(data));			
			this.hm_data.put("data"+k,df.format(value));
		}
		
		for (int k=12; k<=15; k++) {
			//value=Double.parseDouble(this.hm_data.getString("data"+k));
			data=df.format(Double.parseDouble(this.hm_data.getString("data"+k)));
			value = fs.Tm_To_Dec(Double.parseDouble(data));			
			this.hm_data.put("data"+k,df.format(value));
		}		
	}

    public String getString(String field) {
        if (this.hm_data.containsKey(field)) {
            return this.hm_data.get(field).toString();
        } else {
            return super.getString(field);
        }
    }
    
    private MyHashMap getCorperate_Title() {
    	MyHashMap hm = new MyHashMap();
    	MyLog.debug(this, "**** LOAD XML CORPERATE_TITLE FILE****");
    	try {
			String fileName = "CORPERATE_TITLE_TAR022.xml";
			InitialEnvironment en = new InitialEnvironment("GLOBAL");
			String xmlPath = en.getValue("dirimport-dir");
			ReadXml read = new ReadXml();
			read.setDataManager(xmlPath + fileName);
			Element root = read.getRootElement();
			Iterator it = root.getChildren().iterator();
			Element obj;
			while (it.hasNext()) {
				obj = (Element) it.next();
				hm.put(obj.getText().trim(), obj.getText().trim());
			}
		} catch (Exception e) {
			MyLog.error(this, e);

			
		}
		return hm;
    }

}