/**
 * 
 * 新規
 * 2011/1/25
 * 孫奇全
 *  
 */

package com.aimluck.eip.exttimecard;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.Attributes;

import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SelectQuery;
import org.apache.jetspeed.services.logging.JetspeedLogFactoryService;
import org.apache.jetspeed.services.logging.JetspeedLogger;
import org.apache.turbine.util.RunData;
import org.apache.velocity.context.Context;

import com.aimluck.eip.cayenne.om.portlet.EipTExtTimecardSystem;
import com.aimluck.eip.cayenne.om.portlet.ImwTExtTimecardSystemDetail;
import com.aimluck.eip.common.ALAbstractSelectData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALEipConstants;
import com.aimluck.eip.common.ALEipManager;
import com.aimluck.eip.common.ALPageNotFoundException;
import com.aimluck.eip.common.ALPermissionException;
import com.aimluck.eip.exttimecard.util.ExtTimecardUtils;
import com.aimluck.eip.modules.actions.common.ALAction;
import com.aimluck.eip.orm.DatabaseOrmService;
import com.aimluck.eip.services.accessctl.ALAccessControlConstants;
import com.aimluck.eip.util.ALEipUtils;


public class ExtTimecardSystemDetailMapSelectData extends ALAbstractSelectData {
	  /** logger */
	  private static final JetspeedLogger logger = JetspeedLogFactoryService
	      .getLogger(ExtTimecardSystemDetailMapSelectData.class.getName());

	  /** 一覧データ */
	  private ArrayList list;
	  
	  /** システムの総数 */
	  private int systemSum;

	  /** 種別リスト */
	  private Map statusMap = new LinkedHashMap();
	  
	  private String systemId;
	  
	  private String systemName;
	  


	  public void init(ALAction action, RunData rundata, Context context)
	      throws ALPageNotFoundException, ALDBErrorException {
	    super.init(action, rundata, context);

	    if(rundata.getParameters().getString("systemId") != null){
	      systemId = rundata.getParameters().getString("systemId");
	      ALEipUtils.setTemp(rundata, context, "systemId", systemId);
	    }else{
	      systemId = ALEipUtils.getTemp(rundata, context, "systemId");
	    }
	    try{
	      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
	      Expression exp = ExpressionFactory.matchDbExp(
	           EipTExtTimecardSystem.SYSTEM_ID_PK_COLUMN,systemId);
	      SelectQuery query = new SelectQuery(EipTExtTimecardSystem.class, exp);
	      List slist = dataContext.performQuery(query);
	      EipTExtTimecardSystem s = (EipTExtTimecardSystem)slist.get(0);
	      this.setSystemName(s.getSystemName());
	    }catch(Exception ex){
	      
	    }
	  }

	  /**
	   * @see com.aimluck.eip.common.ALAbstractSelectData#selectList(org.apache.turbine.util.RunData,
	   *      org.apache.velocity.context.Context)
	   */
	  protected List selectDetailList(RunData rundata, Context context) {
    
	    try{
	      DataContext dataContext = DatabaseOrmService.getInstance()
	          .getDataContext();
	      Expression exp = ExpressionFactory.matchDbExp(
	          ImwTExtTimecardSystemDetail.SYSTEM_ID_COLUMN, systemId);
	      SelectQuery query = new SelectQuery(ImwTExtTimecardSystemDetail.class, exp);
	      //Upd 20110706 小濵 Start ---
	      //query.addOrdering(ImwTExtTimecardSystemDetail.CREATE_DATE_PROPERTY, true);
	      query.addOrdering(ImwTExtTimecardSystemDetail.START_HOUR_PROPERTY,true);
	      query.addOrdering(ImwTExtTimecardSystemDetail.START_MINUTE_PROPERTY,true);
          //Upd 20110706 小濵 End ----
	      List slist = dataContext.performQuery(query);
	      //Add 20110708 小濵 Start ---
	      if(slist != null && slist.size() > 0){
	        EipTExtTimecardSystem system = ExtTimecardUtils.getEipTExtTimecardSystem(
	            dataContext, Long.valueOf(systemId).longValue());
	        int minutes1 = 0,minutes2 = 0;
	        for(int i = 0;i < slist.size() - 1;i++){
	          for(int j = i + 1;j < slist.size();j++){
	            ImwTExtTimecardSystemDetail detail1 = (ImwTExtTimecardSystemDetail)slist.get(i);
	            if(detail1.getStartHour() >= system.getChangeHour()){
	              minutes1 = detail1.getStartHour() * 60 + detail1.getStartMinute();
	            }else{
	              minutes1 = (detail1.getStartHour() + 24) * 60 + detail1.getStartMinute();
	            }
	            ImwTExtTimecardSystemDetail detail2 = (ImwTExtTimecardSystemDetail)slist.get(j);
	            if(detail2.getStartHour() >= system.getChangeHour()){
	              minutes2 = detail2.getStartHour() * 60 + detail2.getStartMinute();
	            }else{
	              minutes2 = (detail2.getStartHour() + 24) * 60 + detail2.getStartMinute();
	            }
	            if(minutes1 > minutes2){
	              slist.set(i, (Object)detail2);
	              slist.set(j, (Object)detail1);
	            }
	          }
	        }
	      }
          //Add 20110708 小濵 End -----
	        return buildPaginatedList(slist);
	    }catch(Exception ex){
	      logger.error("Exception ex");
	      return null;
	    }
	  }

