package com.csc.library.databean;

import java.rmi.RemoteException;
import java.util.StringTokenizer;

import com.csc.library.database.ChildManager;
import com.csc.library.session.DbInquiry;
import com.csc.library.session.DbRecord;
import com.csc.library.session.DbTable;
import com.csc.library.session.InitialInquiry;
import com.csc.library.session.RecordCmp;
import com.csc.library.utilities.CscCalendar;
import com.csc.library.utilities.MyLog;

public class Totapprove_nstda0 extends RecordCmp {
	
	private String oldDocNo = "";
	private DbInquiry inqTime1 = null;

	public Totapprove_nstda0() {
		super("Totapprove_nstda0", "Totapprove_nstda0 Table");
	}
	
	protected boolean preInsertTrigger() throws Exception {
        boolean result = super.preInsertTrigger();              
        if (this.getString("wf_status").equalsIgnoreCase("4") || this.getString("wf_status").equalsIgnoreCase("6") 
        		|| this.getString("wf_status").equalsIgnoreCase("8") || this.getString("wf_status").equalsIgnoreCase("9")) {
            this.setWFOff();
            this.chkChild();            
        }         
        return result;      
    }
    
    protected boolean preUpdateTrigger() throws Exception {
        boolean result = super.preUpdateTrigger();  
        if (this.getString("wf_status").equalsIgnoreCase("4") || this.getString("wf_status").equalsIgnoreCase("6") 
        		|| this.getString("wf_status").equalsIgnoreCase("8") || this.getString("wf_status").equalsIgnoreCase("9")) {
            this.setWFOff();
            this.chkChild();            
        } 
        return result;
    }  
    
    protected void postInsertTrigger() throws Exception {
        super.postInsertTrigger();              
        if (this.getString("wf_status").equalsIgnoreCase("4") || this.getString("wf_status").equalsIgnoreCase("6")) {
        	this.clearOldDocApprove();
        	this.saveDocApprove();
        } else if (this.getString("wf_status").equalsIgnoreCase("8") || this.getString("wf_status").equalsIgnoreCase("9")) {
        	this.clearOldDocApprove();
        }  
    }
    
    protected void postUpdateTrigger() throws Exception {
        super.postUpdateTrigger();
        if (this.getString("wf_status").equalsIgnoreCase("4") || this.getString("wf_status").equalsIgnoreCase("6")) {
        	this.clearOldDocApprove();
        	this.saveDocApprove();
        } else if (this.getString("wf_status").equalsIgnoreCase("8") || this.getString("wf_status").equalsIgnoreCase("9")) {
        	this.clearOldDocApprove();
        }
    }
    
    protected void postDeleteTrigger() throws Exception {       
        super.postDeleteTrigger();
        this.clearOldDocApprove();
    }
    
    /*
     * �ӡ��ź record ��������١����Ҩҡ˹�Ҩ�
     */
    private void chkChild() {
    	try {
    		String delRec = "";
	    	DbTable dt = (DbTable) this.getChild("Totapprove_nstda1");
			dt.first();
			while (!dt.eof()) {
				String line = dt.getString("line_no");
				String name = "__TOTAPPROVE_NSTDA1$CHECKREC$"+line;
				String value = "";
				if (this.param.containsKey(name)) {
					value = (String) this.param.get(name);
					if (value.equalsIgnoreCase("false")) {
						delRec += (line+",");
					}
				}				
				dt.next();
			}
			
			StringTokenizer str = new StringTokenizer(delRec, ",");
			while (str.hasMoreTokens()) {
				String key = str.nextToken();
				dt.deleteRecord(key);
			}
    	} catch (Exception e) {
    		MyLog.error(this, e);
    	}
    }
	
