/*
 * Aipo is a groupware program developed by Aimluck,Inc.
 * Copyright (C) 2004-2008 Aimluck,Inc.
 * http://aipostyle.com/
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.aimluck.eip.exttimecard;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jp.co.imtt.businesssystem.util.BusinessSystemUtils;

import org.apache.cayenne.DataRow;
import org.apache.cayenne.access.DataContext;
import org.apache.cayenne.exp.Expression;
import org.apache.cayenne.exp.ExpressionFactory;
import org.apache.cayenne.query.SQLTemplate;
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.commons.field.ALDateTimeField;
import com.aimluck.commons.field.ALNumberField;
import com.aimluck.commons.field.ALStringField;
import com.aimluck.eip.cayenne.om.portlet.EipTExtTimecard;
import com.aimluck.eip.cayenne.om.portlet.EipTExtTimecardSystem;
import com.aimluck.eip.cayenne.om.portlet.ImwTExtTimecardDetail;
import com.aimluck.eip.cayenne.om.portlet.ImwTExtTimecardSystemDetail;
import com.aimluck.eip.common.ALAbstractFormData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALPageNotFoundException;
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.util.ALEipUtils;

/**
 * タイムカード集計のフォームデータを管理するためのクラスです。 <br />
 * 
 */
@SuppressWarnings({"unchecked","deprecation","unused"})
public class ExtTimecardWorkFormData extends ALAbstractFormData {

  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(ExtTimecardSystemFormData.class.getName());

  private DataContext dataContext;
  
  /** Add 2010/08/23 チョホン　Start--- */
  private static final String ENCORDE_CONFIRM_CHARTYPE = "shift_jis";
  /** Add 2010/08/23 チョホン　End--- */

  /** Add 2010/08/14 チョホン　Start-- */
  /** タイムカード明細ＩＤ */
  private ALNumberField detail_id;
  
  /** タイムカードＩＤ */
  private ALNumberField timecard_id;
  
  /** 受注情報ＩＤ */
  private ALNumberField job_order_id;
  
  /** 作業区分 */
  private ALStringField work_class;
  
  /** 時間内作業時間（分） */
  private ALNumberField worktime_in;
  
  /** 時間外作業時間（分） */
  private ALNumberField worktime_out;
  
  /** 作業場所 */
  private ALStringField work_place;
  
  /** 作業内容 */
  private ALStringField work_detail;
  
  /** 有効/無効 */
  private ALStringField disabled;
  
  /** 件名 */
  private ALStringField job_order_name;
  
  /** システム区分１ */
  private ALStringField system_class1;
  
  /** システム区分2 */
  private ALStringField system_class2;
  
  /** 親汎用ＩＤ */
  private ALNumberField parent_hanyo_id;
  
  /** 汎用名 */
  private ALStringField hanyokubunnm;
  
  /** 日付 */
  private ALStringField punch_date;
  
  private ALStringField clock_in_time;
  
  private ALStringField clock_out_time;
    
  /** 納期 */
  private ALStringField period; 
  
  /** 顧客ＩＤ */
  private ALNumberField client_id;
  
  /** 顧客名 */
  private ALStringField client_name;
  
  private ALStringField systemTime;
  private ALStringField systemTime2;
  
  private ArrayList jobOrderNameList;
  
  private ArrayList workClassList;
  
  private ArrayList workPlaceList;
  
  private ArrayList clientList;
  
  private ArrayList systemClass1List;
  
  private ArrayList systemClass2List;
  
  private ArrayList periodList;
  
  /** Add 2010/08/14 チョホン　End-- */
  
  private ALStringField dateTime;
    
  /** Add 2010/08/23 チョホン　Start--- */
  private ALNumberField worktime_minute;
  /** Add 2010/08/23 チョホン　End--- */
  
  /** Add 2010/08/25 小濵　Start--- */
  /** <code>today</code> 今日 */
  private ALDateTimeField today;
  
  /** <code>viewStart</code> 出勤時刻 */
  private ALDateTimeField workStart;

  /** <code>viewEnd</code> 退勤時刻 */
  private ALDateTimeField workEnd;
  /** Add 2010/08/25 小濵　End--- */  
  
  /** Add 2011/01/26 王志禹　Start--- */  
  private String target_user_id;
  /** Add 2011/01/26 王志禹　End--- */  
  
  private String job = null;

  /** Add 20110916 小濵 Start --- */
  /** <code>worktimeIn</code> 所定内時間 */
  private double worktimeIn_usually;

  /** <code>worktimeOut_usually</code> 所定外時間(普通) */
  private double worktimeOut_usually;

  /** <code>worktimeOut_midnight</code> 所定外字間(深夜) */
  private double worktimeOut_midnight;
  /** Add 20110916 小濵 End   --- */
  
  @Override
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    super.init(action, rundata, context);

    dataContext = DatabaseOrmService.getInstance().getDataContext();
    
    /** Add 2010/08/25 小濵　Start--- */
    // 出勤時刻
    workStart = new ALDateTimeField("HH時mm分");
    // 退勤時刻
    workEnd = new ALDateTimeField("HH時mm分");
    // 今日
    today = new ALDateTimeField("yyyy-MM-dd");
    Calendar to = Calendar.getInstance();
    to.set(Calendar.HOUR_OF_DAY, 0);
    to.set(Calendar.MINUTE, 0);
    today.setValue(to.getTime());
    
    /** Add 2011/01/26 王志禹　Start--- */  
    target_user_id = getTargetUserId(rundata, context);
    /** Add 2011/01/26 王志禹　End--- */  
    

    StringBuffer statement = new StringBuffer();
    statement.append(" SELECT");
    statement.append("      eip_t_ext_timecard.TIMECARD_ID");
    statement.append("     ,eip_t_ext_timecard.USER_ID");    
    statement.append("     ,eip_t_ext_timecard.CLOCK_IN_TIME");
    statement.append("     ,eip_t_ext_timecard.CLOCK_OUT_TIME");
    statement.append("     ,eip_t_ext_timecard.system_id");
    statement.append(" FROM eip_t_ext_timecard");
    statement.append(" WHERE");
    statement.append("      eip_t_ext_timecard.timecard_id ='" + ALEipUtils.getTemp(rundata, context, "timecard_id") + "'");

    String query = statement.toString();
    try {
      DataContext dataContext = DatabaseOrmService.getInstance()
      .getDataContext();
      SQLTemplate rawSelect = new SQLTemplate(EipTExtTimecard.class, query,
          true);
      rawSelect.setFetchingDataRows(true);
      List list = dataContext.performQuery(rawSelect);
      for(int i = 0;i < list.size();i++){
        if(list.get(i) != null){
          workStart.setValue((Date)ALEipUtils.getObjFromDataRow((DataRow)list.get(i),EipTExtTimecard.CLOCK_IN_TIME_COLUMN));
          if((Date)ALEipUtils.getObjFromDataRow((DataRow)list.get(i),EipTExtTimecard.CLOCK_OUT_TIME_COLUMN) == null
              && today.toString().equals(ALEipUtils.getTemp(rundata, context, "view_date"))){
            Calendar cal6;
            cal6 = BusinessSystemUtils.getEndTime(Calendar.getInstance().getTime(), (Integer)ALEipUtils.getObjFromDataRow((DataRow)list.get(i),EipTExtTimecard.USER_ID_COLUMN), (Integer)ALEipUtils.getObjFromDataRow((DataRow)list.get(i),EipTExtTimecard.SYSTEM_ID_COLUMN));
            workEnd.setValue(cal6.getTime());
          }else{
            workEnd.setValue((Date)ALEipUtils.getObjFromDataRow((DataRow)list.get(0),EipTExtTimecard.CLOCK_OUT_TIME_COLUMN));
          }
          /** Add 2010/09/16 小濵　Start --- */
          double[] worktime = getWorktime(workStart, workEnd, (Integer)ALEipUtils.getObjFromDataRow((DataRow)list.get(0),EipTExtTimecard.SYSTEM_ID_COLUMN));
          worktimeIn_usually = worktime[0];
          worktimeOut_usually = worktime[1];
          worktimeOut_midnight = worktime[2];
          /** Add 2010/09/16 小濵　End   --- */
        }
      }
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    /** Add 2010/08/25 小濵　End--- */

  }

