/*
 * 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.cashflow;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.cayenne.DataObjectUtils;
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.commons.field.ALDateField;
import com.aimluck.commons.field.ALDateTimeField;
import com.aimluck.commons.field.ALNumberField;
import com.aimluck.commons.field.ALStringField;
import com.aimluck.commons.utils.ALDateUtil;

import com.aimluck.eip.cayenne.om.portlet.EipTTodoCategory;

import com.aimluck.eip.cayenne.om.portlet.ImwMClient;
import com.aimluck.eip.cayenne.om.portlet.ImwMHanyo;
import com.aimluck.eip.cayenne.om.portlet.ImwMItem;
import com.aimluck.eip.cayenne.om.portlet.ImwMItemCategory;
import com.aimluck.eip.cayenne.om.portlet.ImwMItemSubcategory;
import com.aimluck.eip.cayenne.om.portlet.ImwTAccount;
import com.aimluck.eip.cayenne.om.portlet.ImwTAccountPlan;
import com.aimluck.eip.common.ALAbstractFormData;
import com.aimluck.eip.common.ALDBErrorException;
import com.aimluck.eip.common.ALPageNotFoundException;
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.services.eventlog.ALEventlogConstants;
import com.aimluck.eip.services.eventlog.ALEventlogFactoryService;
import com.aimluck.eip.cashflow.util.AccountPlanUtils;
import com.aimluck.eip.util.ALEipUtils;

/**
 * 支払情報のフォームデータを管理するクラスです。 <BR>
 * 
 */
public class AccountPlanFormData extends ALAbstractFormData {
  /** logger */
  private static final JetspeedLogger logger = JetspeedLogFactoryService
      .getLogger(AccountPlanFormData.class.getName());
  
  /** 入出金予定ID */
  private ALNumberField account_plan_id;
  
  /** 入出金区分 */
  private ALNumberField account_class;
  
  /** カテゴリID */
  private ALNumberField category_id;
  
  /** サブカテゴリID */
  private ALNumberField subCategory_id;

  /** 科目 */
  private ALNumberField item_id;
  private ALStringField item_name;

  /** 取引先 */
  private ALNumberField client_id;
  private ALStringField client_name;
  
  /** 取引先支払入金区分 */
  private ALStringField client_pay_class;
  
  /** 手形番号 */
  private ALStringField draft_number;
  
  /** 振出人 */
  private ALNumberField remitter;
  private ALStringField remitter_name;
  
  /**　振出日 */
  private ALDateField remittance_date;
  
  /**　受取日 */
  private ALDateField receipt_date; 
  
  /**　支払場所銀行名 */
  private ALStringField pay_bank_name;
  
  /**　支払場所支店名 */
  private ALStringField pay_bank_branch_name;
  
  /** 請求日 */
  private ALDateField billing_date;

  /**　手形取立預け銀行名 */
  private ALStringField charge_bank_name;
  
  /**　手形取立預け支店名 */
  private ALStringField charge_bank_branch_name;
  
  /**　手形取立預け金額 */
  private ALNumberField charge_money;
  
  /** 手形取立預け日 */
  private ALDateField charge_date;
  
  /**　手形取立預け手数料 */
  private ALNumberField charge_handling;
  
  /** 現金出金日 */
  private ALDateField cash_account_date;
  
  /**　出金日 */
  private ALDateField account_date;

  /** 金額 */
  private ALNumberField price;
 
  /** 摘要 */
  private ALStringField note;
  
  /** 確定フラグ */
  private ALNumberField decide_flag;
  
  /** カテゴリリスト */
  private List categoryList;

//  /** サブカテゴリリスト */
//  private List subCategoryList;
  
  /** 科目リスト */
  private ArrayList itemList = null;
  
  /** 取引先リスト */
  private ArrayList clientList;
  
  /** 入出金予定リスト */
  private ArrayList accountPlanList;
  
  private DataContext dataContext;

  //private ImwTAccountPlan accountPlan;
   
  //private ImwMItem item;
  
  //private ImwMClient client;
  
  /** ログインユーザーのID * */
  private int user_id;

  /** ACL用の変数 * */
  private String aclPortletFeature;
  
  /** 現在のモード */
  private String mode;
  
  /** タイプ(seikyu/shiharai */
  private String type;

  /** 予定/実績 */
  private String yojitsu;
  