	private String genCh() {
		int lineno = 1;		
		try {
			CscCalendar c1 = new CscCalendar(this.getString("DATE_START"));
			CscCalendar c2 = new CscCalendar(this.getString("DATE_END"));
			ChildManager oChild = this.getChild("TOTAPPROVE_NSTDA1");
			if ((oChild != null) && (oChild instanceof DbTable)) {
				DbTable dbTable = (DbTable) oChild;
				dbTable.clearRecord();			
				
				DbInquiry inq = new InitialInquiry(this.userPro).getDbInquiry();
				inq.setParam(this.param);
				inq.setSchemaName(this.userPro.getSchemaName());	
				inq.initMyTable("Ttime_current1", 
						"employeeid='"+this.getString("employeeid")+"' and " +
						"(dateid between '"+c1.getYYYYMMDD()+"' and '"+c2.getYYYYMMDD()+"') and " +
						"ac_ot>0 and (docno='' or docno is null)",
						"employeeid,dateid");
				inq.setColumn("*");
				inq.refresh();
				while (inq.next()) {                    
                    DbRecord rec = dbTable.getNewRecord();
					rec.set("APPROVEID", this.getString("APPROVEID"));
					rec.set("COMPANYID", this.getString("COMPANYID"));
					rec.set("OT_DATE", inq.getString("dateid"));
					rec.set("OT_SHIFT", inq.getString("time0id"));
					rec.set("OT_TIMEIN", inq.getString("m_tm_bg"));
					rec.set("OT_TIMEOUT", inq.getString("m_tm_en"));
					rec.set("OT_TOTAL", inq.getString("ac_ot"));
					rec.set("OT_1", inq.getString("ot1"));
					rec.set("OT_15", inq.getString("ot5"));
					rec.set("OT_2", inq.getString("ot2"));
					rec.set("OT_3", inq.getString("ot3"));
					rec.set("DAY_TYPE", inq.getString("eventgrp"));
					rec.set(dbTable.getMinorKey(), lineno++);
					dbTable.putNewRecord(rec);
				}
			}
		} catch (RemoteException e) {
			MyLog.error(this, e);
			// TODO Auto-generated catch block				
		}
		return String.valueOf(lineno);
	}

	public String getString(String field) {
		if (field.equalsIgnoreCase("gen")) {
			return this.genCh();
		} else {
			return super.getString(field);
		}
	}
	
	public int search() {
    	int result = super.search();
    	if (result==1) {
    		this.oldDocNo = this.getString("approveid");
    	}
    	return result;
    }		
	
	private DbInquiry getInqTime1() {
		try {
			this.param.put("__screen", "");
			if (this.inqTime1==null) {				
				this.inqTime1 = new InitialInquiry(this.userPro).getDbInquiry();
				this.inqTime1.setParam(this.param);
				this.inqTime1.setSchemaName(this.userPro.getSchemaName());
				this.inqTime1.initMyTable("Ttime_current1", "", "");
				this.inqTime1.setColumn("*");				
			}			
		} catch (Exception e) {
			MyLog.error(this, e);
		}
		return this.inqTime1;
	}
	
	/*
	 * �ӡ�� clear ��� DOCNO ����� update ŧ�� ttime_current1 
	*/
	private void clearOldDocApprove() {
		try {
			this.inqTime1 = this.getInqTime1();
			this.inqTime1.setFilter("docno='"+this.oldDocNo+"' and doctype='OTA'");
			this.inqTime1.refresh();
			while (this.inqTime1.next()) {
				DbRecord rec1 = this.inqTime1.getCurrentDbRecord().cloneRecord(true);
				rec1.set("DOCNO", "");
				rec1.set("DOCTYPE", "");				
				rec1.save();
			}
		} catch (Exception e) {
			MyLog.error(this, e);
		}
	}
	
	/*
	 * �ӡ�� update ��� DOCNO ����� ŧ�� ttime_current1 
	*/
	private void saveDocApprove() {
		try {
			DbTable dt = (DbTable) this.getChild("Totapprove_nstda1");
			dt.first();
			while (!dt.eof()) {
				CscCalendar csc = new CscCalendar(dt.getString("ot_date"));
				this.inqTime1 = this.getInqTime1();
				this.inqTime1.setFilter("employeeid='"+this.getString("employeeid")+"' and dateid='"+csc.getYYYYMMDD()+"'");
				this.inqTime1.refresh();
				while (this.inqTime1.next()) {
					DbRecord rec1 = this.inqTime1.getCurrentDbRecord().cloneRecord(true);
					rec1.set("DOCNO", this.getString("approveid"));
					rec1.set("DOCTYPE", "OTA");				
					rec1.save();
				}
				dt.next();		
			}		
		} catch (Exception e) {
			MyLog.error(this, e);
		}
	}
}