  /**
   *
   */
  public void initField() {
      
    /** Add 2010/08/16 チョホン　Start--- */
    
    job_order_id = new ALNumberField();
    job_order_id.setNotNull(true);
    
    work_place = new ALStringField();
    work_place.setNotNull(true);
    
    client_name = new ALStringField();
    
    system_class1 = new ALStringField();
    
    system_class2 = new ALStringField();
    
    period = new ALStringField();
    
    punch_date = new ALStringField();
    
    dateTime = new ALStringField();
    
    work_class = new ALStringField();
    work_class.setNotNull(true);
    
    detail_id = new ALNumberField();
    detail_id.setNotNull(true);
    
    disabled = new ALStringField();
    
    timecard_id = new ALNumberField();
    
    /** Add 2010/08/23 チョホン　Start--- */
    worktime_in = new ALNumberField();
    //worktime_in.setFieldName("時間内作業時間（分）");
    worktime_in.setFieldName("作業時間（所定内）");
    //worktime_in.limitValue(0, 480);
    
    worktime_out = new ALNumberField();
    //worktime_out.setFieldName("時間外作業時間（分）");
    worktime_out.setFieldName("作業時間（所定外）");
    //worktime_out.limitValue(0, 480);
    /** Add 2010/08/23 チョホン　End--- */
    
    work_detail = new ALStringField();
    work_detail.setFieldName("作業内容");
      
    disabled = new ALStringField();
    disabled.setFieldName("有効/無効");
   
    
    clock_in_time = new ALStringField();
    clock_out_time = new ALStringField();
    
    jobOrderNameList = new ArrayList();
    
    workClassList = new ArrayList();
    
    workPlaceList = new ArrayList();
    
    clientList = new ArrayList();
    
    systemClass1List = new ArrayList();
    
    systemClass2List = new ArrayList();
    
    periodList = new ArrayList();
    
    systemTime = new ALStringField();
    systemTime2 = new ALStringField();

    /** Add 2010/08/16 チョホン　End--- */
    
    /** Add 2010/08/23 チョホン　Start--- */
    worktime_minute = new ALNumberField();
    /** Add 2010/08/23 チョホン　End--- */
  }