  /**
   * 
   * @param action
   * @param rundata
   * @param context
   * @see com.aimluck.eip.common.ALAbstractFormData#init(com.aimluck.eip.modules.actions.common.ALAction,
   *      org.apache.turbine.util.RunData, org.apache.velocity.context.Context)
   */
  public void init(ALAction action, RunData rundata, Context context)
      throws ALPageNotFoundException, ALDBErrorException {
    super.init(action, rundata, context);

    user_id = ALEipUtils.getUserId(rundata);

    dataContext = DatabaseOrmService.getInstance().getDataContext();
    aclPortletFeature = ALAccessControlConstants.POERTLET_CASHFLOW;    
  }

  /**
   * 各フィールドを初期化します。 <BR>
   * 
   * @see com.aimluck.eip.common.ALData#initField()
   */
  public void initField() {
    // 入出金区分
    account_class = new ALNumberField();
    
    category_id = new ALNumberField();
    category_id.setFieldName("カテゴリID");
    
    subCategory_id = new ALNumberField();
    subCategory_id.setFieldName("サブカテゴリID");
    
    // 科目
    item_id = new ALNumberField();
    item_id.setFieldName("科目");
    // 取引先
    client_id = new ALNumberField();
    client_id.setFieldName("取引先");
    
    client_name = new ALStringField();
    client_name.setFieldName("取引先名");
    
    // 取引先支払入金区分
    client_pay_class = new ALStringField();
    client_pay_class.setFieldName("取引先入出金区分");
    // 手形番号
    draft_number = new ALStringField();
    draft_number.setFieldName("手形番号");
    // 振出人
    remitter = new ALNumberField();
    remitter.setFieldName("振出人ID");
    remitter_name = new ALStringField();
    remitter_name.setFieldName("振出人名");
    // 振出日
    remittance_date = new ALDateField();
    remittance_date.setFieldName("振出日");
    //remittance_date.setValue(new Date());
    // 受取日
    receipt_date = new ALDateField();
    receipt_date.setFieldName("受取日");
    receipt_date.setValue(new Date());
    // 支払場所銀行名
    pay_bank_name = new ALStringField();
    pay_bank_name.setFieldName("支払場所銀行名");
    // 支払場所支店名
    pay_bank_branch_name = new ALStringField();
    pay_bank_branch_name.setFieldName("支払場所支店名");
    // 請求日
    billing_date = new ALDateField();
    billing_date.setFieldName("請求日");
    // 手形取立預け銀行名
    charge_bank_name = new ALStringField();
    charge_bank_name.setFieldName("手形取立預け銀行名");
    // 手形取立預け支店名
    charge_bank_branch_name = new ALStringField();
    charge_bank_branch_name.setFieldName("手形取立預け支店名");
    // 手形取立預け金額
    charge_money = new ALNumberField();
    charge_money.setFieldName("手形取立預け金額");
    // 手形取立預け日
    charge_date = new ALDateField();
    charge_date.setFieldName("手形取立預け日");
    //charge_date.setValue(new Date());
    // 手形取立預け手数料
    charge_handling = new ALNumberField();
    charge_handling.setFieldName("手形取立預け手数料");
    // 入出金日
    account_date = new ALDateField();
    account_date.setFieldName("入出金日");
    // 現金出金日
    cash_account_date = new ALDateField();
    // 金額
    price = new ALNumberField();
    price.setFieldName("金額");
    // 摘要
    note = new ALStringField();
    note.setFieldName("摘要");
    note.setTrim(false);
    
    // 確定フラグ
    decide_flag = new ALNumberField();
    decide_flag.setFieldName("確定フラグ");
    
    //＄＄
    //type = new ALStringField();
    type = "shiharai";
    yojitsu = "yotei";
        
    SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");
    Calendar rightNow = Calendar.getInstance();
    String tempPassDate = df.format(rightNow.getTime());
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
    Date date = null;
    try {
      date = format.parse(tempPassDate);
    } catch (ParseException e) {
    }
    ALDateTimeField tmpDate = new ALDateTimeField("yyyy/MM/dd");
    tmpDate.setValue(date);
    cash_account_date.setValue(tmpDate.getValue());

 }
 
  /**
   * テンプレートを渡す
   * 
   * @param num
   * @return
   */
  public String categoryTemplate(int num) {
    for (Object o : categoryList) {
      AccountPlanResultData tmp = (AccountPlanResultData) o;
      if (tmp.getCategoryId().getValue() == num) {
        return tmp.getOrderTemplate().getValue();
      }
    }
    return "";
  }
    
