/*********************************************************************
* All Rights reserved,Copyright (c) K-Opticom
**********************************************************************
*＜プログラム内容＞
*   システム名      ：eo顧客基幹システム
*   モジュール名    ：CNA90101SFLogic
*   ソースファイル名：CNA90101SFLogic.java
*   作成者          ：富士通
*   日付            ：2011年11月23日
*＜機能概要＞
*   会員情報更新処理(支払方法登録,クレカ登録/削除)を行います。
*＜修正履歴＞
*   バージョン  修正日       修正者      修正内容
*   v1.00.00    2011/11/23   FJ          新規作成
*
**********************************************************************/
package eo.web.webview.CNA90101SF;

import static com.fujitsu.futurity.web.x31.X31SWebLog.DEBUG_LOG;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fujitsu.futurity.web.x31.X31CMessageResult;
import com.fujitsu.futurity.web.x31.X31CWebConst;
import com.fujitsu.futurity.web.x31.X31SDataBeanAccess;

import eo.common.constant.JCNStrConst;
import eo.web.webview.JCCWebBusinessLogic;
import eo.web.webview.CommonInfoCF.CommonInfoCFConst;
import eo.web.webview.mapping.CNSV0036_CNSV0036OPDBMapper;
import eo.web.webview.mapping.CNSV0037_CNSV0037OPDBMapper;
import eo.web.webview.mapping.CNSV0038_CNSV0038OPDBMapper;

/**
 * 会員情報更新処理(支払方法登録,クレカ登録/削除)
 * @author FJ
 *
 */
@SuppressWarnings("serial")
public class CNA90101SFLogic extends JCCWebBusinessLogic
{
	/** 処理区分：決済方法登録 */
	private static final String PROCESS_DIV_REGIST_KSSAI = "11";
	/** 処理区分：クレジットカード情報登録 */
	private static final String PROCESS_DIV_REGIST_CRECARD = "13";
	/** 処理区分：クレジットカード情報削除 */
	private static final String PROCESS_DIV_DELETE_CRECARD = "14";
	/** ユースケースID：決済方法登録 */
	private static final String USECASE_ID_REGIST_KSSAI = "CNSV0036";
	/** ユースケースID：クレジットカード情報登録 */
	private static final String USECASE_ID_REGIST_CRECARD = "CNSV0037";
	/** ユースケースID：クレジットカード情報削除 */
	private static final String USECASE_ID_DELETE_CRECARD = "CNSV0038";
	/** ユースケースID：AxM連携 */
	private static final String USECASE_ID_AXM_RENKEI = "CKSV9001";
	/** オペレーション文字列 */
	private static final String OPERATION_STR = "OP";
	/**
	 * 空文字
	 */
	private static final String STR_BLANK = "";
	
	/**
	 * APIリターンコード(パラメータエラー)
	 */
	private static final String S_API_RTN_CD_PARAM_ERR = JCNStrConst.S_API_RTN_CD_PARAM_ERR;
	
	/**
	 * APIリターンコード(システムエラー)
	 */
	private static final String S_API_RTN_CD_SYS_ERR = JCNStrConst.S_API_RTN_CD_SYS_ERR;
	
	/**
	 * 正常終了コード
	 */
	private static final String RESULT_CD_NORMAL = "00";
	