  @Override
  protected boolean loadFormData(RunData rundata, Context context,
      ArrayList msgList) throws ALPageNotFoundException, ALDBErrorException {
    try {
      /** Update 2010/08/14 チョホン　Start--- */
            
      ImwTExtTimecardDetail record = ExtTimecardUtils.getImwTExtTimecardDetail(
          rundata, context);
      if (record == null){
        return false;
      }
 

      SimpleDateFormat listFormat = new SimpleDateFormat("yyyy-MM-dd");
      Date tempDate = listFormat.parse(ALEipUtils.getTemp(rundata, context, "view_date"));
      
      SimpleDateFormat punchDateFormat = new SimpleDateFormat("yyyy年MM月dd日(EE)");      
      String puchDatedate = punchDateFormat.format(tempDate);
      punch_date.setValue(puchDatedate);
      
//      //
//      SimpleDateFormat systemTimeFormat = new SimpleDateFormat("HH時ss分");
//      EipTExtTimecard eipTExpTimecard = ExtTimecardUtils.getEipTExtTimecardTime(36, "2010-08-19");
//      String tempString1="";
//      if(eipTExpTimecard!=null){
//        if(eipTExpTimecard.getClockInTime()!=null&&eipTExpTimecard.getClockOutTime()!=null){
//          tempString1=systemTimeFormat.format(eipTExpTimecard.getClockInTime())+"  ~  "+systemTimeFormat.format(eipTExpTimecard.getClockOutTime());
//        }
//         
//      }
//      
//      //Calculate  Date
//      CalculateDate calculateDate = new CalculateDate(); 
//      calculateDate.initFile();
//      Date startDate=eipTExpTimecard.getClockInTime();
//      Date endDate=eipTExpTimecard.getCalClockOutTime();
//      ImwTExtTimecardSystemDetail timecardDetail=ExtTimecardUtils.getDetailDate(eipTExpTimecard);
//      if(timecardDetail!=null){
//        if(timecardDetail.getStartHour()!=null&&timecardDetail.getStartMinute()!=null&&timecardDetail.getEndHour()!=null&& timecardDetail.getEndMinute()!=null){
//            Integer startHour=timecardDetail.getStartHour();
//            Integer startMinute=timecardDetail.getStartMinute();
//            Integer endHour=timecardDetail.getEndHour();
//            Integer endMinute=timecardDetail.getEndMinute();
//       
//            Calendar startCalendar=Calendar.getInstance();
//            startCalendar.set(tempDate.getYear(), tempDate.getMonth(), tempDate.getDate(), startHour, startMinute);
//            Date regulationStartTime=startCalendar.getTime();
//            Calendar endCalendar=Calendar.getInstance();
//            endCalendar.set(tempDate.getYear(), tempDate.getMonth(), tempDate.getDate(), endHour, endMinute);
//            Date regulationEndTime=endCalendar.getTime();
//            calculateDate.setAllDateOrTime(startDate, endDate,
//              regulationStartTime, regulationEndTime);
//        }
//    }
//      // 直接作業時間
//      String work_time = calculateDate.getWorkTime();
//      // 時間外普通
//      String ordinary_time = calculateDate.getOrdinaryTime();
//      // 時間外深夜
//      String night_time = calculateDate.getNightTime();
//      
////      "所定内" ＋ （半角スペース） ＋ 作業時間（所定内） ＋ （半角スペース） ＋ "時間" ＋ （全角スペース） × ２                                                                                                         
////      ＋ "普通残業" ＋ （半角スペース） ＋ 作業時間（普通残業） ＋ （半角スペース） ＋ "時間" ＋ （全角スペース） × ２                                                                                                           
////      ＋ "深夜残業" ＋ （半角スペース） ＋ 作業時間（深夜残業） ＋ （半角スペース） ＋ "時間"                                                                                                          
//      
//      
//      String tempString2="所定内 "+work_time+ " 時間　　普通残業 " + ordinary_time+" 時間　　深夜残業 "+night_time+" 時間"; 
//      systemTime.setValue(tempString1);
//      systemTime2.setValue(tempString2);
//      
      
      job_order_id.setValue(record.getJobOrderId());
           
      work_class.setValue(record.getWorkClass());
      work_place.setValue(record.getWorkPlace());
      /** Update 2010/08/22 チョホン Start--- */
      /** Delete 2010/08/25 金廣 Start--- */
      /*
      String jobId = rundata.getParameters().getString("jobId");
      System.out.print(jobId);
      if (jobId != null && !jobId.toString().equals("")) {
        job_order_id.setValue(jobId);
      } else {
        job_order_id.setValue(record.getJobOrderId());
      }
      */
      /** Delete 2010/08/25 金廣 End--- */
      jobOrderNameList.addAll(ExtTimecardUtils.getJobOrderNameList());
//      client_name.setValue(ExtTimecardUtils.getClientList(record.getJobOrderId()));
//      system_class1.setValue(ExtTimecardUtils.getSystemClass1List(record.getJobOrderId()));
//      system_class2.setValue(ExtTimecardUtils.getSystemClass2List(record.getJobOrderId()));
//      Date getPeriodDate = (Date)ExtTimecardUtils.getPeriodList(record.getJobOrderId());
      client_name.setValue(ExtTimecardUtils.getClientList(Integer.valueOf(String.valueOf(job_order_id.getValue()))));
      system_class1.setValue(ExtTimecardUtils.getSystemClass1List(Integer.valueOf(String.valueOf(job_order_id.getValue()))));
      system_class2.setValue(ExtTimecardUtils.getSystemClass2List(Integer.valueOf(String.valueOf(job_order_id.getValue()))));
      Date getPeriodDate = (Date)ExtTimecardUtils.getPeriodList(Integer.valueOf(String.valueOf(job_order_id.getValue())));
 
      /** Update 2010/10/08 金廣 Start--- */
      // 課題64:納期が入力されていない受注が選択された作業入力編集画面を開くと、
      // 作業区分と訪問/来客のリストが表示されない問題の修正 
//      SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日");
//      String periodDate=format.format(getPeriodDate);
//      period.setValue(periodDate);
      if (getPeriodDate != null){
        SimpleDateFormat format=new SimpleDateFormat("yyyy年MM月dd日");
        String periodDate=format.format(getPeriodDate);
        period.setValue(periodDate);
      }
      /** Update 2010/10/08 金廣 End----- */

      workClassList.addAll(ExtTimecardUtils.getWorkClassList());
      workPlaceList.addAll(ExtTimecardUtils.getWorkPlaceList());
       
      /** Update 2010/09/10 金廣　Start---*/
      // 課題31：作業入力の編集画面を開くと、入力した所定外の時間や作業内容が消える問題の対応
      
//      double dworktimein = (double) record.getWorktimeIn();
//      double dhour = (double) 60;
//      double worktimeIn = dworktimein / dhour;
//      Double tempTimeIn = worktimeIn;
//      worktime_in.setValue(tempTimeIn.toString());
//
//      double dworktimeout=(double)record.getWorktimeOut();
//      double worktimeOut=dworktimeout/dhour;
//      Double tempTimeOut=worktimeOut;
//      worktime_out.setValue(tempTimeOut.toString());
         
      double dhour = (double) 60;
      if (record.getWorktimeIn() == null) {
        // 作業時間（所定内）がnullのとき0.0を画面の項目にセット 
        worktime_in.setValue("0.0");
      } else {
        // 作業時間（所定内）がnullでないとき分を時間に直して画面の項目にセット
        double dworktimein = (double) record.getWorktimeIn();     
        double worktimeIn = dworktimein / dhour;
        Double tempTimeIn = worktimeIn;
        worktime_in.setValue(tempTimeIn.toString());
      }
        
      if (record.getWorktimeOut() == null) {
        // 作業時間（所定外）がnullのとき0.0を画面の項目にセット
        worktime_out.setValue("0.0");
      } else {
        // 作業時間（所定外）がnullでないとき分を時間に直して画面の項目にセット
        double dworktimeout = (double) record.getWorktimeOut();
        double worktimeOut = dworktimeout / dhour;
        Double tempTimeOut = worktimeOut;
        worktime_out.setValue(tempTimeOut.toString());
      }
      /** Update 2010/09/10 金廣　End---*/     

//      worktime_out.setValue(record.getWorktimeIn()/60);
//      worktime_out.setValue(record.getWorktimeOut()/60);
      /** Update 2010/08/23 チョホン　End---*/
      work_detail.setValue(record.getWorkDetail());

      /** Update 2010/08/14 チョホン　End--- */
      /** Add 20110922 小濵 Start --- */
      timecard_id.setValue(record.getEipTExtTimecard().getExtTimecardId());
      detail_id.setValue(record.getDetailId());
      /** Add 20110922 小濵 End   --- */
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return true;
  }

  @Override
  protected boolean updateFormData(RunData rundata, Context context,
      ArrayList msgList) throws ALPageNotFoundException, ALDBErrorException {
    try {
      /** Update 2010/08/15 チョホン　Start--- */
      ImwTExtTimecardDetail record = ExtTimecardUtils.getImwTExtTimecardDetail(
          rundata, context);
      if (record == null) {
        return false;
      }
      
      /** Update 2010/08/25 金廣 Start--- */
      /** Update 2010/08/23 チョホン　Start---*/
      //record.setJobOrderId(Integer.valueOf(String.valueOf(job_order_id.getValueAsString()).substring(String.valueOf(job_order_id.getValueAsString()).length()-1)));
      /** Update 2010/08/23 チョホン　End---*/
      record.setJobOrderId((int)job_order_id.getValue());
      /** Update 2010/08/25 金廣 End--- */
      
      record.setWorkClass(work_class.getValue());
      int worktime = Integer.parseInt(ALEipUtils.getTemp(rundata, context, "timecard_id")); 
//      int worktime = 77; 
      
      
      /** Update 2010/08/23 チョホン　Start--- */
//      int dworktimein = (Integer.valueOf( worktime_in.toString()))* 60;
      /** Update 2010/08/26 小濵　Start--- */
      Double dworktimeminute = Double.valueOf(ExtTimecardUtils.getWorktimeMinute(worktime));
      if(worktime_in != null && !worktime_in.getValueAsString().equals("")){
        Double dworktimein = Double.valueOf(worktime_in.getValueAsString()) * 60;
//      int timeIn = (int)worktime_in.getValue()*60 % ExtTimecardUtils.getWorktimeMinute(worktime);
        double timeIn = dworktimein % dworktimeminute;
        
        if( timeIn != 0 ){
          msgList.add("『 <span class='em'>"+worktime_in.getFieldName()+" 』を"+ExtTimecardUtils.getWorktimeMinute(worktime) +"分単位で入力してください。");
          return false;
        }else{
          record.setWorktimeIn(Integer.valueOf(dworktimein.toString().substring(0, dworktimein.toString().indexOf(".")) ));
        }
      }else{
        record.setWorktimeIn(null);        
      }

      if(worktime_out != null && !worktime_out.getValueAsString().equals("")){
        Double dworktimeout = Double.valueOf(worktime_out.getValueAsString()) * 60;
        double timeOut = dworktimeout % dworktimeminute;
//      int timeOut = (int)worktime_out.getValue()*60 % ExtTimecardUtils.getWorktimeMinute(worktime);
        if(timeOut != 0){
          msgList.add("『 <span class='em'>"+worktime_out.getFieldName()+" 』を"+ExtTimecardUtils.getWorktimeMinute(worktime) +"分単位で入力してください。");
          return false;
        }else{
//        record.setWorktimeOut((int) worktime_out.getValue() * 60);
          record.setWorktimeOut(Integer.valueOf(dworktimeout.toString().substring(0, dworktimeout.toString().indexOf(".")) ));
        }
      }else{
        record.setWorktimeOut(null);
      }
      /** Update 2010/08/26 小濵　End--- */    
      /** Update 2010/08/23 チョホン　End--- */
      //record.setWorktimeIn((int)worktime_in.getValue());
      //record.setWorktimeOut((int)worktime_out.getValue());
      record.setWorkPlace(work_place.getValue());
      record.setWorkDetail(work_detail.getValue());
      
      Date now = new Date();
      //更新日
      record.setUpdateDate(now);
      // 更新者ＩＤ
      record.setUpdateUserId(ALEipUtils.getUserId(rundata));
      
      /** Update 2010/08/15 チョホン　End--- */
      dataContext.commitChanges();

      // 拡張タイムカードの読み込み
      SelectQuery query1 = new SelectQuery(EipTExtTimecard.class);
      Expression exp11 = ExpressionFactory.matchDbExp(EipTExtTimecard.TIMECARD_ID_PK_COLUMN, worktime);
      query1.setQualifier(exp11);   // タイムカードＩＤ
      List eipTExtTimecardList = dataContext.performQuery(query1);
      if (eipTExtTimecardList == null || eipTExtTimecardList.size() <= 0) {
        msgList.add("タイムカードが存在しません。");
        dataContext.rollbackChanges();
        return false;
      } else {
        // レコードが存在する場合
        EipTExtTimecard eipTExtTimecard = (EipTExtTimecard) eipTExtTimecardList.get(0);
        /** Del 20110922 小濵 Start --- */
//        /** Add 2011/02/03 小濵　Start--- */
//        double[] worktime_total = getWorktimeTotal(dataContext,eipTExtTimecard,record.getDetailId());
//        double[] workstart = getLosstime(eipTExtTimecard);
//        
//        SelectQuery query2 = new SelectQuery(ImwTExtTimecardSystemDetail.class);
//        ImwTExtTimecardSystemDetail sysdetail = new ImwTExtTimecardSystemDetail();
//        Expression exp21 = ExpressionFactory.matchDbExp(
//            sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
//        query2.setQualifier(exp21);
//        String[] strin = {"0","1"};
//        Expression exp22 = ExpressionFactory.inExp(
//            ImwTExtTimecardSystemDetail.WORKTIME_STATUS_PROPERTY, strin);
//        query2.andQualifier(exp22);
//        List eipTExtTimecardSystemDetailList = dataContext.performQuery(query2);
//        if(eipTExtTimecardSystemDetailList == null || eipTExtTimecardSystemDetailList.size() <= 0){
//          msgList.add("勤務形態が存在しません。");
//          dataContext.rollbackChanges();
//          return false;
//        }else {
//          double worktimesys_in = 0;
//          for(int i = 0;i < eipTExtTimecardSystemDetailList.size();i++){
//            ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
//              (ImwTExtTimecardSystemDetail) eipTExtTimecardSystemDetailList.get(i);
//            worktimesys_in += imwTExtTimecardSystemDetail.getWorktime();
//          }
//          if((((double)worktimesys_in / 60) - worktime_total[0] - workstart[0]) < Double.valueOf(String.valueOf(worktime_in))){
//              msgList.add("『 <span class='em'>"+worktime_in.getFieldName()+"』の値が大きすぎます。");
//              dataContext.rollbackChanges();
//              return false;
//          }
//        }
//
//        SelectQuery query3 = new SelectQuery(ImwTExtTimecardSystemDetail.class);
//        Expression exp31 = ExpressionFactory.matchDbExp(
//            sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
//        query3.setQualifier(exp31);
//        String[] strout = {"2","3"};
//        Expression exp32 = ExpressionFactory.inExp(
//            ImwTExtTimecardSystemDetail.WORKTIME_STATUS_PROPERTY, strout);
//        query3.andQualifier(exp32);
//        eipTExtTimecardSystemDetailList = dataContext.performQuery(query3);
//        if(eipTExtTimecardSystemDetailList == null || eipTExtTimecardSystemDetailList.size() <= 0){
//          msgList.add("勤務形態が存在しません。");
//          dataContext.rollbackChanges();
//          return false;
//        }else {
//          double worktimesys_out = 0;
//          for(int i = 0;i < eipTExtTimecardSystemDetailList.size();i++){
//            ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
//              (ImwTExtTimecardSystemDetail) eipTExtTimecardSystemDetailList.get(i);
//            worktimesys_out += imwTExtTimecardSystemDetail.getWorktime();
//          }
//          if((((double)worktimesys_out / 60) - worktime_total[1] - workstart[1]) < Double.valueOf(String.valueOf(worktime_out))){
//              msgList.add("『 <span class='em'>"+worktime_out.getFieldName()+"』の値が大きすぎます。");
//              dataContext.rollbackChanges();
//              return false;
//          }
//        }
//        /** Add 2011/02/03 小濵　End--- */
        /** Del 20110922 小濵 End   --- */

        BusinessSystemUtils.setCalClockOutTime(
            eipTExtTimecard.getPunchDate(),
            Integer.valueOf(ALEipUtils.getUserId(rundata)),
            eipTExtTimecard.getSystemId());
      }
      /** Del 20110922 小濵 End   --- */
      
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return true;
  }

  @Override
  protected boolean deleteFormData(RunData rundata, Context context,
      ArrayList msgList) throws ALPageNotFoundException, ALDBErrorException {
   
    return true;
  }

  @Override
  protected boolean insertFormData(RunData rundata, Context context,
      ArrayList msgList) throws ALPageNotFoundException, ALDBErrorException {
    try {
      /** Update 2010/08/14 チョホン　Start--- */
      ImwTExtTimecardDetail record = (ImwTExtTimecardDetail) dataContext
        .createAndRegisterNewObject(ImwTExtTimecardDetail.class);
      record.setJobOrderId((int) job_order_id.getValue());
      record.setWorkClass(work_class.getValue());
      
      /** Update 2010/08/23 チョホン　Start--- */
      int worktime = Integer.parseInt(ALEipUtils.getTemp(rundata, context, "timecard_id")); 
//      int timeIn = (int)worktime_in.getValue()*60 % ExtTimecardUtils.getWorktimeMinute(worktime);
      Double dworktimeminute = Double.valueOf(ExtTimecardUtils.getWorktimeMinute(worktime));
      
      /** Add 2011/01/26 王志禹　Start--- */
      /** Del 2011/02/02 小濵　Start--- */
//    EipTExtTimecardSystem eipTExtTimecardSystem=ExtTimecardUtils.getEipTExtTimecardSystemByUserId(Integer.valueOf("103"));
      /** Del 2011/02/02 小濵　End--- */
      /** Add 2011/01/26 王志禹　End--- */
      
      if(worktime_in != null && !worktime_in.getValueAsString().equals("")){
        Double dworktimein = Double.valueOf(worktime_in.getValueAsString()) * 60;
        double timeIn = dworktimein % dworktimeminute;
        
        if( timeIn != 0 ){
          msgList.add("『 <span class='em'>"+worktime_in.getFieldName()+"』を"+ExtTimecardUtils.getWorktimeMinute(worktime) +"分単位で入力してください。");
          return false;
          /** Del 2011/02/02 小濵　Start--- */
          /** Add 2011/01/26 王志禹　Start--- */
//        }else if(eipTExtTimecardSystem.getWorktimeIn()/60 < Integer.valueOf(String.valueOf(worktime_in))){
//          msgList.add("『 <span class='em'>"+worktime_in.getFieldName()+"』は勤務時間より小さいな時間を入力してください。");
          /** Add 2011/01/26 王志禹　End--- */
//          return false;
          /** Del 2011/02/02 小濵　End--- */     
        }else{
          record.setWorktimeIn(Integer.valueOf(dworktimein.toString().substring(0, dworktimein.toString().indexOf(".")) ));
//        record.setWorktimeIn((int) worktime_in.getValue() * 60);
        }
      }else{
        record.setWorktimeIn(null);
      }
//      int timeOut = (int)worktime_out.getValue()*60 % ExtTimecardUtils.getWorktimeMinute(worktime);
      if(worktime_out != null && !worktime_out.getValueAsString().equals("")){
        Double dworktimeout = Double.valueOf(worktime_out.getValueAsString()) * 60;
        double timeOut = dworktimeout % dworktimeminute;
        if(timeOut != 0){
          msgList.add("『 <span class='em'>"+worktime_out.getFieldName()+" 』を"+ExtTimecardUtils.getWorktimeMinute(worktime) +"分単位で入力してください。");
          return false;
          /** Del 2011/02/02 小濵　Start--- */
          /** Add 2011/01/26 王志禹　Start--- */
//        }else if(eipTExtTimecardSystem.getWorktimeOut()/60 < Integer.valueOf(String.valueOf(worktime_out))){
//          msgList.add("『 <span class='em'>"+worktime_out.getFieldName()+"』は勤務時間より小さいな時間を入力してください。");
          /** Add 2011/01/26 王志禹　End--- */
//          return false;
          /** Del 2011/02/02 小濵　End--- */
        }else{
          record.setWorktimeOut(Integer.valueOf(dworktimeout.toString().substring(0, dworktimeout.toString().indexOf(".")) ));
//        record.setWorktimeOut((int) worktime_out.getValue() * 60);
        }
      }else{
        record.setWorktimeOut(null);       
      }
      /** Update 2010/08/26 小濵　End--- */

      // 拡張タイムカードの読み込み
      SelectQuery query1 = new SelectQuery(EipTExtTimecard.class);
      Expression exp11 = ExpressionFactory.matchDbExp(EipTExtTimecard.TIMECARD_ID_PK_COLUMN, worktime);
      query1.setQualifier(exp11);   // タイムカードＩＤ
      List eipTExtTimecardList = dataContext.performQuery(query1);
      if (eipTExtTimecardList == null || eipTExtTimecardList.size() <= 0) {
        msgList.add("タイムカードが存在しません。");
        dataContext.rollbackChanges();
        return false;
      } else {
        // レコードが存在する場合
        EipTExtTimecard eipTExtTimecard = (EipTExtTimecard) eipTExtTimecardList.get(0);
      
        /** Del 20110922 小濵 Start --- */
//        /** Add 2011/02/02 小濵　Start--- */
//        double[] worktime_total = getWorktimeTotal(dataContext,eipTExtTimecard,null);
//        double[] workstart = getLosstime(eipTExtTimecard);
//        
//        SelectQuery query2 = new SelectQuery(ImwTExtTimecardSystemDetail.class);
//        ImwTExtTimecardSystemDetail sysdetail = new ImwTExtTimecardSystemDetail();
//        Expression exp21 = ExpressionFactory.matchDbExp(
//            sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
//        query2.setQualifier(exp21);
//        String[] strin = {"0","1"};
//        Expression exp22 = ExpressionFactory.inExp(
//            ImwTExtTimecardSystemDetail.WORKTIME_STATUS_PROPERTY, strin);
//        query2.andQualifier(exp22);
//        List eipTExtTimecardSystemDetailList = dataContext.performQuery(query2);
//        if(eipTExtTimecardSystemDetailList == null || eipTExtTimecardSystemDetailList.size() <= 0){
//          msgList.add("勤務形態が存在しません。");
//          dataContext.rollbackChanges();
//          return false;
//        }else {
//          double worktimesys_in = 0;
//          for(int i = 0;i < eipTExtTimecardSystemDetailList.size();i++){
//            ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
//              (ImwTExtTimecardSystemDetail) eipTExtTimecardSystemDetailList.get(i);
//            worktimesys_in += imwTExtTimecardSystemDetail.getWorktime();
//          }
//          if((((double)worktimesys_in / 60) - worktime_total[0] - workstart[0]) < Double.valueOf(String.valueOf(worktime_in))){
//              msgList.add("『 <span class='em'>"+worktime_in.getFieldName()+"』の値が大きすぎます。");
//              dataContext.rollbackChanges();
//              return false;
//          }
//        }
//
//        SelectQuery query3 = new SelectQuery(ImwTExtTimecardSystemDetail.class);
//        Expression exp31 = ExpressionFactory.matchDbExp(
//            sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
//        query3.setQualifier(exp31);
//        String[] strout = {"2","3"};
//        Expression exp32 = ExpressionFactory.inExp(
//            ImwTExtTimecardSystemDetail.WORKTIME_STATUS_PROPERTY, strout);
//        query3.andQualifier(exp32);
//        eipTExtTimecardSystemDetailList = dataContext.performQuery(query3);
//        if(eipTExtTimecardSystemDetailList == null || eipTExtTimecardSystemDetailList.size() <= 0){
//          msgList.add("勤務形態が存在しません。");
//          dataContext.rollbackChanges();
//          return false;
//        }else {
//          double worktimesys_out = 0;
//          for(int i = 0;i < eipTExtTimecardSystemDetailList.size();i++){
//            ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
//              (ImwTExtTimecardSystemDetail) eipTExtTimecardSystemDetailList.get(i);
//            worktimesys_out += imwTExtTimecardSystemDetail.getWorktime();
//          }
//          if((((double)worktimesys_out / 60) - worktime_total[1] - workstart[1]) < Double.valueOf(String.valueOf(worktime_out))){
//              msgList.add("『 <span class='em'>"+worktime_out.getFieldName()+"』の値が大きすぎます。");
//              dataContext.rollbackChanges();
//              return false;
//          }
//        }
//        /** Add 2011/02/02 小濵　End--- */
        /** Del 20110922 小濵 End   --- */
        /** Update 2010/08/23 チョホン　End--- */
        record.setEipTExtTimecard(eipTExtTimecard);
        record.setWorkPlace(work_place.getValue());
        record.setWorkDetail(work_detail.getValue());
        
        record.setDisabled("F");
        
        Date now = new Date();
        // 作成日
        record.setCreateDate(now);
        // 更新日
        record.setUpdateDate(now);
        // 作成者ＩＤ
        record.setCreateUserId(ALEipUtils.getUserId(rundata));
        // 更新者ＩＤ
        record.setUpdateUserId(ALEipUtils.getUserId(rundata));
        
        dataContext.commitChanges();

        BusinessSystemUtils.setCalClockOutTime(
            eipTExtTimecard.getPunchDate(),
            Integer.valueOf(ALEipUtils.getUserId(rundata)),
            eipTExtTimecard.getSystemId());
      }
        
    } catch (Exception ex) {
      logger.error("Exception", ex);
      dataContext.rollbackChanges();
      return false;
    }
    return true;
    /** Update 2010/08/14 チョホン　End--- */
  }

  protected boolean setFormData(RunData rundata, Context context,
      ArrayList msgList) throws ALPageNotFoundException, ALDBErrorException {
    boolean res = super.setFormData(rundata, context, msgList);
    try {
      if (res) {
          /** Update 2010/08/14 チョホン　Start--- */
 
          jobOrderNameList.addAll(ExtTimecardUtils.getJobOrderNameList());
          workClassList.addAll(ExtTimecardUtils.getWorkClassList());
          workPlaceList.addAll(ExtTimecardUtils.getWorkPlaceList());
          SimpleDateFormat listFormat = new SimpleDateFormat("yyyy-MM-dd");
          Date tempDate = listFormat.parse(ALEipUtils.getTemp(rundata, context, "view_date"));
          
          SimpleDateFormat punchDateFormat = new SimpleDateFormat("yyyy年MM月dd日(EE)");      
          String puchDatedate = punchDateFormat.format(tempDate);
          punch_date.setValue(puchDatedate);
          
          /** Update 2010/10/06 金廣 Start--- */
          // 課題56 作業時間が空欄の場合、月報が正常に表示されない問題の対応
          // 作業時間が空欄の場合、0をセットしておく
          // （初期表示時は値がnull、編集画面で空欄にした場合は値が""になる。）
          if ("".equals(worktime_in.getValueAsString())){
            worktime_in.setValue(0);
          }
          if ("".equals(worktime_out.getValueAsString())){
            worktime_out.setValue(0);
          }
          /** Update 2010/10/06 金廣 End----- */
          
//          //Date date = new Date();
//          Date tempDate = getDate;
//          SimpleDateFormat systemTimeFormat = new SimpleDateFormat("HH時ss分");
//          EipTExtTimecard eipTExpTimecard = ExtTimecardUtils.getEipTExtTimecardTime(36, "2010-08-19");
//          String tempString1="";
//          if(eipTExpTimecard!=null){
//            if(eipTExpTimecard.getClockInTime()!=null&&eipTExpTimecard.getClockOutTime()!=null){
//              tempString1=systemTimeFormat.format(eipTExpTimecard.getClockInTime())+"  ~  "+systemTimeFormat.format(eipTExpTimecard.getClockOutTime());
//            }
//             
//          }
//          
//          
//         
//          //Calculate  Date
//          CalculateDate calculateDate = new CalculateDate(); 
//          calculateDate.initFile();
//          Date startDate=eipTExpTimecard.getClockInTime();
//          Date endDate=eipTExpTimecard.getCalClockOutTime();
//          ImwTExtTimecardSystemDetail timecardDetail=ExtTimecardUtils.getDetailDate(eipTExpTimecard);
//          if(timecardDetail!=null){
//            if(timecardDetail.getStartHour()!=null&&timecardDetail.getStartMinute()!=null&&timecardDetail.getEndHour()!=null&& timecardDetail.getEndMinute()!=null){
//                Integer startHour=timecardDetail.getStartHour();
//                Integer startMinute=timecardDetail.getStartMinute();
//                Integer endHour=timecardDetail.getEndHour();
//                Integer endMinute=timecardDetail.getEndMinute();
//           
//                Calendar startCalendar=Calendar.getInstance();
//                startCalendar.set(tempDate.getYear(), tempDate.getMonth(), tempDate.getDate(), startHour, startMinute);
//                Date regulationStartTime=startCalendar.getTime();
//                Calendar endCalendar=Calendar.getInstance();
//                endCalendar.set(tempDate.getYear(), tempDate.getMonth(), tempDate.getDate(), endHour, endMinute);
//                Date regulationEndTime=endCalendar.getTime();
//                calculateDate.setAllDateOrTime(startDate, endDate,
//                  regulationStartTime, regulationEndTime);
//            }
//        }
//          // 直接作業時間
//          String work_time = calculateDate.getWorkTime();
//          // 時間外普通
//          String ordinary_time = calculateDate.getOrdinaryTime();
//          // 時間外深夜
//          String night_time = calculateDate.getNightTime();
//          
////          "所定内" ＋ （半角スペース） ＋ 作業時間（所定内） ＋ （半角スペース） ＋ "時間" ＋ （全角スペース） × ２                                                                                                         
////          ＋ "普通残業" ＋ （半角スペース） ＋ 作業時間（普通残業） ＋ （半角スペース） ＋ "時間" ＋ （全角スペース） × ２                                                                                                           
////          ＋ "深夜残業" ＋ （半角スペース） ＋ 作業時間（深夜残業） ＋ （半角スペース） ＋ "時間"                                                                                                          
//          
//          
//          String tempString2="所定内 "+work_time+ " 時間　　普通残業 " + ordinary_time+" 時間　　深夜残業 "+night_time+" 時間"; 
//          systemTime.setValue(tempString1);
//          systemTime2.setValue(tempString2);
//          
          /** Update 2010/08/14 チョホン　End--- */
      }
      
      job = rundata.getParameters().getString("job_order_id");
      if(job != null){
        job_order_id.setValue(job);
      }
      /** Add 20110922 小濵 Start --- */
      ImwTExtTimecardDetail record = ExtTimecardUtils.getImwTExtTimecardDetail(
          rundata, context);
      timecard_id.setValue(Integer.parseInt(ALEipUtils.getTemp(rundata, context, "timecard_id")));
      detail_id.setValue(record.getDetailId());
      /** Add 20110922 小濵 End   --- */
    } catch (Exception ex) {
        logger.error("[ExtTimecardSystemFormData]", ex);
    }
    return res;
  }
  
  @Override
  protected void setValidator() throws ALPageNotFoundException,
      ALDBErrorException {
    
    /** Add 2010/08/14 チョホン　Start--- */
    job_order_id.setNotNull(true);
    work_class.setNotNull(true);
    work_place.setNotNull(true);
    /** Update 2010/08/23 チョホン　Start--- */
    //worktime_in.limitValue(0, 480);
    //worktime_out.limitValue(0, 480);
//    worktime_in.limitValue(0, 24);
//    worktime_out.limitValue(0, 24);
    worktime_in.limitValue(0, 24);
    worktime_out.limitValue(0, 24);
    /** Update 2010/08/23 チョホン　End--- */
    /** Add 2010/08/14 チョホン　End--- */
  }

  @Override
  protected boolean validate(ArrayList msgList) throws ALPageNotFoundException,
      ALDBErrorException {
    /** Add 2010/08/14 チョホン　Start--- */
    try {
        /** Update 2010/10/08 金廣 Start--- */
        //  課題23:作業入力検索画面の実装
        //  件名の必須チェックの誤りを修正
//        if (String.valueOf(job_order_id.getValue()) =="" ) {
//          msgList.add("『 <span class='em'>件名</span> 』を選択してください。");
//        }
        if ("".equals(job_order_id.getValueAsString())){
          msgList.add("『 <span class='em'>件名</span> 』を選択してください。");
        }
        /** Update 2010/10/08 金廣 End----- */
        
        if(work_class.getValue().equals("")){
          msgList.add("『 <span class='em'>作業区分</span> 』を選択してください。");
        }
        
        if(work_place.getValue().equals("")){
          msgList.add("『 <span class='em'>訪／来</span> 』を選択してください。");
        }
        
        /** Add 2010/08/23 チョホン　Start--- */
        /** Update 2010/08/26 小濵　Start--- */   
        if(!isNumberValue(String.valueOf(worktime_in))){
          msgList.add("『 <span class='em'>" + worktime_in.getFieldName()
              + "</span> 』に正しい数値を入力してください。");
        }else if(worktime_in != null && !worktime_in.getValueAsString().equals("") && Double.valueOf(worktime_in.getValueAsString())<0){
          msgList.add("『 <span class='em'>" +  worktime_in.getFieldName() + "</span> 』には"
              + 0 + "以上の値を入力してください。");
        }else if(worktime_in != null && !worktime_in.getValueAsString().equals("") && Double.valueOf(worktime_in.getValueAsString())>24){
          msgList.add("『 <span class='em'>" +  worktime_in.getFieldName() + "</span> 』には"
              + 24 + "以下の値を入力してください。");
        }
        
        if(!isNumberValue(String.valueOf(worktime_out))){
          msgList.add("『 <span class='em'>" + worktime_out.getFieldName()
              + "</span> 』に正しい数値を入力してください。");
        }else if(worktime_out != null && !worktime_out.getValueAsString().equals("") && Double.valueOf(worktime_out.getValueAsString())<0){
          msgList.add("『 <span class='em'>" +  worktime_out.getFieldName() + "</span> 』には"
              + 0 + "以上の値を入力してください。");
        }else if(worktime_out != null && !worktime_out.getValueAsString().equals("") && Double.valueOf(worktime_out.getValueAsString())>24){
          msgList.add("『 <span class='em'>" +  worktime_out.getFieldName() + "</span> 』には"
              + 24 + "以下の値を入力してください。");
        }
        /** Update 2010/08/26 小濵　End--- */        
        /** Add 2010/08/23 チョホン　End--- */
        /** Add 20110922 小濵 Start --- */
        // 拡張タイムカードの読み込み
        SelectQuery query1 = new SelectQuery(EipTExtTimecard.class);
        Expression exp11 = ExpressionFactory.matchDbExp(EipTExtTimecard.TIMECARD_ID_PK_COLUMN, timecard_id.getValueAsString());
        query1.setQualifier(exp11);   // タイムカードＩＤ
        List eipTExtTimecardList = dataContext.performQuery(query1);
        if (eipTExtTimecardList == null || eipTExtTimecardList.size() <= 0) {
          msgList.add("タイムカードが存在しません。");
        } else {
          // レコードが存在する場合
          EipTExtTimecard eipTExtTimecard = (EipTExtTimecard) eipTExtTimecardList.get(0);
          double[] worktime_total = getWorktimeTotal(dataContext,eipTExtTimecard,(int)detail_id.getValue());
          double[] workstart = getLosstime(eipTExtTimecard);
          
          SelectQuery query2 = new SelectQuery(ImwTExtTimecardSystemDetail.class);
          ImwTExtTimecardSystemDetail sysdetail = new ImwTExtTimecardSystemDetail();
          Expression exp21 = ExpressionFactory.matchDbExp(
              sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
          query2.setQualifier(exp21);
          String[] strin = {"0","1"};
          Expression exp22 = ExpressionFactory.inExp(
              ImwTExtTimecardSystemDetail.WORKTIME_STATUS_PROPERTY, strin);
          query2.andQualifier(exp22);
          List eipTExtTimecardSystemDetailList = dataContext.performQuery(query2);
          if(eipTExtTimecardSystemDetailList == null || eipTExtTimecardSystemDetailList.size() <= 0){
            msgList.add("勤務形態が存在しません。");
          }else {
            double worktimesys_in = 0;
            for(int i = 0;i < eipTExtTimecardSystemDetailList.size();i++){
              ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
                (ImwTExtTimecardSystemDetail) eipTExtTimecardSystemDetailList.get(i);
              worktimesys_in += imwTExtTimecardSystemDetail.getWorktime();
            }
            if((((double)worktimesys_in / 60) - worktime_total[0] - workstart[0]) < Double.valueOf(String.valueOf(worktime_in))){
                msgList.add("『 <span class='em'>"+worktime_in.getFieldName()+"』の値が大きすぎます。");
            }
          }

          SelectQuery query3 = new SelectQuery(ImwTExtTimecardSystemDetail.class);
          Expression exp31 = ExpressionFactory.matchDbExp(
              sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
          query3.setQualifier(exp31);
          String[] strout = {"2","3"};
          Expression exp32 = ExpressionFactory.inExp(
              ImwTExtTimecardSystemDetail.WORKTIME_STATUS_PROPERTY, strout);
          query3.andQualifier(exp32);
          eipTExtTimecardSystemDetailList = dataContext.performQuery(query3);
          if(eipTExtTimecardSystemDetailList == null || eipTExtTimecardSystemDetailList.size() <= 0){
            msgList.add("勤務形態が存在しません。");
          }else {
            double worktimesys_out = 0;
            for(int i = 0;i < eipTExtTimecardSystemDetailList.size();i++){
              ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
                (ImwTExtTimecardSystemDetail) eipTExtTimecardSystemDetailList.get(i);
              worktimesys_out += imwTExtTimecardSystemDetail.getWorktime();
            }
            if((((double)worktimesys_out / 60) - worktime_total[1] - workstart[1]) < Double.valueOf(String.valueOf(worktime_out))){
                msgList.add("『 <span class='em'>"+worktime_out.getFieldName()+"』の値が大きすぎます。");
            }
          }
        }
        /** Add 20110922 小濵 End   --- */
    } catch(Exception ex){
      logger.error("Exception", ex);
      return false;
    }
    /** Delete 2010/08/23 チョホン　Start--- */
//    worktime_in.validate(msgList);
//    worktime_out.validate(msgList);
    /** Delete 2010/08/23 チョホン　End--- */
    return (msgList.size() == 0);
  }

  /** Add 2010/08/23 チョホン　Start--- */
  /**
   * 入力フィールド値が数字かどうかを判定します。
   * 
   * @return
   */
  protected boolean isNumberValue(String value) {
    if (value == null) {
      return false;
    }

    try {
      byte[] chars;
      int len = value.length();
      for (int i = 0; i < len; i++) {
        chars = (Character.valueOf(value.charAt(i)).toString())
            .getBytes(ENCORDE_CONFIRM_CHARTYPE);
        if (chars.length > 1 || ((chars[0]<48 || chars[0]>57) && chars[0]!=46) ) {
          return false;
        }
      }
    } catch (UnsupportedEncodingException ex) {
      return false;
    }

//    try {
//      Long.valueOf(value);
//    } catch (NumberFormatException ex) {
//      return false;
//    }
    return true;
  }
  /** Add 2010/08/23 チョホン　End--- */
  
  /**
   * 詳細データを取得する抽象メソッドです。
   * 
   * @param rundata
   * @param context
   * @return
   */
  protected Object selectDetail(RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    return null;
  }
  /** Add 2011/01/26 王志禹　Start--- */
  /**
   * 表示切り替えで指定したユーザ ID を取得する．
   *
   * @param rundata
   * @param context
   * @return
   */
  private String getTargetUserId(RunData rundata, Context context) {
    String target_user_id = rundata.getParameters().getString(
          ExtTimecardUtils.TARGET_USER_ID);
    
    return target_user_id;
  }
  /** Add 2011/02/03 小濵　Start--- */
  
  /**
   * 作業時間の合計を取得する。
   *
   * @param datacontext
   * @param eipTExtTimecard
   * @return
   */
  private double[] getWorktimeTotal(DataContext datacontext,EipTExtTimecard eipTExtTimecard,Integer detailId) {
    SelectQuery query = new SelectQuery(ImwTExtTimecardDetail.class);
    ImwTExtTimecardDetail detail = new ImwTExtTimecardDetail();
    Expression exp1 = ExpressionFactory.matchDbExp(
        detail.getEipTExtTimecard().TIMECARD_ID_COLUMN, Integer.valueOf(eipTExtTimecard.getExtTimecardId()));
    query.setQualifier(exp1);
    if(detailId != null && detailId != 0){
      Expression exp2 = ExpressionFactory.noMatchDbExp(
          ImwTExtTimecardDetail.DETAIL_ID_PK_COLUMN, detailId);
      query.andQualifier(exp2);
    }
    List eipTExtTimecardDetailList = dataContext.performQuery(query);

    double worktime_in_total = 0;
    double worktime_out_total = 0;
    for(int i = 0;i < eipTExtTimecardDetailList.size();i++){
      ImwTExtTimecardDetail imwTExtTimecardDetail = 
        (ImwTExtTimecardDetail) eipTExtTimecardDetailList.get(i);
      worktime_in_total += imwTExtTimecardDetail.getWorktimeIn();
      worktime_out_total += imwTExtTimecardDetail.getWorktimeOut();
    }
    worktime_in_total = worktime_in_total / 60;
    worktime_out_total = worktime_out_total / 60;
    double[] returnVal = {worktime_in_total,worktime_out_total};
    
    return returnVal;
  }
  
  /**
   * 出勤時間と業務開始時間の差を取得する。
   *
   * @param datacontext
   * @param eipTExtTimecard
   * @return
   */
  private double[] getLosstime(EipTExtTimecard eipTExtTimecard) {
    DataContext dataContext = DatabaseOrmService.getInstance()
    .getDataContext();
    int start = 0;  //勤務開始時間(分)
    SelectQuery query = new SelectQuery(ImwTExtTimecardSystemDetail.class);
    ImwTExtTimecardSystemDetail sysdetail = new ImwTExtTimecardSystemDetail();
    Expression exp1 = ExpressionFactory.matchDbExp(
        sysdetail.getEipTExtTimecardSystem().SYSTEM_ID_PK_COLUMN, Integer.valueOf(eipTExtTimecard.getSystemId()));
    query.setQualifier(exp1);
    query.addOrdering(ImwTExtTimecardSystemDetail.START_HOUR_PROPERTY,true);
    query.addOrdering(ImwTExtTimecardSystemDetail.START_MINUTE_PROPERTY,true);
    List imwTExtTimecardSystemDetailList = dataContext.performQuery(query);

    //Add 20110616 小濵 Start ---
    EipTExtTimecardSystem sys = ExtTimecardUtils.getEipTExtTimecardSystemByUserId(
        Integer.valueOf(eipTExtTimecard.getSystemId()));
    //Add 20110616 小濵 End -----
    //勤務形態リストを並び替える
    for(int i = 0;i < imwTExtTimecardSystemDetailList.size();i++){
      ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
        (ImwTExtTimecardSystemDetail)imwTExtTimecardSystemDetailList.get(0);
      //Upd 20110616 小濵 Start ---
      //if(!(imwTExtTimecardSystemDetail.getWorkstartFlag().equals("1"))){
      if(!(imwTExtTimecardSystemDetail.getStartHour() >= sys.getChangeHour())){
      //Upd 20110616 小濵 End -----
        imwTExtTimecardSystemDetail.setStartHour(imwTExtTimecardSystemDetail.getStartHour() + 24);
        imwTExtTimecardSystemDetailList.add(imwTExtTimecardSystemDetail);
        imwTExtTimecardSystemDetailList.remove(0);
      }else{
        start = imwTExtTimecardSystemDetail.getStartHour() * 60 
                        + imwTExtTimecardSystemDetail.getStartMinute();
        break;
      }
    }
    
    //出勤時刻を分単位にする
    int workintime = eipTExtTimecard.getClockInTime().getHours() * 60 
                    + eipTExtTimecard.getClockInTime().getMinutes();
    //出勤時刻が日付変更時刻より早い場合、1440分(24時間)足す
    if(workintime < start)
      workintime += 1440;

    double worktime_in_total = 0;
    double worktime_out_total = 0;
    for(int i = 0;i < imwTExtTimecardSystemDetailList.size();i++){
      ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
        (ImwTExtTimecardSystemDetail)imwTExtTimecardSystemDetailList.get(i);
      int worktime_start = imwTExtTimecardSystemDetail.getStartHour() * 60 
                          + imwTExtTimecardSystemDetail.getStartMinute();
      int worktime_end = imwTExtTimecardSystemDetail.getEndHour() * 60 
                          + imwTExtTimecardSystemDetail.getEndMinute();
      
      if(worktime_start < start) worktime_start += 1440;
      if(worktime_end < start) worktime_end += 1440;
      
      if(workintime <= worktime_end){
        if(imwTExtTimecardSystemDetail.getWorktimeStatus().equals("0")
            || imwTExtTimecardSystemDetail.getWorktimeStatus().equals("1")){
          worktime_in_total += workintime - worktime_start;
        }else{
          worktime_out_total += workintime - worktime_start;
        }
        break;
      }else{
        if(imwTExtTimecardSystemDetail.getWorktimeStatus().equals("0")
            || imwTExtTimecardSystemDetail.getWorktimeStatus().equals("1")){
          worktime_in_total += imwTExtTimecardSystemDetail.getWorktime();
        }else{
          worktime_out_total += imwTExtTimecardSystemDetail.getWorktime();
        }
      }
    }

    worktime_in_total = worktime_in_total / 60;
    worktime_out_total = worktime_out_total / 60;
    double[] returnVal = {worktime_in_total,worktime_out_total};
    dataContext.rollbackChanges();  
    return returnVal;
  }

  /** Add 2011/02/03 小濵　End--- */

  /** Add 2011/09/16 小濵 Start --- */
  public double[] getWorktime(ALDateTimeField startTime, ALDateTimeField endTime,Integer systemId){
    //戻り値を初期化する　1つ目:所定内　2つ目:普通残業　3つ目:深夜残業
    double[] retHour = {0,0,0};
    DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();
    SelectQuery query = new SelectQuery(ImwTExtTimecardSystemDetail.class);
    Expression exp1 = ExpressionFactory.matchDbExp(
        ImwTExtTimecardSystemDetail.SYSTEM_ID_COLUMN,systemId);
    query.setQualifier(exp1);
    query.addOrdering(ImwTExtTimecardSystemDetail.START_HOUR_PROPERTY,true);
    query.addOrdering(ImwTExtTimecardSystemDetail.START_MINUTE_PROPERTY,true);
    List list = dataContext.performQuery(query);
    if(list == null ||list.size() == 0){
      return retHour;
    }
    EipTExtTimecardSystem sys = ExtTimecardUtils.getEipTExtTimecardSystemByUserId(
        systemId);
    for(int i = 0;i < list.size();i++){
      ImwTExtTimecardSystemDetail imwTExtTimecardSystemDetail = 
        (ImwTExtTimecardSystemDetail)list.get(0);
      if(!(imwTExtTimecardSystemDetail.getStartHour() >= sys.getChangeHour())){
        list.add(imwTExtTimecardSystemDetail);
        list.remove(0);
      }else{
        break;
      }
    }
    //出勤時刻を分に変換
    int startMinute = (Integer.parseInt(startTime.getHour()) * 60) 
      + Integer.parseInt(startTime.getMinute());
    if(!(Integer.parseInt(startTime.getHour()) >= sys.getChangeHour()))
        startMinute += (24 * 60);
    //出勤時刻を分に変換
    int endMinute = (Integer.parseInt(endTime.getHour()) * 60) 
      + Integer.parseInt(endTime.getMinute());
    if(!(Integer.parseInt(endTime.getHour()) >= sys.getChangeHour()))
      endMinute += (24 * 60);
    for(int i = 0;i < list.size();i++){
      ImwTExtTimecardSystemDetail obj = (ImwTExtTimecardSystemDetail)list.get(i);
      int minute = obj.getWorktime();
      //対象の勤務形態明細の作業開始時刻を分に変換
      int sysStartMinute = (obj.getStartHour() * 60) + obj.getStartMinute();
      if(!(obj.getStartHour() >= sys.getChangeHour()))
        sysStartMinute += (24 * 60);
      //対象の勤務形態明細の作業終了時刻を分に変換
      int sysEndMinute = (obj.getEndHour() * 60) + obj.getEndMinute();
      if(!(obj.getEndHour() >= sys.getChangeHour()))
        sysEndMinute += (24 * 60);
      if(sysEndMinute <= startMinute){
        continue;
      }
      if(sysStartMinute >= endMinute){
        break;
      }
      if(startMinute > sysStartMinute){
        minute -= (startMinute - sysStartMinute);
      }
      if(endMinute < sysEndMinute){
        minute -= (sysEndMinute - endMinute);
      }
      
      switch(Integer.parseInt(obj.getWorktimeStatus())){
        case 0:
        case 1:
          retHour[0] += minute;
          break;
        
        case 2:
          retHour[1] += minute;
          break;
          
        case 3:
          retHour[2] += minute;
          break;
          
        default:
      }
    }
    retHour[0] /= 60;
    retHour[1] /= 60;
    retHour[2] /= 60;
    
    return retHour;
  }
  /** Add 2010/09/16 小濵 End   --- */

  /** Add 2010/08/14 チョホン　Start--- */
  
  /**
   * 
   * @return
   */
  public ALNumberField getDetailId() {
    return detail_id;
  }
  
  /**
   * 
   * @return
   */
  public ALNumberField getTimeardId() {
    return timecard_id;
  }
  
  /**
   * 
   * @return
   */
  public ALNumberField getJobOrderId() {
    return job_order_id;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getWorkClass() {
    return work_class;
  }
  
  /**
   * 
   * @return
   */
  public ALNumberField getWorktimeIn() {
    return worktime_in;
  }
  
  /**
   * 
   * @return
   */
  public ALNumberField getWorktimeOut() {
    return worktime_out;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getWorkPlace() {
    return work_place;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getWorkDetail() {
    return work_detail;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getJobOrderName() {
    return job_order_name;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getSystemClass1() {
    return system_class1;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getSystemClass2() {
    return system_class2;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getHanyokubunnm() {
    return hanyokubunnm;
  }
    
  /**
   * 
   * @return
   */
  public ALStringField getPeriod() {
    return period;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getClientName() {
    return client_name;
  }
  
  /**
   * 
   * @return
   */
  public ALNumberField getParentHanyoId() {
    return parent_hanyo_id;
  }

  /**
   * 
   * @return
   */
  public ALNumberField getClientId() {
    return client_id;
  }
  
  
  /**
   * 
   * @return
   */
  public ALStringField getDateTime() {
    return dateTime;
  }
  
  
  public ALStringField getClockInTime() {
    return clock_in_time;
  }
  
  public ALStringField getClockOutTime() {
    return clock_out_time;
  }
  /**
   * 
   * @return
   */
  public ALStringField getPunchDate() {
    return punch_date;
  }
  
  public ALStringField getSystemTime(){
    return systemTime;
  }
  public ALStringField getSystemTime2(){
    return systemTime2;
  }
  
  /**
   * 
   * @return
   */
  public ALStringField getDisabled() {
    return disabled;
  }
  
  public List getJobOrderNameList() {
    return jobOrderNameList;
  }
  
  public List getWorkClassList() {
    return workClassList;
  }
  
  public List getWorkPlaceList() {
    return workPlaceList;
  }
  
  public List getClientList() {
    return clientList;
  }
  
  public List getSystemClass1List() {
    return systemClass1List;
  }
  
  public List getSystemClass2List() {
    return systemClass2List;
  }
  
  public List getPeriodList(){
    return periodList;
  }
  
  /** Add 2010/08/14 チョホン　End--- */

  /** Add 2010/08/23 チョホン　Start--- */
  public ALNumberField getWorktimeMinute(){
    return worktime_minute;
  }
  /** Add 2010/08/23 チョホン End--- */

  /** Add 2010/08/25 小濵　Start--- */
  /**
   * 出勤時刻を取得します。
   *
   * @return
   */
  public ALDateTimeField getWorkStart() {
    return workStart;
  }

  /**
   * 退勤時刻を取得します。
   *
   * @return
   */
  public ALDateTimeField getWorkEnd() {
    return workEnd;
  }
  /** Add 2010/08/25 小濵　End--- */

  /** Add 20110916 小濵 Start --- */
  /**
   * 所定内時間を取得します。
   *
   * @return
   */
  public double getWorktimeIn_usually() {
    return worktimeIn_usually;
  }

  /**
   * 普通残業時間を取得します。
   *
   * @return
   */
  public double getWorktimeOut_usually() {
    return worktimeOut_usually;
  }

  /**
   * 深夜残業時間を取得します。
   *
   * @return
   */
  public double getWorktimeOut_midnight() {
    return worktimeOut_midnight;
  }
  /** Add 20110916 小濵 End   --- */


}