  /**
   * 
   * @param rundata
   * @param context
   */
  public void loadCategoryList(RunData rundata, Context context) {
    categoryList = AccountPlanUtils.loadCategoryList(rundata, context);
  }
  
  /**
   * 
   * @param catId
   */
  public List getSubCategoryList(int catId) {
    for(Object catObj : this.getCategoryList()){
      ImwMItemCategory cat = (ImwMItemCategory)catObj;
      if(cat.getItemCategoryId() == catId)
      {
        return cat.getImwMItemSubcategory();
      }
    }
    
    return new ArrayList();
  }

  /**
   * 
   * @param catId
   */
  public List getItemList(int catId, int subcatId) {
    if(subcatId < 0){
      for(Object catObj : this.getCategoryList()){
        ImwMItemCategory cat = (ImwMItemCategory)catObj;
        if(cat.getItemCategoryId() == catId)
        {
          return cat.getImwMItem();
        }
      }
    }
    else{
      for(Object subcatObj : this.getSubCategoryList(catId)){
        ImwMItemSubcategory subcat = (ImwMItemSubcategory)subcatObj;
        if(subcat.getItemSubcategoryId() == subcatId){
          return subcat.getImwMItem();
        }
      }
    }

    return new ArrayList();
  }
  
//  /**
//   * サブカテゴリ一覧を取得する。 <BR>
//   * 
//   * @param num
//   * @return
//   */
//  public void getSubCategoryList(RunData rundata, Context context) {
//    
//    Integer categoryId = rundata.getParameters().getInteger("category_id");
//
//    DataContext dataContext = DatabaseOrmService.getInstance()
//    .getDataContext();
//
//    SelectQuery query = new SelectQuery(ImwMItemCategory.class);
//    Expression exp1 = ExpressionFactory.matchDbExp(
//        ImwMItemCategory.DISABLED_PROPERTY, "F");
//    query.setQualifier(exp1);
//    Expression exp2 = ExpressionFactory.matchDbExp(
//        ImwMItemCategory.ITEM_CATEGORY_ID_PK_COLUMN, categoryId);
//    query.andQualifier(exp2);
//    List aList = dataContext.performQuery(query);
//
//    ImwMItemCategory record1 = (ImwMItemCategory) aList.get(0);
//    AccountPlanResultData rd1 = new AccountPlanResultData();
//    List subCateList = record1.getImwMItemSubcategory();
//
//    subCategoryList = new ArrayList();
//    
//    int size = subCateList.size();
//    for (int i = 0; i < size; i++) {
//      ImwMItemSubcategory record = (ImwMItemSubcategory) aList.get(i);
//      AccountPlanResultData rd = new AccountPlanResultData();
//      rd.initField();
//      rd.setSubCategoryId(record.getItemSubcategoryId());
//      rd.setSubCategoryName(record.getItemSubcategoryName());
//
//      subCategoryList.add(rd);
//    }
//  }
  