	/**
	 * APIリクエスト時
	 * 
	 * @return boolean 処理結果
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public boolean action_init() throws Exception
	{

		DEBUG_LOG.info("action_Init Start!");

		// 共通Bean取得
		X31SDataBeanAccess commoninfoBean = super.getCommonInfoBean();
		X31SDataBeanAccess bean = getServiceFormBean();

		try
		{
			// SYSID
			String sysid = "";
			// リクエストパラメータを取得・格納
			HashMap requestMap = super.getRequestParams();
			
			// テスト用
			HashMap payment_setting_list = new HashMap();
			HashMap payment_setting = new HashMap();
			
			HashMap reqMap = new HashMap();
			// SYSIDを取得
			sysid = (String)requestMap.get("sys_id");
			reqMap.put("process_div", requestMap.get("process_div"));
			reqMap.put("sys_id", sysid);
			reqMap.put("eo_id", requestMap.get("eo_id"));
			payment_setting.put("sys_id", requestMap.get("sys_id"));
			payment_setting.put("okyakusama_id", requestMap.get("okyakusama_id"));
			payment_setting.put("isp_stop_flg", requestMap.get("isp_stop_flg"));
			payment_setting_list.put("payment_setting", payment_setting);
			reqMap.put("credit_id", requestMap.get("credit_id"));
			reqMap.put("payment_setting_list", payment_setting_list);
			
			commoninfoBean.sendMessageString(CommonInfoCFConst.USER_ID,  X31CWebConst.DATABEAN_SET_VALUE, "CCMGUSER");
			commoninfoBean.sendMessageString(CommonInfoCFConst.USER_NM,  X31CWebConst.DATABEAN_SET_VALUE, "CCMGUSER");
			
			/************************
			 * パラメータチェック
			 ************************/
			if(!checkParam(reqMap))
			{
				createErrResultParam(bean, S_API_RTN_CD_PARAM_ERR);
				return true;
			}
			
			// サービス呼び出しの際の引数を生成
			HashMap paramMap = new HashMap();
			HashMap inputMap = new HashMap();
			HashMap outputMap = new HashMap();

			// 処理区分
			String processDiv = (String)reqMap.get("process_div");
			// 決済方法登録
			if (PROCESS_DIV_REGIST_KSSAI.equals(processDiv))
			{
				// サービスへのデータセット
				paramMap.put(X31CWebConst.TELEGRAM_INFO_USECASE_ID, USECASE_ID_REGIST_KSSAI);
				paramMap.put(X31CWebConst.TELEGRAM_INFO_OPERATION_ID, USECASE_ID_REGIST_KSSAI + OPERATION_STR);
				// マッピングクラスのインスタンス作成
				CNSV0036_CNSV0036OPDBMapper mapper = new CNSV0036_CNSV0036OPDBMapper();
				mapper.setCNSV0036(this, reqMap, inputMap, "1");
			}
			// クレジットカード情報登録
			else if (PROCESS_DIV_REGIST_CRECARD.equals(processDiv))
			{
				// サービスへのデータセット
				paramMap.put(X31CWebConst.TELEGRAM_INFO_USECASE_ID, USECASE_ID_REGIST_CRECARD);
				paramMap.put(X31CWebConst.TELEGRAM_INFO_OPERATION_ID, USECASE_ID_REGIST_CRECARD + OPERATION_STR);
				// マッピングクラスのインスタンス作成
				CNSV0037_CNSV0037OPDBMapper mapper = new CNSV0037_CNSV0037OPDBMapper();
				mapper.setCNSV0037(this, reqMap, inputMap, "1");
			}
			// クレジットカード情報削除
			else if (PROCESS_DIV_DELETE_CRECARD.equals(processDiv))
			{
				// サービスへのデータセット
				paramMap.put(X31CWebConst.TELEGRAM_INFO_USECASE_ID, USECASE_ID_DELETE_CRECARD);
				paramMap.put(X31CWebConst.TELEGRAM_INFO_OPERATION_ID, USECASE_ID_DELETE_CRECARD + OPERATION_STR);
				// マッピングクラスのインスタンス作成
				CNSV0038_CNSV0038OPDBMapper mapper = new CNSV0038_CNSV0038OPDBMapper();
				mapper.setCNSV0038(this, reqMap, inputMap, "1");
			}
			
			// サービスの呼出
			X31CMessageResult msgResult = invokeService(paramMap, inputMap, outputMap);
			
			// エラー処理 
			if(msgResult != null)
			{
				createErrResultParam(bean, S_API_RTN_CD_SYS_ERR);
				return true;
			}
			