	  /**
	   * 検索条件を設定した SelectQuery を返します。 <BR>
	   *
	   * @param rundata
	   * @param context	 
	   * @return
	   */
	  private SelectQuery getSelectDetailQuery(RunData rundata, Context context) {
	    SelectQuery detailQuery = new SelectQuery(ImwTExtTimecardSystemDetail.class);    
	    EipTExtTimecardSystem record = ExtTimecardUtils.getEipTExtTimecardSystem(
	    		  rundata, context);
	    record.getSystemId();
	    Expression exp2 = ExpressionFactory.matchExp(
	    		ImwTExtTimecardSystemDetail.SYSTEM_ID_COLUMN,record.getSystemId()) ;
	    detailQuery.setQualifier(exp2);
	    
	    
	    return detailQuery;
	    
	  }

	

	private SelectQuery getSelectDetailQueryForSystemDetail(RunData rundata, Context context) {
	    SelectQuery detailQuery = new SelectQuery(ImwTExtTimecardSystemDetail.class);
	    EipTExtTimecardSystem record = ExtTimecardUtils.getEipTExtTimecardSystem(
	    		  rundata, context);
	    record.getSystemId();

	    Expression exp2 = ExpressionFactory.matchExp(
	    		ImwTExtTimecardSystemDetail.SYSTEM_ID_COLUMN,  record.getSystemId());
	    detailQuery.andQualifier(exp2);
	    return detailQuery;
	  }

	  /**
	   * @see com.aimluck.eip.common.ALAbstractSelectData#selectDetail(org.apache.turbine.util.RunData,
	   *      org.apache.velocity.context.Context)
	   */
	  protected Object selectDetail(RunData rundata, Context context) {
	    return ExtTimecardUtils.getImwTExtTimecardSystemDetail(rundata, context);
	  }



	  /**
	   * @see com.aimluck.eip.common.ALAbstractSelectData#getResultDataDetail(java.lang.Object)
	   */
	  protected Object getResultDataDetail(Object obj) {
	    try {
	      ImwTExtTimecardSystemDetail record = (ImwTExtTimecardSystemDetail) obj;
	      ExtTimecardSystemDetailResultData rd = new ExtTimecardSystemDetailResultData();
	      rd.initField();
	      
	      rd.setSystemId(record.getSystemId().intValue());
	      rd.setStartHour(record.getStartHour().intValue());
	      rd.setStartMinute(record.getStartMinute().intValue());
	      rd.setEndHour(record.getEndHour().intValue());
	      rd.setEndMinute(record.getEndMinute().intValue());
	      rd.setWorkstartFlag(record.getWorkstartFlag());
	      rd.setWorkTime(record.getWorktime().intValue());

	      rd.setWorktimeStatus(record.getWorktimeStatus());

	      return rd;
	    } catch (Exception ex) {
	      logger.error("Exception", ex);
	      return null;
	    }
	  }

	  /**
	   * @return
	   * @see com.aimluck.eip.common.ALAbstractSelectData#getColumnMap()
	   */
	  protected Attributes getColumnMap() {
	    Attributes map = new Attributes();
	    map.putValue("system_timesection", ImwTExtTimecardSystemDetail.START_HOUR_PROPERTY);
	    return map;
	  }