  /**
   * 
   * @param rundata
   * @param context
   */
  public void loadComboList(RunData rundata, Context context) {
    // カテゴリリスト
    categoryList = new ArrayList();
    try {
      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      SelectQuery query = new SelectQuery(ImwMItemCategory.class);

//      Expression exp1 = ExpressionFactory.matchExp(
//          ImwMItemCategory.ACCOUNT_CLASS_PROPERTY, Integer.valueOf(2));
//      query.setQualifier(exp1);
      List aList = dataContext.performQuery(query);

      if (aList == null || aList.size() == 0 ) {
        
      }
      
      int size = aList.size();
      for (int i = 0; i < size; i++) {
        ImwMItemCategory record = (ImwMItemCategory) aList.get(i);
        AccountPlanResultData rd = new AccountPlanResultData();
        rd.initField();
        rd.setCategoryId(record.getItemCategoryId().longValue());
        rd.setCategoryName(record.getItemCategoryName());
        rd.setAccountClass(record.getAccountClass().toString());
        categoryList.add(rd);
      }
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }

    // 入出金予定リスト
    accountPlanList = new ArrayList();
    try {
      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      SelectQuery query = new SelectQuery(ImwTAccountPlan.class);

      Expression exp1 = ExpressionFactory.matchDbExp(
          ImwTAccountPlan.ACCOUNT_ID_PK_COLUMN, Integer.valueOf(1));
      query.setQualifier(exp1);
      List aList = dataContext.performQuery(query);
      
      int size = aList.size();
      for (int i = 0; i < size; i++) {
        ImwTAccountPlan record = (ImwTAccountPlan) aList.get(i);
        AccountPlanResultData rd = new AccountPlanResultData();
        rd.initField();
        rd.setAccountPlanId(record.getAccountPlanId().longValue());
        rd.setItemId(record.getImwMItem().getItemId().longValue());
        rd.setItemName(record.getImwMItem().getItemName());
        rd.setAccountDate(ALDateUtil.format(record.getAccountDate(), "yyyy年M月d日"));

        // 入出金区分
        SelectQuery typeQuery = new SelectQuery(ImwMItemCategory.class);

        Expression exp2 = ExpressionFactory.matchDbExp(
            ImwMItemCategory.ITEM_CATEGORY_ID_PK_COLUMN, record.getImwMItem().getItemCategoryId());
        typeQuery.setQualifier(exp2);
        List typelist = dataContext.performQuery(typeQuery);

        ImwMItemCategory imwmitemcategory = (ImwMItemCategory)typelist.get(0);
        rd.setAccountClass(imwmitemcategory.getAccountClass().toString());
        
        accountPlanList.add(rd);
      }
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
    
    // 取引先リスト
    clientList = new ArrayList();
    try {
      DataContext dataContext = DatabaseOrmService.getInstance()
          .getDataContext();
      SelectQuery query = new SelectQuery(ImwMClient.class);

      Expression exp1 = ExpressionFactory.matchExp(
          ImwMClient.DISABLED_PROPERTY, 'F');
      query.setQualifier(exp1);
      List aList = dataContext.performQuery(query);

      if (aList == null || aList.size() == 0 ) {
        
      }
      
      int size = aList.size();
      for (int i = 0; i < size; i++) {
        ImwMClient record = (ImwMClient) aList.get(i);
        AccountPlanResultData rd = new AccountPlanResultData();
        rd.initField();
        rd.setClientId(record.getClientId().longValue());
        rd.setClientName(record.getClientName());
        

        int hanyoKey = type.equals("shiharai") ? 1 : 7;
        String hanyoValue = type.equals("shiharai") ? 
            record.getPayClass() : record.getReceiptClass();
        
        ImwMHanyo hanyo = AccountPlanUtils.getHanyoByKey(hanyoKey, hanyoValue);
        if(hanyo != null){
          String payClassName = hanyo.getHanyokubunnm();
          rd.setClientPayClassId(hanyoValue);
          rd.setClientPayClassName(payClassName);
        }

        clientList.add(rd);
      }
    } catch (Exception ex) {
      logger.error("Exception", ex);
    }
  }

//  /**
//   * カテゴリ・サブカテゴリ選択時、科目コンボに値をセットする
//   * @param rundata
//   * @param context
//   */
//  public void loadItemList(RunData rundata, Context context) {
//    
//    Integer tempCategoryId = rundata.getParameters().getInteger("category_id");
//    //Integer tempCategoryId = Integer.valueOf(1);
//    //サブカテゴリリスト
//    if (tempCategoryId != 0) {
//      List mySubcategorys = getSubCategoryNames(tempCategoryId);
//      subCategoryList = new ArrayList();
//      int length = mySubcategorys.size();
//      if (length == 0) {
//        subCategoryList = null;
//      }else{
//        for (int i = 0; i < length; i++) {
//          subCategoryList.add(mySubcategorys.get(i));
//        }  
//      }
//    }
//    Integer tempSubCategoryId = rundata.getParameters().getInteger("subCategory_id");
//    
////    Integer tempSubCategoryId = Integer.valueOf(0);
//    //科目リスト
//    if (tempCategoryId != 0) {
//      List myItems = getItemNames(tempCategoryId,tempSubCategoryId);
//      itemList = new ArrayList();
//      int length = myItems.size();
//      for (int i = 0; i < length; i++) {
//        itemList.add(myItems.get(i));
//      }  
//    }  
//  }
  
  /**
   * 各フィールドに対する制約条件を設定します。 <BR>
   * 
   * @see com.aimluck.eip.common.ALAbstractFormData#setValidator()
   */
  protected void setValidator() {
    // 入出金日必須
    account_date.setNotNull(true);
    
    // 金額必須項目
    price.setNotNull(true);
    // 金額の桁数制限
    price.limitValue(0, 1000000000);
    // 必須項目
    charge_handling.setNotNull(true);
    // 金額の桁数制限
    charge_handling.limitValue(0, 1000000000);
    // 金額必須項目
    charge_handling.setNotNull(true);
    // 金額の桁数制限
    charge_handling.limitValue(0, 1000000000);
    // メモの文字数制限
    note.limitMaxLength(1000);
  }

  /**
   * 入出金予定(実績)のフォームに入力されたデータの妥当性検証を行います。 <BR>
   * 
   * @param msgList
   * @return TRUE 成功 FALSE 失敗
   * @see com.aimluck.eip.common.ALAbstractFormData#validate(java.util.ArrayList)
   */
  protected boolean validate(ArrayList msgList) {
    //入出金日
    account_date.validate(msgList);
    
    //
    price.validate(msgList);

    // 摘要
    note.validate(msgList);
    return (msgList.size() == 0);

  }

  /**
   入出金予定をデータベースから読み出します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return TRUE 成功 FALSE 失敗
   * @see com.aimluck.eip.common.ALAbstractFormData#loadFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  protected boolean loadFormData(RunData rundata, Context context,
      ArrayList msgList) {
    String date1 = null;
    try {
      // オブジェクトモデルを取得
      ImwTAccountPlan plan = AccountPlanUtils.getImwTAccountPlan(rundata, context, false);
      if (plan == null)
        return false;
      
      ImwMItem item = plan.getImwMItem();
      ImwMItemCategory itemcat = item.getImwMItemCategory();
      ImwMItemSubcategory itemsubcat = item.getImwMItemSubcategory();
      ImwMClient client = plan.getImwMClient();
      
      //
      if(itemcat.getAccountClass() == 1){
        type = "seikyu";
      }else{
        type = "shiharai";
      }
      
      //
      category_id.setValue(itemcat.getItemCategoryId());
      
      if(itemsubcat == null){
        subCategory_id.setValue(-1);
      }else{
        subCategory_id.setValue(itemsubcat.getItemSubcategoryId());
      }
      
      // 科目ID
      item_id.setValue(item.getItemId().longValue());
      // 取引先
      client_id.setValue(client.getClientId().longValue());
      client_name.setValue(client.getClientName());
      // 振出人
      if(plan.getRemitter() != null)
        remitter.setValue(plan.getRemitter());
      // 振出日
      if(! AccountPlanUtils.isEmptyDate(plan.getRemittanceDate()))
        remittance_date.setValue(plan.getRemittanceDate());
      
      if(! AccountPlanUtils.isEmptyDate(plan.getReceiptDate()))
        receipt_date.setValue(plan.getReceiptDate());
          
      // 支払場所銀行名
      if(plan.getPayBankName() != null)
        pay_bank_name.setValue(plan.getPayBankName());
      // 支払場所支店名
      if(plan.getPayBankBranchName() != null)
        pay_bank_branch_name.setValue(plan.getPayBankBranchName());
      // 請求日
      if(! AccountPlanUtils.isEmptyDate(plan.getBillingDate()))
        billing_date.setValue(plan.getBillingDate());
      // 手形取立預け銀行名
      if(plan.getPayBankName() != null)
        charge_bank_name.setValue(plan.getPayBankName());
      // 手形取立預け支店名
      if(plan.getPayBankBranchName() != null)
        charge_bank_branch_name.setValue(plan.getPayBankBranchName());
      // 手形取立預け金額
      if(plan.getChargeMoney() != null)
        charge_money.setValue(plan.getChargeMoney());
      // 手形取立預け日
      if(plan.getChargeDate() != null)
        charge_date.setValue(plan.getChargeDate());
      // 手形取立預け手数料
      if(plan.getChargeHandling() != null)
        charge_handling.setValue(plan.getChargeHandling());
      // 入出金日
      if (AccountPlanUtils.isEmptyDate(plan.getAccountDate())) {
        account_date.setValue(date1);
      } else {
        account_date.setValue(plan.getAccountDate());
      }
      // 金額
      price.setValue(plan.getPrice());
      // 摘要
      if(plan.getNote() != null)
        note.setValue(plan.getNote());
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return true;
  }

  /**
   * 入出金予定をデータベースから削除します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return TRUE 成功 FALSE 失敗
   * @see com.aimluck.eip.common.ALAbstractFormData#deleteFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context)
   */
  protected boolean deleteFormData(RunData rundata, Context context,
      ArrayList msgList) {
    try {
      // オブジェクトモデルを取得
      ImwTAccountPlan plan = AccountPlanUtils.getImwTAccountPlan(rundata, context, false);
      if (plan == null)
        return false;

      // entityIdの取得
      int entityId = plan.getAccountPlanId();

      // 入出金予定を削除
      dataContext.deleteObject(plan);
      dataContext.commitChanges();

      // イベントログに保存
      ALEventlogFactoryService.getInstance().getEventlogHandler().log(entityId,
          ALEventlogConstants.PORTLET_TYPE_CASHFLOW, "");

    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return true;
  }

  /**
   * 入出金予定をデータベースに格納します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return TRUE 成功 FALSE 失敗
   * @see com.aimluck.eip.common.ALAbstractFormData#insertFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean insertFormData(RunData rundata, Context context,
      ArrayList msgList) {
    try {

      // 新規オブジェクトモデル
      ImwTAccountPlan account = (ImwTAccountPlan) dataContext
          .createAndRegisterNewObject(ImwTAccountPlan.class);

      this.makeImwTAccountPlanData(account);

      int userid = ALEipUtils.getUserId(rundata);
      account.setCreateUserId(Integer.valueOf(userid));
      account.setCreateData(Calendar.getInstance().getTime());
      account.setUpdateUserId(Integer.valueOf(userid));
      account.setUpdateDate(Calendar.getInstance().getTime());    
      
      // 入出金予定を登録
      dataContext.commitChanges();

//      if (accountPlan != null) {
//        // カテゴリIDの設定
//        category_id.setValue(accountPlan.getAccountPlanId().longValue());
//      }

//      // イベントログに保存
//      ALEventlogFactoryService.getInstance().getEventlogHandler().log(
//          todo.getTodoId(), ALEventlogConstants.PORTLET_TYPE_TODO,
//          job_order_name.getValue());
    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return true;
  }

  /**
   * データベースに格納されている入出金予定を更新します。 <BR>
   * 
   * @param rundata
   * @param context
   * @param msgList
   * @return TRUE 成功 FALSE 失敗
   * @see com.aimluck.eip.common.ALAbstractFormData#updateFormData(org.apache.turbine.util.RunData,
   *      org.apache.velocity.context.Context, java.util.ArrayList)
   */
  protected boolean updateFormData(RunData rundata, Context context,
      ArrayList msgList) {
    try {      
      ImwTAccountPlan account;
      // 確定フラグにチェックが入っているか
      int flg;
      if (decide_flag.getValue()==2){
        flg=1;
        // 入出金のオブジェクトモデルを取得
        account = AccountPlanUtils.getImwTAccountPlan(rundata, context, false);
      }else {
        flg=0;
        // 入出金予定のオブジェクトモデルを取得
         account = AccountPlanUtils.getImwTAccountPlan(rundata, context, false);          
      }  
      if (account == null)
        return false;

      this.makeImwTAccountPlanData(account);

      int userid = ALEipUtils.getUserId(rundata);
      account.setUpdateUserId(Integer.valueOf(userid));
      account.setUpdateDate(Calendar.getInstance().getTime());
      
      // 入出金予定 を更新
      dataContext.commitChanges();

//      // イベントログに保存
//      ALEventlogFactoryService.getInstance().getEventlogHandler().log(
//          todo.getTodoId(), ALEventlogConstants.PORTLET_TYPE_TODO,
//          job_order_name.getValue());

    } catch (Exception ex) {
      logger.error("Exception", ex);
      return false;
    }
    return true;
  }

  private void makeImwTAccountPlanData(ImwTAccountPlan account) throws Exception {
    ImwMItem item = AccountPlanUtils.getImwMItem(dataContext, Long
        .valueOf(item_id.getValue()));
    ImwMClient client = AccountPlanUtils.getImwMClient(dataContext, Long
        .valueOf(client_id.getValue()));

    account.setImwMItem(item);
    account.setImwMClient(client);
    account.setDraftNumber(draft_number.getValue());
    try{
      account.setRemitter(Integer.valueOf(remitter.getValueAsString()));
    }
    catch(Exception ex){
      account.setRemitter(null);
    }
    
    //
    account.setAccountDate(account_date.getValue().getDate());
    account.setPrice(Long.valueOf(price.getValueAsString()));
    
    // 振出日
    if(remittance_date.getValue() == null || remittance_date.getValue().isNullYear()){
      account.setRemittanceDate(null);
    }else{
      account.setRemittanceDate(remittance_date.getValue().getDate());
    }
    
    if(receipt_date.getValue() == null || receipt_date.getValue().isNullYear()){
      account.setReceiptDate(null);
    }else{
      account.setReceiptDate(receipt_date.getValue().getDate());
    }
    
    account.setPayBankName(pay_bank_name.getValue());
    account.setPayBankBranchName(pay_bank_branch_name.getValue());

    if(billing_date.getValue() == null || billing_date.getValue().isNullYear()){
      account.setBillingDate(null);
    }else{
      account.setBillingDate(billing_date.getValue().getDate());
    }
    
    account.setChargeBankName(charge_bank_name.getValue());
    account.setChargeBankBranchName(charge_bank_branch_name.getValue());
    account.setChargeMoney(charge_money.getValue());

    if(charge_date.getValue() == null || charge_date.getValue().isNullYear()){
      account.setChargeDate(null);
    }else{
      account.setChargeDate(charge_date.getValue().getDate());
    }
    
    account.setChargeHandling(charge_handling.getValue());

    account.setAccountDate(account_date.getValue().getDate());
    account.setPrice(price.getValue());
    account.setNote(note.getValue());
    
    // 確定フラグにチェックが入っているか
    int flg;
    flg = 0;
    if (decide_flag.getValue() == 2){
      flg = 1;
    }else {
      flg = 0;
    }  

    account.setDecideFlag(String.valueOf(flg));
  }
  
//  /**
//   * サブカテゴリリストを取得する <BR>
//   * 
//   * @return uList
//   */
// public static List getSubCategoryNames(int categoryid) {
//   ArrayList uList = new ArrayList();
//   
//   DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();
//   SelectQuery query = new SelectQuery(ImwMItemSubcategory.class);
//   
//   Expression exp1 = ExpressionFactory.matchExp(
//       ImwMItemSubcategory.DISABLED_PROPERTY, "F");
//   query.setQualifier(exp1);
//   Expression exp2 = ExpressionFactory.matchExp(
//       ImwMItemSubcategory.IMW_MITEM_CATEGORY_PROPERTY, Integer.valueOf(categoryid));
//   query.andQualifier(exp2);
//   
//   List list = dataContext.performQuery(query);
//   if (list == null || list.size() == 0)
//     return null;
//   int size = list.size();
//   
//   for (int i = 0; i < size; i++) {
//     ImwMItemSubcategory record = (ImwMItemSubcategory) list.get(i);
//     ImwMItemSubcategory rd = new ImwMItemSubcategory();
//     rd.setItemSubcategoryId(record.getItemSubcategoryId().toString());
//     rd.setItemSubcategoryName(record.getItemSubcategoryName());
//     uList.add(rd);
//   }
//   return uList;
// }
// 
  /**
   * 科目リストを取得する <BR>
   * 
   * @return uList
   */
 public static List getItemNames(int categoryid,int subcategoryid) {
   ArrayList uList = new ArrayList();
   
   DataContext dataContext = DatabaseOrmService.getInstance().getDataContext();
   SelectQuery query = new SelectQuery(ImwMItem.class);
   
//   Expression exp1 = ExpressionFactory.noMatchExp(ImwMItem.DISABLED_PROPERTY, 'T');
//   query.setQualifier(exp1);
   
   if (categoryid != 0) {
     Expression exp2 = ExpressionFactory.matchDbExp(
         ImwMItemCategory.ITEM_CATEGORY_ID_PK_COLUMN, Integer.valueOf(categoryid));
     query.andQualifier(exp2);  
   }
   if (subcategoryid != 0) {    
     Expression exp3 = ExpressionFactory.matchDbExp(
         ImwMItemSubcategory.ITEM_SUBCATEGORY_ID_PK_COLUMN, Integer.valueOf(subcategoryid));
     query.andQualifier(exp3);
   }
   
   List list = dataContext.performQuery(query);
   if (list == null || list.size() == 0)
     return null;
   int size = list.size();
   
   for (int i = 0; i < size; i++) {
     ImwMItem record = (ImwMItem) list.get(i);
     ImwMItem rd = new ImwMItem();
     rd.setItemId(record.getItemId().toString());
     rd.setItemName(record.getItemName());
     uList.add(rd);
   }
   return uList;
 }

 /**
  * カテゴリリストを取得します。 <BR>
  * 
  * @return
  */
 public List getCategoryList() {
   return categoryList;
 }

// /**
//  * サブカテゴリリストを取得します。 <BR>
//  * 
//  * @return
//  */
// public List getSubCategoryList() {
//   return subCategoryList;
// }
 
 /**
  * 科目リストを取得します。 <BR>
  * 
  * @return
  */
 public ArrayList getItemList() {
   return itemList;
 }
 public List setItemList() {
   return itemList;
 }
 
 /**
  * 取引先リストを取得します。 <BR>
  * 
  * @return
  */
 public ArrayList getClientList() {
   return clientList;
 }
 public List setClientList() {
   return clientList;
 }
 
 
 public AccountPlanResultData getClientInfo(long clientId){
   for(Object obj : this.clientList){
     AccountPlanResultData client = (AccountPlanResultData)obj;
     if(client.getClientId().getValue() == clientId){
       return client;
     }
   }
   
   return null;
 }
 
 /**
  *入出金予定リストを取得します。 <BR>
  * 
  * @return
  */
 public ArrayList getAccountPlanList() {
   return accountPlanList;
 }
 public List setAccountPlanList() {
   return accountPlanList;
 }
 
 /**
  * 入出金区分 <BR>
  * 
  * @return
  */
 public ALNumberField getAccountType() {
   return account_class;
 }
 
  /**
   * カテゴリIDを取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getCategoryId() {
    return category_id;
  }
  
  /**
   * サブカテゴリIDを取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getSubCategoryId() {
    return subCategory_id;
  }
  
  /**
   * 科目IDを取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getItemId() {
    return item_id;
  }
    
  /**
   * 取引先IDを取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getClientId() {
    return client_id;
  }
  
  /**
   * 振出人を取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getRemitter() {
    return remitter;
  }

  /**
   * 振出日を取得します。 <BR>
   * 
   * @return
   */
  public ALDateField getRemittanceDate() {
    return remittance_date;
  }
  
  /**
   * 支払場所銀行名を取得します。 <BR>
   * 
   * @return
   */
  public ALStringField getPayBankName() {
    return pay_bank_name;
  }

  /**
   * 支払場所支店名を取得します。 <BR>
   * 
   * @return
   */
  public ALStringField getPayBankBranchName() {
    return pay_bank_branch_name;
  }
  
  /**
   * 請求日を取得します。 <BR>
   * 
   * @return
   */
  public ALDateField getBillingDate() {
    return billing_date;
  }
  
  /**
   * 手形取立預け銀行名を取得します。 <BR>
   * 
   * @return
   */
  public ALStringField getChargeBankName() {
    return charge_bank_name;
  }

  /**
   * 手形取立預け支店名を取得します。 <BR>
   * 
   * @return
   */
  public ALStringField getChargeBankBranchName() {
    return charge_bank_branch_name;
  }
  
  /**
   * 手形取立預け金額を取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getChargeMoney() {
    return charge_money;
  }
  
  /**
   * 手形取立預け日を取得します。 <BR>
   * 
   * @return
   */
  public ALDateField getChargeDate() {
    return charge_date;
  }
  
  /**
   * 手形取立預け手数料を取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getChargeHandling() {
    return charge_handling;
  }
  
  /**
   * 入出金日を取得します。 <BR>
   * 
   * @return
   */
  public ALDateField getAccountDate() {
    return account_date;
  }

  /**
   * 金額を取得します。 <BR>
   * 
   * @return
   */
  public ALNumberField getPrice() {
    return price;
  }

  /**
   * 現金出金日を取得します。 <BR>
   * 
   * @return
   */
  public ALDateField getInitReceiptDate() {
    return cash_account_date;
  }
    
  /**
   * 摘要を取得します。 <BR>
   * 
   * @return
   */
  public ALStringField getNote() {
    return note;
  }
 
  /**
   * 請求・支払区分を取得します。 <BR>
   * 
   * @return
   */
  public String getType() {
    return type;
  }

  public void setType(String val) {
    type = val;
  }

  /**
   * 予定・実績区分を取得します。 <BR>
   * 
   * @return
   */
  public String getYojitsu() {
    return yojitsu;
  }

  public void setYojitsu(String val) {
    yojitsu = val;
  }

  /**
   * アクセス権限チェック用メソッド。<br />
   * アクセス権限の機能名を返します。
   * 
   * @return
   */
  public String getAclPortletFeature() {
    return aclPortletFeature;
  }

  public void setAclPortletFeature(String aclPortletFeature) {
    this.aclPortletFeature = aclPortletFeature;
  }
}