			// 返却パラメータ設定
			String result = createResultParam(bean, outputMap, processDiv);
			
		}
		catch (Exception e)
		{
			e.printStackTrace();
//			DEBUG_LOG.info(e.getMessage());

			createErrResultParam(bean, S_API_RTN_CD_SYS_ERR);
			return true;
		}
		DEBUG_LOG.info("action_Init End!");
		return true;
	}
	
	/**
	 * パラメータチェック処理
	 * @param bean
	 * @return boolean(true:チェックOK,false:チェックNG)
	 */
	private static boolean checkParam(HashMap<Object, Object> requestMap)
	{
		// 処理区分
		String processDiv = getParameterToString(requestMap, "process_div");
		// SYSID
		String sysid = getParameterToString(requestMap, "sys_id");
		// EOID
		String eoid = getParameterToString(requestMap, "eo_id");
		HashMap<String, Object> childMap = (HashMap<String, Object>)requestMap.get("payment_setting_list");
		HashMap<Object, Object> workMap = (HashMap<Object, Object>)childMap.get("payment_setting");
		// SYSID
		String paymentSysid = getParameterToString(workMap, "sys_id");
		// サービス契約番号
		String svcKeiNo = getParameterToString(workMap, "okyakusama_id");
		// ISP利用停止フラグ
		String ispStopFlg = getParameterToString(workMap, "isp_stop_flg");
		// クレジットカードID
		String crecardId = getParameterToString(requestMap, "credit_id");
		
		/************************
		 * パラメータチェック
		 ************************/
		// 処理区分
		if (!isNullOrBlankWithTrim(processDiv))
		{
			// 桁数チェック
			if (processDiv.length() != 2)
			{
				return false;
			}
			else
			{
				// SYSID
				if (!isNullOrBlankWithTrim(sysid))
				{
					if (sysid.length() != 10)
					{
						return false;
					}
				}
				else
				{
					return false;
				}
				// EOID
				if (!isNullOrBlankWithTrim(eoid))
				{
					if ((eoid.length() < 1) && (eoid.length() > 80))
					{
						return false;
					}
				}
				// SYSID
				if (!isNullOrBlankWithTrim(paymentSysid))
				{
					if (paymentSysid.length() != 10)
					{
						return false;
					}
				}
				else
				{
					return false;
				}
				// 処理区分：決済方法登録
				if (PROCESS_DIV_REGIST_KSSAI.equals(processDiv))
				{
					// サービス契約番号チェック
					if (!isNullOrBlankWithTrim(svcKeiNo))
					{
						if (svcKeiNo.length() != 10)
						{
							return false;
						}
					}
					else
					{
						return false;
					}
					// ISP利用停止フラグチェック
					if (!isNullOrBlankWithTrim(ispStopFlg))
					{
						if (ispStopFlg.length() != 1)
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
				// 処理区分：クレジットカード情報登録 or クレジットカード情報削除
				else if ((PROCESS_DIV_REGIST_CRECARD.equals(processDiv) || (PROCESS_DIV_DELETE_CRECARD.equals(processDiv))))
				{
					// クレジットカードIDチェック
					if (!isNullOrBlankWithTrim(crecardId))
					{
						if (crecardId.length() != 9)
						{
							return false;
						}
					}
					else
					{
						return false;
					}
				}
			}
		}
		else
		{
			return false;
		}
		
		return true;
	}

	/**
	 * 返却パラメータ編集処理
	 * @param bean
	 * @param outMap
	 * @return String
	 */
	private String createResultParam(X31SDataBeanAccess bean, HashMap<?, ?> outputMap, String processDiv) throws Exception
	{
		// 下記2つは設定なし
		bean.sendMessageString(CNA90101SFConst.UPDATE_TIMESTAMP_M00010_OUT, X31CWebConst.DATABEAN_SET_VALUE, "");
		bean.sendMessageString(CNA90101SFConst.UPDATE_TIMESTAMP_M00280_OUT, X31CWebConst.DATABEAN_SET_VALUE, "");
		String result = "";
		if (PROCESS_DIV_REGIST_KSSAI.equals(processDiv))
		{
			// お客様存在チェック
			HashMap custMap = null;
			if(outputMap.containsKey("CNSV003602SC")){
				custMap = (HashMap)outputMap.get("CNSV003602SC");
			}
			ArrayList list11 = (ArrayList)custMap.get("ECK0011A010CBSMsg1List");
			if (list11 == null || list11.isEmpty())
			{
				result = "01";
				bean.sendMessageString(CNA90101SFConst.RETURN_CODE, X31CWebConst.DATABEAN_SET_VALUE, result);
				
				return result;
			}
			HashMap parentMap = null;
			if(outputMap.containsKey("CNSV003607SC")){
				parentMap = (HashMap)outputMap.get("CNSV003607SC");
			}
			String system_err_flg = (String)parentMap.get("system_err_flg");
			String out_sys_id = (String)parentMap.get("out_sys_id");
			String err_cd = (String)parentMap.get("err_cd");
			if ("0".equals(system_err_flg))
			{
				result = "00";
			}
			else
			{
				if ("90006".equals(err_cd))
				{
					// eoID会員が存在しない
					result = "99";
				}
				else if ("54001".equals(err_cd))
				{
					// 決済方法が無効
					result = "99";
				}
				else if ("99990".equals(err_cd))
				{
					// 連携エラー
					result = "91";
				}
				else
				{
					// システムエラー
					result = "99";
				}
			}
			bean.sendMessageString(CNA90101SFConst.RETURN_CODE, X31CWebConst.DATABEAN_SET_VALUE, result);
		}
		// クレジットカード情報登録
		else if (PROCESS_DIV_REGIST_CRECARD.equals(processDiv))
		{
			HashMap parentMap01 = null;
			if(outputMap.containsKey("CNSV003701SC")){
				parentMap01 = (HashMap)outputMap.get("CNSV003701SC");
			}
			HashMap parentMap02 = null;
			if(outputMap.containsKey("CNSV003702SC")){
				parentMap02 = (HashMap)outputMap.get("CNSV003702SC");
			}
			String system_err_flg01 = "";
			if (parentMap01 != null && parentMap01.containsKey("system_err_flg"))
			{
				system_err_flg01 = (String)parentMap01.get("system_err_flg");
			}
			String system_err_flg02 = "";
			if (parentMap02 != null && parentMap02.containsKey("system_err_flg"))
			{
				system_err_flg02 = (String)parentMap02.get("system_err_flg");
			}

			if ("1".equals(system_err_flg01))
			{
				// クレジットカード登録枚数エラー
				result = "23";
			}
			else if ("1".equals(system_err_flg02))
			{
				// クレジットカード重複エラー
				result = "26";
			}
			else
			{
				result = "00";
			}
			bean.sendMessageString(CNA90101SFConst.RETURN_CODE, X31CWebConst.DATABEAN_SET_VALUE, result);
		}
		// クレジットカード情報削除
		else if (PROCESS_DIV_DELETE_CRECARD.equals(processDiv))
		{
			HashMap parentMap01 = null;
			if(outputMap.containsKey("CNSV003801SC")){
				parentMap01 = (HashMap)outputMap.get("CNSV003801SC");
			}
			String system_err_flg01 = "";
			if (parentMap01 != null && parentMap01.containsKey("search_err_flg"))
			{
				system_err_flg01 = (String)parentMap01.get("search_err_flg");
			}
			if ("1".equals(system_err_flg01))
			{
				// 該当データなし
				result = "01";
			}
			else
			{
				result = "00";
			}
			bean.sendMessageString(CNA90101SFConst.RETURN_CODE, X31CWebConst.DATABEAN_SET_VALUE, result);
		}
		
		return result;
	}
	
	/**
	 * View層エラー発生時返却パラメータ編集処理
	 * @param bean
	 * @return String
	 */
	private void createErrResultParam(X31SDataBeanAccess bean, String errCd) throws Exception
	{
		bean.sendMessageString(CNA90101SFConst.RETURN_CODE, X31CWebConst.DATABEAN_SET_VALUE, errCd);
	}
	

	/**
	 * パラメータマップを解析し、キーに一致する値を返却する。
	 * @param requestParamMap
	 * @param keyName
	 * @return String
	 */
	private static String getParameterToString(HashMap<Object, Object> requestParamMap, String keyName)
	{
		String value = "";
		
		if(requestParamMap.containsKey(keyName))
		{
			value = (String)requestParamMap.get(keyName);
			if (null == value && "".equals(value))
			{
				value = "";
			}
		}
		return value;
	}
	
	/**
	 * マップから指定されたキーの値を取得する。
	 * (使用例）<BR/>
	 *     getParamFromXml("LKA11020_RECEIVE", "PROCESS_DIV");<BR/>
	 * 
	 * @param map マップ
	 * @param allKeys キー名
	 * @return 値
	 */
	@SuppressWarnings("unchecked")
	public static Object getParamFromMap(Map map, String...allKeys)
	{

		Map nowMap = map;
		Object returnVal = null;
		for (int i = 0; i < allKeys.length; i++)
		{
			String key = allKeys[i];
			int idx = -1;
			if (key.matches("[a-zA-Z0-9_\\-]+\\[[0-9]+\\]"))
			{
				idx = new Integer(key.replaceFirst("^[a-zA-Z0-9_\\-]+\\[", "").replace("]", ""));
				key = key.replaceFirst("\\[[0-9]+\\]", "");
			}
			if (nowMap.containsKey(key))
			{
				Object val = nowMap.get(key);
				if ((val instanceof List) && (idx >= 0))
				{
					List nowList = (List)val;
					val = nowList.get(idx);
				}
				if (val instanceof Map)
				{
					nowMap = (Map)val;
				}
				if (i == allKeys.length - 1)
				{
					returnVal = val;
				}
			}
			else
			{
				return null;
			}
		}

		return returnVal;
	}
	
	/**
	 * メソッド名  ：null、空白文字（半角空白、全角空白）判定
	 * メソッド説明：
	 * 備考： 半角トリムを行う。
	 * @param strCheck 対象文字列
	 * @return true :対象文字列がnullもしくは空白文字（半角空白、全角空白）
	 *          false:上記以外
	 */
	private static boolean isNullOrBlankWithTrim(String strCheck)
	{
		// null文字置換、半角トリムを行い、
		// null、空文字、空白文字（半角空白、全角空白）判定結果を返す
		return isNullOrBlanks(replaceNullToBlank(strCheck).trim());
	}
	
	/**
	 * メソッド名  ：null文字→空文字変換
	 * メソッド説明：対象文字列がnull文字の場合、空文字に変換して返す
	 * 備考    
	 * @param base 対象文字列
	 * @return 変換後文字列
	 */
	private static String replaceNullToBlank(String base)
	{
    	
    	// 引数の対象文字列がnullの場合
        if(base == null)
        {
        	// 空文字を返す
            return STR_BLANK;
        }
        
        // 引数の対象文字列がnullでない場合、そのまま返す
        return base;
    }
	/**
	 * メソッド名  ：null、空文字、空白文字（半角空白、全角空白）判定
	 * メソッド説明：：null、空文字、
	 *                     空白文字（半角空白、全角空白）の判定を行う
	 * 備考：
	 * @param strCheck　対象文字列
	 * @return true :対象文字列がnullもしくは空白文字（半角空白、全角空白）のみ
	 *          false:上記以外
	 */
    private static boolean isNullOrBlanks(String strCheck)
    {
		// 対象文字列が対象文字列がnullもしくは空文字の場合
    	if(isNullOrBlank(strCheck))
    	{
    		// trueを返す
        	return true;
        }
    	
    	// 全半角空白を空文字に置換
        String strRepTemp = strCheck.replaceAll(" ", "");
        String strRep = strRepTemp.replaceAll("　", "");
        
        // 空文字以外が存在する場合
        if(strRep.length() > 0)
        {
        	// falseを返す
        	return false;
        }
        
        // 空文字のみの場合、trueを返す
        return true;
	}
    /**
     * メソッド名  ：null、空文字判定
     * メソッド説明：nullもしくは空文字の判定を行う
     * 備考：
     * @param strCheck 対象文字列
     * @return true :対象文字列がnullもしくは空文字
     *          false:上記以外
     */
	private static boolean isNullOrBlank(String strCheck)
	{
		
		// 対象文字列が対象文字列がnullもしくは空文字の場合、trueを返す
    	return strCheck == null || STR_BLANK.equals(strCheck);
	}
}