	  public int getSystemSum() {
	    return systemSum;
	  }

	  /**
	   *
	   * @return
	   */
	  public Map getPostMap() {
	    return ALEipManager.getInstance().getPostMap();
	  }

	  public List getSystemList() {
	    return ExtTimecardUtils.getAllEipTExtTimecardSystem();
	  }
	  
	  public String getSystemId(){
	    return systemId;
	  }
	  
	  public String setSystemId(String systemId){
	    return this.systemId = systemId;
	  }
	  
	  public boolean doDetailViewList(ALAction action, RunData rundata, Context context) {
		    try {
		      init(action, rundata, context);
		      doCheckAclPermission(rundata, context,
		          ALAccessControlConstants.VALUE_ACL_LIST);
		      action.setMode(ALEipConstants.MODE_LIST);
		      List dList = selectDetailList(rundata, context);
		      if (dList != null) {
		        list = new ArrayList();
		        Object obj = null;
		        int size = dList.size();
		        for (int i = 0; i < size; i++) {
		          obj = getResultData(dList.get(i));
		          if (obj != null) {
		            list.add(obj);
		          }
		        }
		      }
		      action.setResultData(this);
		      action.putData(rundata, context);
		      ALEipUtils.removeTemp(rundata, context, ALEipConstants.ENTITY_ID);
		      return (list != null);
		    } catch (ALPermissionException e) {
		      ALEipUtils.redirectPermissionError(rundata);
		      return false;
		    } catch (ALPageNotFoundException e) {
		      ALEipUtils.redirectPageNotFound(rundata);
		      return false;
		    } catch (ALDBErrorException e) {
		      ALEipUtils.redirectDBError(rundata);
		      return false;
		    }

		  }

	@Override
	protected List selectList(RunData rundata, Context context)
			throws ALPageNotFoundException, ALDBErrorException {
		return null;
	}
	private String getStatus(String str){
		if(str.equals("0")){
			str="所定内（午前）";
		}else if(str.equals("1")){
			str="所定内（午後）";
		}else if(str.equals("2")){
			str="普通残業";
		}else if(str.equals("3")){
			str="深夜残業";
		}
		return str;
	}
	
	@Override
	protected Object getResultData(Object obj) throws ALPageNotFoundException,
			ALDBErrorException {
		 try {
		      ImwTExtTimecardSystemDetail record = (ImwTExtTimecardSystemDetail) obj;
		      ExtTimecardSystemDetailMapResultData rd = new ExtTimecardSystemDetailMapResultData();
		      rd.initField();
		      rd.setSystemDetailId(record.getDetailId().intValue());
		      
		      rd.setStartHour((record.getStartHour() < 10 ?  "0"+record.getStartHour():record.getStartHour()).toString());
		      rd.setStartMinute((record.getStartMinute() < 10 ? "0"+record.getStartMinute():record.getStartMinute()).toString());
		      rd.setEndHour((record.getEndHour() < 10 ? "0"+record.getEndHour():record.getEndHour()).toString());
		      rd.setEndMinute((record.getEndMinute() < 10 ? "0"+record.getEndMinute():record.getEndMinute()).toString());
		      int workTime = record.getWorktime();
		      /* Updata 2011/03/06 IMTT 武 Start */
		      float workTimeD = workTime / 60f;
			  BigDecimal bd  = new BigDecimal(workTimeD);
			  float b = bd.setScale(1,bd.ROUND_HALF_UP).floatValue();
			  rd.setWork_hour(b + "");
			  /* Updata 2011/03/06 IMTT 武 End */
		      rd.setWorkstartFlag(record.getWorkstartFlag());
		      if(record.getWorktimeStatus() != null){
		        rd.setWorktimeStatus(getStatus(record.getWorktimeStatus()));
		      }
		      return rd;
		    } catch (Exception ex) {
		      logger.error("Exception", ex);
		      return null;
		    }
		 
		
	}
	
	  /**
	   * 一覧データを取得します。
	   * 
	   * @return
	   */
	  public ArrayList getList() {
	    return list;
	  }

    public String getSystemName() {
      return systemName;
    }

    public void setSystemName(String systemName) {
      this.systemName = systemName;
    }
	  
	  
}











