package jp.agentec.sinaburocast.action.user;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletResponse;

import jp.agentec.sinaburocast.action.AbstractAction;
import jp.agentec.sinaburocast.action.admin.enquete.EnqueteRegistAction;
import jp.agentec.sinaburocast.action.batch.EnqueteSumBatchAction;
import jp.agentec.sinaburocast.common.SinaburoConstant;
import jp.agentec.sinaburocast.common.SinaburoConstant.EnqueteType;
import jp.agentec.sinaburocast.common.annotation.NoLogin;
import jp.agentec.sinaburocast.common.exception.SystemException;
import jp.agentec.sinaburocast.common.util.AgtVelocityViewServlet;
import jp.agentec.sinaburocast.common.util.PropertyUtil;
import jp.agentec.sinaburocast.common.util.ServletUtil;
import jp.agentec.sinaburocast.common.util.SinaburoUtil;
import jp.agentec.sinaburocast.common.util.SinaburoViewUtil;
import jp.agentec.sinaburocast.common.util.velocity.VelocityTool;
import jp.agentec.sinaburocast.entity.AdminUser;
import jp.agentec.sinaburocast.entity.Answer;
import jp.agentec.sinaburocast.entity.Enquete;
import jp.agentec.sinaburocast.entity.Member;
import jp.agentec.sinaburocast.entity.Organization;
import jp.agentec.sinaburocast.entity.PointDonation;
import jp.agentec.sinaburocast.entity.Question;
import jp.agentec.sinaburocast.entity.Template;
import jp.agentec.sinaburocast.form.user.EnqueteForm;
import jp.agentec.sinaburocast.helper.KeyHelper;
import jp.agentec.sinaburocast.service.EnqueteService;
import jp.agentec.sinaburocast.service.MemberService;
import jp.agentec.sinaburocast.service.OrganizationService;
import jp.agentec.sinaburocast.service.PointDonationService;
import jp.agentec.sinaburocast.service.QuestionService;
import jp.agentec.sinaburocast.service.ReplyService;
import jp.agentec.sinaburocast.service.TemplateService;
import jp.agentec.sinaburocast.vo.EnqueteKey;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.TokenProcessor;
import org.seasar.framework.util.StringUtil;
import org.seasar.struts.annotation.ActionForm;
import org.seasar.struts.annotation.Execute;
import org.seasar.struts.util.RequestUtil;

/**
 * アンケート処理
 *
 * @author choi-c
 *
 */
@NoLogin
public class EnqueteAction extends AbstractAction {

	private final Logger logger = Logger.getLogger(getClass());

	@ActionForm
	public EnqueteForm enqueteForm;
	public EnqueteService enqueteService;

	public QuestionService questionService;

	public ReplyService replyService;

	public TemplateService templateService;

	public OrganizationService organizationService;

	//団体寄付用
	public PointDonationService pointDonationService;

	/**
	 * アンケート通知メールから来た場合の情報設定
	 * @throws Exception
	 */
	private void initFromMail() throws Exception{
		if(StringUtil.isNotBlank(enqueteForm.qUrlId)){
			if (!enqueteForm.qUrlId.endsWith("@")) {
				enqueteForm.qUrlId = enqueteForm.qUrlId + "@";
			}
			EnqueteKey org = new KeyHelper().decrypt(enqueteForm.qUrlId);
			enqueteForm.eid=org.enqueteId+"";
			enqueteForm.member= memberService.findById(org.memberId);
		}
	}
	/**
	 * 初期表示
	 * @throws Exception
	 */
	@Execute(validator = false, reset="initReset")
	public String index() throws Exception {
		initFromMail();
		Member member = null;
		AdminUser adminUser = null;

		//ログインしたユーザーのみ閲覧可能
		Integer eid = null;
		try {
			eid = Integer.parseInt(enqueteForm.eid);
		} catch (Exception e1) {
			logger.error(e1,e1);
			request.setAttribute("errMsg", "parameter error. eid");
			return getHtmlPath(enqueteForm.template, errorPage);
		}
		
		Enquete enquete = enqueteService.findById(eid);

//		if(enqueteForm.member == null && !StringUtil.equals(enqueteForm.type, "pre") && (member = getMember()) == null && (adminUser = getAdmin()) == null && isLoginTarget(enquete) )return "/user/login/";

		member = enqueteForm.member != null ? enqueteForm.member : getMember();

		if (member == null) {
			adminUser = getAdmin();
		}

		Template template = templateService.findByenqueteType(enquete.enqueteType);
		enqueteForm.template = template;

		//住所、連絡先が未登録ユーザの場合、会員情報変更画面に遷移する。
		if (enquete.enqueteType.equals(SinaburoConstant.EnqueteType.ORGANIZATION_CONTRIBUTE) && member != null) {
			if (StringUtil.isBlank(member.zipCode) || member.prefectureId == null || StringUtil.isBlank(member.cityName) || StringUtil.isBlank(member.areaName) || StringUtil.isBlank(member.telno)
					|| StringUtil.isBlank(member.firstName) || StringUtil.isBlank(member.lastName) || StringUtil.isBlank(member.firstNameKana) || StringUtil.isBlank(member.lastNameKana)
					|| member.genderCd == null || StringUtil.isBlank(member.birthday)) {
				ActionMessages messages = (ActionMessages)request.getAttribute(Globals.ERROR_KEY);

				if (messages == null) {
					messages = new ActionMessages();
				}
				if(StringUtil.isNotBlank(enqueteForm.qUrlId)){
					request.setAttribute("errMsg", SinaburoViewUtil.getMessage("errors.E060"));
					// enqueteForm.qUrlIdが残っていると同じアンケートを開き続けてしまうのでクリア
					enqueteForm.qUrlId = null;
					return getHtmlPath(enqueteForm.template, errorPage);
				} else {
					messages.add("pointUse", new ActionMessage(SinaburoViewUtil.getMessage("errors.E052")));
					request.setAttribute(Globals.ERROR_KEY, messages);
					session.setAttribute("pointCheckFlg", true);
					return "/user/userEdit/";
				}
			}

		}		
		// enqueteForm.qUrlIdが残っていると同じアンケートを開き続けてしまうのでクリア
		enqueteForm.qUrlId = null;
		if(enquete.enqueteType ==SinaburoConstant.EnqueteType.WEB_ENQUETE && enquete.privateFlg && getAdmin() == null){
			String ipAddress = ServletUtil.getRemoteAddr(RequestUtil.getRequest());
			if(!SinaburoUtil.isAllowedSrc(ipAddress, PropertyUtil.getList("IP_ALLOWED_SRC"))){
				response.sendError(HttpServletResponse.SC_NOT_FOUND);
		    	return null;
			}
		}		
		if((member == null || SinaburoConstant.DelFlg.DEL.equals(member.delFlg+"") )&& !StringUtil.equals(enqueteForm.type, "pre")
				&& !SinaburoUtil.contain(enquete.enqueteType, SinaburoConstant.EnqueteType.PUBLIC_COMMENT,SinaburoConstant.EnqueteType.RECRUITMENT,SinaburoConstant.EnqueteType.WEB_ENQUETE)){
			String errMsg = SinaburoViewUtil.getMessage("errors.E058", request.getContextPath() + SinaburoUtil.nvl("/", ""));
			request.setAttribute("errMsgE058", errMsg);
			return getHtmlPath(enqueteForm.template,errorPage);
		}

		//期間チェック
		if(adminUser == null && !StringUtil.equals(enqueteForm.type, "pre")){
			try{
				if (Integer.valueOf(enquete.startDate) > Integer.valueOf(SinaburoUtil.getToDayString())
						|| Integer.valueOf(SinaburoUtil.getToDayString()) > Integer.valueOf(enquete.endDate)) {
					request.setAttribute("errMsg", enquete.expiredMessage);
					return getHtmlPath(enqueteForm.template, errorPage);
				}
			} catch (NumberFormatException e){
				request.setAttribute("errMsg", enquete.expiredMessage);
				return getHtmlPath(enqueteForm.template, errorPage);
			}
		}

		if(!SinaburoUtil.contain(enquete.enqueteType,SinaburoConstant.EnqueteType.WEB_ENQUETE,
			SinaburoConstant.EnqueteType.RECRUITMENT,
			SinaburoConstant.EnqueteType.PUBLIC_COMMENT)){

			if(adminUser == null && !StringUtil.equals(enqueteForm.type, "pre") //&& !enquete.enqueteType.equals(SinaburoConstant.EnqueteType.ORGANIZATION_CONTRIBUTE)
					                                                            && !enquete.enqueteType.equals(SinaburoConstant.EnqueteType.PUBLIC_COMMENT) ){
				 // 回答回数チェック ※管理者はチェックしない
				if(replyService.getAnswerTimes(member.memberId,enquete.enqueteId) >= template.replyTimesLimit  ){
					request.setAttribute("errMsg", enquete.exceedMessage);
					return getHtmlPath(enqueteForm.template,errorPage);
				}
			}
		}
		ArrayList<Question> questionList = questionService.findAllOrderByEnqueteId(enqueteForm.eid);

		for (Question question : questionList) {
			if(StringUtil.equals("6", question.controlId+"") ){
				enqueteForm.organizationListFor1Percent = organizationService.findAllOrderByNo();
			}
		}

		//予約語を変更する。
		if(enquete.enqueteType ==SinaburoConstant.EnqueteType.PUBLIC_COMMENT
				||enquete.enqueteType ==SinaburoConstant.EnqueteType.WEB_ENQUETE
				||enquete.enqueteType ==SinaburoConstant.EnqueteType.RECRUITMENT){
			String startDate="";
			String endDate="";
			VelocityTool tools = new VelocityTool();
			if(StringUtil.isNotBlank(enquete.startDate)){
				startDate=tools.addSlashDate(enquete.startDate);  
			}
			
			if(StringUtil.isNotBlank(enquete.endDate)){
				endDate=tools.addSlashDate(enquete.endDate);  
			}
			
			enquete.header=enquete.header.replace("%anqueteName%", enquete.enqueteName).replace("%startYmd%", startDate).replace("%endYmd%", endDate);
			enquete.footer=enquete.footer.replace("%anqueteName%", enquete.enqueteName).replace("%startYmd%", startDate).replace("%endYmd%", endDate);
			enquete.endMessage=enquete.endMessage.replace("%anqueteName%", enquete.enqueteName).replace("%startYmd%", startDate).replace("%endYmd%", endDate);
			enquete.expiredMessage=enquete.expiredMessage.replace("%anqueteName%", enquete.enqueteName).replace("%startYmd%", startDate).replace("%endYmd%", endDate);
			enquete.exceedMessage=enquete.exceedMessage.replace("%anqueteName%", enquete.enqueteName).replace("%startYmd%", startDate).replace("%endYmd%", endDate);

		}

		enqueteForm.enquete = enquete;
		enqueteForm.questionList = questionList;

		enqueteForm.initCount = "1";//初期表示

		return getHtmlPath(enqueteForm.template,indexPage);

	}

	/**
	 * アンケート回答確認画面
	 */
	@Execute(validator = false,reset="valueReset")
	public String confirm() {

		ActionMessages actionMessages =enqueteValidate();
		if(actionMessages != null && !actionMessages.isEmpty()){
			addErrorMessage("errorheader",  "errors.enqheader");
			return getHtmlPath(enqueteForm.template,indexPage);
		}

		TokenProcessor.getInstance().saveToken(request);

		//ログインしたユーザーのみ閲覧可能
		if(enqueteForm.member == null && !StringUtil.equals(enqueteForm.type, "pre") && getMember() == null && getAdmin() == null && isLoginTarget(enqueteForm.enquete))return "/user/login/";

		//1%団体の場合は団体IDで団体名を設定。
		List<Organization> organizationList = organizationService.findAllOrderByNo();
		HashMap<String, String>  organizationMap = new HashMap<String, String>();
		for (Organization organization : organizationList) {
			organizationMap.put(organization.organizationId.toString(), organization.organizationName);
		}
		enqueteForm.organizationMap=organizationMap;


		//アンケート回答確認画面へ
		return getHtmlPath(enqueteForm.template,confirmPage);
	}
	
	public EnqueteSumBatchAction enqueteSumBatchAction;
	/**
	 * アンケート回答確認画面でアンケート回答を押下した場合の処理
	 * @throws Exception 
	 */
	@Execute(validator = false)
	public String regist() throws Exception{

		if (!TokenProcessor.getInstance().isTokenValid(request, true)) {
			addError(SinaburoViewUtil.getMessage("errors.S999"));
			return "/error/doubleAction.html";
		}
		if(StringUtil.equals(enqueteForm.type, "pre")){
			return getHtmlPath(enqueteForm.template,endPage);
		}

		ActionMessages actionMessages = enqueteValidate();
		if (actionMessages != null && !actionMessages.isEmpty()) {
			addErrorMessage("errorheader", "errors.enqheader");
			return getHtmlPath(enqueteForm.template, indexPage);
		}

		Member member = getMember();
		member = member == null ? enqueteForm.member:member;
		Enquete enquete = enqueteService.findById(Integer.parseInt(enqueteForm.eid));
		Template template = templateService.findByenqueteType(enquete.enqueteType);

		 // 回答回数チェック ※管理者はチェックしない
		if(!SinaburoUtil.contain(enqueteForm.enquete.enqueteType, SinaburoConstant.EnqueteType.WEB_ENQUETE,SinaburoConstant.EnqueteType.PUBLIC_COMMENT,SinaburoConstant.EnqueteType.RECRUITMENT)
				&&
				replyService.getAnswerTimes(member.memberId,enquete.enqueteId) >= template.replyTimesLimit  ){
			request.setAttribute("errMsg", enquete.exceedMessage);
			return getHtmlPath(enqueteForm.template,errorPage);
		}
		
		boolean isNoCheckEnquete=false;
		if( (isNoCheckEnquete=SinaburoUtil.contain(enqueteForm.enquete.enqueteType, SinaburoConstant.EnqueteType.WEB_ENQUETE,SinaburoConstant.EnqueteType.PUBLIC_COMMENT,SinaburoConstant.EnqueteType.RECRUITMENT))
			||
				(getAdmin() == null ) ){//管理者の場合更新処理は行わない。
			//ログインしたユーザーのみ閲覧可能
			member=member==null?enqueteForm.member:member;
			if(!isNoCheckEnquete && member  == null)return "/user/login/";
			// ユーザ再取得
			if(member != null){
				member = memberService.findById(member.memberId);
			}
			//回答結果を登録する。
			replyService.replyRegistAndMailSendLogic(member,enqueteForm.questionList,enqueteForm.enquete, isNoCheckEnquete);
			if (getMember() != null) {
				getMember().pointNum = member.pointNum;
			}
			
			if(enqueteForm.enquete.enqueteType == SinaburoConstant.EnqueteType.EMONITOR
			   || enqueteForm.enquete.enqueteType == SinaburoConstant.EnqueteType.WEB_ENQUETE){
				enqueteSumBatchAction.enqueteSumBatchForm.eid=enqueteForm.eid;
				enqueteService.enqueteSumBatch(enqueteSumBatchAction.enqueteSumBatchForm, getAdmin());
			}
		}

		//複数タブ異常チェック
		if (!StringUtils.isEmpty(enqueteForm.chkeid) && !StringUtils.isEmpty(enqueteForm.eid)) {
			//chkeidとeid比較 違っている場合はアラートメール送信へ
			if (!enqueteForm.chkeid.equals(enqueteForm.eid)){
				String loginId = "";
				if (member != null && member.loginId != null) {
					loginId = member.loginId;
				}
				replyService.sendReplyAlertMail(enqueteForm.eid, enqueteForm.chkeid, loginId);
			}
		}
		
		//アンケート回答完了画面へ
		return getHtmlPath(enqueteForm.template,endPage);
	}

	/**
	 * 団体寄付
	 * @return
	 * @throws MessagingException
	 * @throws UnsupportedEncodingException
	 * @throws SystemException
	 */
	@Execute(validator = false)
	public String registOrganization() throws UnsupportedEncodingException, MessagingException {
		if (!TokenProcessor.getInstance().isTokenValid(request, true)) {
			addError(SinaburoViewUtil.getMessage("errors.S999"));
			return "/error/doubleAction.html";
		}
		if(StringUtil.equals(enqueteForm.type, "pre")){
			return getHtmlPath(enqueteForm.template,endPage);
		}

		Member member = getMember();
		member = member == null ? enqueteForm.member:member;
		Enquete enquete = enqueteService.findById(Integer.parseInt(enqueteForm.eid));
		Template template = templateService.findByenqueteType(enquete.enqueteType);

		if (getAdmin() == null) {// 管理者の場合更新処理は行わない。
			// ログインしたユーザーのみ閲覧可能
			if (member == null)
				return "/user/login/";

			// ユーザ再取得
			member = memberService.findById(member.memberId);

			// 回答回数チェック ※管理者はチェックしない
			if (replyService.getAnswerTimes(member.memberId, enquete.enqueteId) >= template.replyTimesLimit) {
				request.setAttribute("errMsg", enquete.exceedMessage);
				return getHtmlPath(enqueteForm.template, errorPage);
			}

			// 寄付結果を登録する。
			PointDonation pointDonation = new PointDonation();

			pointDonation.memberId = member.memberId;
			// 寄付の場合は下記の情報が設定されているのが大前提
			pointDonation.organizationId = Integer.parseInt(enqueteForm.questionList.get(1).answerList.get(0).answerIdValue);
			pointDonation.pointNum = Integer.parseInt(enqueteForm.questionList.get(0).answerList.get(0).answerIdValue);
			//pointDonationService.insertPointDonation(pointDonation, member.loginId);

			try {
				pointDonationService.organizationDonation(pointDonation, member, enqueteForm.enquete, enqueteForm.questionList);
				if(getMember() != null){
					getMember().pointNum = member.pointNum;
				}
			} catch (Exception e) {
				String errorCode = "E000";
				if (e instanceof SystemException) {
					errorCode = ((SystemException) e).getCode();
				} else if (e instanceof MessagingException) {
					logger.warn("Mail send failed." + e.toString());
					errorCode = "E056";
				}
				addErrorMessage(enqueteForm.questionList.get(0).answerList.get(0).enqueteId + "," + enqueteForm.questionList.get(0).answerList.get(0).questionId, "errors." + errorCode);
				return "/user/enquete/";
			}
		}
		return getHtmlPath(enqueteForm.template,endPage);
	}

	/**
	 *
	 * @return エラーメッセージを変換する。
	 */
	public ActionMessages enqueteValidate(){
		
		if (enqueteForm.questionList == null) {
			logger.error("enqueteValidate: enqueteForm.questionList is null.");
			addErrorMessage("dummy","parameter error. questionList");
			return (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
		}
		
		//ポイント寄付
		Integer orgniz = SinaburoConstant.EnqueteType.ORGANIZATION_CONTRIBUTE;
		valueReplace(enqueteForm);

		//回答数を求め、必須チェックを行う。
		for(Question question : enqueteForm.questionList){
			question.answerCount  = valueCount(question);

			//■必須チェック
			if(question.requiredFlg == SinaburoConstant.requiredFlg.REQUIRED
				&&	question.answerCount.equals(0) ){
					addErrorMessage(question.enqueteId+","+question.questionId,  "errors.required", SinaburoConstant.questionMark.q+question.questionNo);

			//■最小選択数,最大選択数チェック
			}else if(
					question.answerCount > 0 &&
					StringUtil.isNumber(question.minSelectNum+"") && StringUtil.isNumber(question.maxSelectNum+"")
					&& !(question.minSelectNum <= question.answerCount && question.answerCount <= question.maxSelectNum)  ){

				if(question.requiredFlg.equals(1)){//必須の場合
					if(question.minSelectNum.equals(question.maxSelectNum)){

						addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.errMinMaxEqualsOne",//{0}は{1}個選択してください。
							SinaburoConstant.questionMark.q+question.questionNo,question.maxSelectNum.toString());
					}else if(question.minSelectNum < question.maxSelectNum){
						addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.errMinMax",//{0}は{1}~{2}個以内で選択してください。
							SinaburoConstant.questionMark.q+question.questionNo,
										question.minSelectNum.toString(),
										question.maxSelectNum.toString());
					}
				}else{
					
					if(question.minSelectNum < question.maxSelectNum){
						addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.errMinMax",//{0}は{1}~{2}個以内で選択してください。
							SinaburoConstant.questionMark.q+question.questionNo,
										question.minSelectNum.toString(),
										question.maxSelectNum.toString());
					}else{
						addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.errMinMaxEquals",//{0}は{1}個以内で選択してください。
							SinaburoConstant.questionMark.q+question.questionNo,question.maxSelectNum.toString());
					}

				}
			}
		}


		//■条件必須チェック
		for(Question question :enqueteForm.questionList){
			//条件付きが設定されている場合
			if(StringUtil.isNumber(question.condRequiredQuestionNo+"") && question.condRequiredQuestionNo != 0 && StringUtil.isNotBlank(question.condRequiredAnswer)){

				//条件付きの回答を取得
				List<String> condRequiredAnswer = Arrays.asList(question.condRequiredAnswer.split(","));
				Question condRequiredQuestion = null;
				//条件付きの対象になっている設問取得
				for(Question questionTemp :enqueteForm.questionList){
					if(questionTemp.questionId.equals(question.condRequiredQuestionNo)){//question.condRequiredQuestionNo「設問ID」
						condRequiredQuestion = questionTemp;
						break;
					}
				}

				//条件付きの対象になっている設問の回答なのか確認
				for(Answer condRequiredanswer : condRequiredQuestion.answerList){

					if(StringUtil.isBlank(condRequiredanswer.answerIdValue))continue;

					//必須になる回答をした場合ループを抜ける
					if(condRequiredAnswer.contains(condRequiredanswer.answerId+"")){
						if(question.answerCount.equals(0)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.condRequired", SinaburoConstant.questionMark.q+condRequiredQuestion.questionNo,condRequiredanswer.answer);
						}
						break;
					}
				}
			}
		}

		//■自由入力欄必須チェック、文字列制限数チェック
		for(Question question :enqueteForm.questionList){

			for(Answer answer :question.answerList){

				if(  SinaburoUtil.contain(question.controlId,
					  SinaburoConstant.ControlType.TEXTAREA,
					  SinaburoConstant.ControlType.TEXTFIELD)
					  && StringUtil.isNumber(answer.freeTextLimit+"")
					  && (answer.answerIdValue.length() > question.maxInputText || (question.minInputText !=null && answer.answerIdValue.length() < question.minInputText))
						){

					if(SinaburoConstant.ControlType.TEXTAREA == question.controlId){
						addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimit", question.maxInputText.toString());//以内で入力してください。
					}else{

						if(question.minInputText == 0){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimit", question.maxInputText.toString());//以内で入力してください。
						}else{
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitFT", question.minInputText.toString(),question.maxInputText.toString());//以内で入力してください。
						}
					}
				}


				if(!StringUtil.isNumber(answer.freeTextFlg+""))continue;
				//必須チェック
				if(    StringUtil.isNotBlank(answer.answerIdValue)
					&& answer.freeTextFlg == SinaburoConstant.freeTextFlg.REQUIRED
					&& StringUtil.isBlank(answer.answerValue) ){
					//enquete.freeTextRequired ={0}番目の回答は必須です。
					addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.freeTextRequired", answer.answerNo.toString());
					//自由入力欄は必須がないと判断:荒川さんと相談ずみ。→塚田より必須チェックをして欲しいということでコメントを外す
				}

				//文字列制限数チェック
				if(       !StringUtil.isBlank(answer.answerValue)
						&& StringUtil.isNumber(answer.freeTextLimit+"")
						&& answer.freeTextLimit > 0
						&& answer.answerValue.length() > answer.freeTextLimit
						){
					//enquete.freeTextLimit ={0}番目の回答は{1}文字以内で入力してください。
					addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.freeTextLimit", answer.answerNo.toString(),answer.freeTextLimit.toString());

				}

				//テキストフィルドの文字チェック
				if(question.controlId == SinaburoConstant.ControlType.TEXTFIELD){
					String answerValueTemp = orgniz == enqueteForm.enquete.enqueteType ?  answer.answerIdValue :answer.answerIdValue;
					switch (question.inputTextLimit) {
					case 1://半角数字
						if(StringUtil.isNotBlank(answerValueTemp)) {
							if (!SinaburoUtil.isHanaku09(answerValueTemp)){
								addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "半角数字のみ");
							}
							else if (enqueteForm.enquete.enqueteType == EnqueteType.ORGANIZATION_CONTRIBUTE) {
								if (answerValueTemp.length() > 10) {
									addErrorMessage(question.enqueteId+","+question.questionId,  "labels.textLengthOrver", "数値");
								}
								else if (Long.parseLong(answerValueTemp) % 10 != 0) {
									addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textUnit", "10ポイント");
								}
								else{
									if(!StringUtil.equals(enqueteForm.type, "pre")){
										if(getMember() != null){
											if(Long.parseLong(answerValueTemp) > getMember().pointNum) {
												addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textOverMaxPoint");
											}
										} else {
											if(Long.parseLong(answerValueTemp) > memberService.findById(enqueteForm.member.memberId).pointNum) {
												addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textOverMaxPoint");
											}
										}
									}
								}
							}
						}

						break;
					case 2://半角英数字
						if(StringUtil.isNotBlank(answerValueTemp  ) && !SinaburoUtil.isHanakuE09(answerValueTemp)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "半角英数字のみ");
						}
						break;
					case 3://全角カナ
						if(StringUtil.isNotBlank(answerValueTemp  ) && !SinaburoUtil.isZenkakuKana(answerValueTemp)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "全角カナのみ");
						}
						break;
					case 4://全角
						if(StringUtil.isNotBlank(answerValueTemp  ) && !SinaburoUtil.isZenkaku(answerValueTemp)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "全角のみ");
						}
						break;
					case 5://郵便番号
						if(StringUtil.isNotBlank(answerValueTemp  ) && !SinaburoUtil.isPostNo(answerValueTemp)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "郵便番号");
						}
						break;
					case 6://電話番号
						if(StringUtil.isNotBlank(answerValueTemp  ) && !SinaburoUtil.isPhoneNo(answerValueTemp)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "電話番号");
						}
						break;
					case 7://メールアドレス
						if(StringUtil.isNotBlank(answerValueTemp  ) && !SinaburoUtil.emailCheck(answerValueTemp)){
							addErrorMessage(question.enqueteId+","+question.questionId,  "enquete.textLimitSeigen", "メールアドレス");
						}
					default:
						break;
					}
				}

				if(question.controlId == SinaburoConstant.ControlType.HIDUKE && StringUtil.isNotEmpty(answer.answerValue)){

					if(!SinaburoUtil.checkDate(answer.answerValue)){
						addErrorMessage(question.enqueteId+","+question.questionId, "errors.E033");
						addErrorMessage(question.enqueteId+","+question.questionId + "_1", "errors.E033_1");
						addErrorMessage(question.enqueteId+","+question.questionId + "_2", "errors.E033_2");
					}else if(!SinaburoUtil.checkDate(answer.answerValue)){
						addErrorMessage(question.enqueteId+","+question.questionId, "errors.D044");
					}else if((StringUtil.isNotBlank(question.startymd) && StringUtil.isNotBlank(question.endymd) )
							&& !SinaburoUtil.dateFromToCheck(question.startymd,question.endymd,answer.answerValue)){
						addErrorMessage(question.enqueteId+","+question.questionId, "errors.range",SinaburoConstant.questionMark.q+question.questionNo.toString(),question.startymd,question.endymd);//{0}は{1}と{2}の間でなければいけません。
					}else if(StringUtil.isNotBlank(question.startymd) 
							&& !SinaburoUtil.dateFromToCheck(question.startymd,question.endymd,answer.answerValue)){
						addErrorMessage(question.enqueteId+","+question.questionId, "errors.D045",SinaburoConstant.questionMark.q+question.questionNo.toString(),question.startymd+"以降");//{0}は{1}と{2}の間でなければいけません。
					}else if(StringUtil.isNotBlank(question.endymd) 
							&& !SinaburoUtil.dateFromToCheck(question.startymd,question.endymd,answer.answerValue)){
						addErrorMessage(question.enqueteId+","+question.questionId, "errors.D045",SinaburoConstant.questionMark.q+question.questionNo.toString(),question.endymd+"以前");//{0}は{1}と{2}の間でなければいけません。
					}

				}
			}
		}

		return (ActionMessages)request.getAttribute(Globals.ERROR_KEY);
	}


	/**
	 * 設問ごとに回答された数。
	 * @param argQuestion
	 * @return argQuestionに入力された数
	 */
	private int valueCount(Question argQuestion){
		int requiredCnt=0;
		for (Answer answer : argQuestion.answerList ) {
			//
			if(argQuestion.controlId == SinaburoConstant.ControlType.SELECTMENU){
				requiredCnt += StringUtil.isNotBlank(answer.answerIdValue) && !StringUtil.equals(EnqueteRegistAction.selectKuhaku,answer.answer) ? 1 : 0;
			}else if(argQuestion.controlId == SinaburoConstant.ControlType.HIDUKE){
				requiredCnt += StringUtil.isBlank(answer.answerValue) ? 0 : 1;
			}else{
				requiredCnt += StringUtil.isBlank(answer.answerIdValue) ? 0 : 1;
			}

		}

		return requiredCnt;
	}

	/**
	 * 値を設定し直す。
	 * @param agEnqueteForm
	 */
	private void valueReplace(EnqueteForm agEnqueteForm){
		//ラジオボタンの場所移動(ラジオボタンは同じ名前にする必要があるため)
		String answerRadioValue = "";

		//例外対応
		if (agEnqueteForm.questionList == null) {
			//前工程で判定済み
			return;
		}
		for( Question  question: agEnqueteForm.questionList) {

			if(question.controlId == SinaburoConstant.ControlType.RADIO){
				for (int i=0;i< question.answerList.size();i++) {
					Answer answer = question.answerList.get(i);

					//answer.answerRadioValue 選択されたIndexが設定されている。
					if(!StringUtil.isBlank(answer.answerIdValue)){
						answerRadioValue = answer.answerIdValue;
						answer.answerIdValue = "";
						question.answerList.get(Integer.parseInt(answerRadioValue)).answerIdValue = answerRadioValue;
						break;
					}
				}
			}else if(question.controlId == SinaburoConstant.ControlType.SELECTMENU){
				String answerIdValue ="";
				for (int i=0;i< question.answerList.size();i++) {
					Answer answer = question.answerList.get(i);

					answerIdValue = StringUtil.isNotBlank(answer.answerIdValue) ? answer.answerIdValue :answerIdValue;



					if(StringUtil.equals(answerIdValue, answer.answerId.toString()) ){
						answer.answerIdValue = answerIdValue;
					}else{
						answer.answerIdValue="";
					}

				}
			}
		}
	}

	private static final String indexPage="";
	private static final String confirmPage="Confirm";
	private static final String endPage="End";
	//private static final String resultPage="Result";
	private static final String errorPage="Error";


	/**
	 * テンプレートタイプにより、該当遷移先を戻す。
	 * @param template
	 * @param html "":初期表示,Confirm:確認,End:完了,URL:URL確認
	 * @return 表示するパス
	 */
	private String getHtmlPath(Template template,String html){

		String prefix = "/user/enquete/enquete";

		AgtVelocityViewServlet avvs = new AgtVelocityViewServlet();
		if(avvs.getDevice().equals(SinaburoConstant.AccessType.PC)){
			if(StringUtil.equals("2", enqueteForm.kind)){
				prefix = "/mb/"+prefix;
			}else if(StringUtil.equals("3", enqueteForm.kind)){
				prefix = "/sp/"+prefix;
			}
		}

		html = StringUtil.isBlank(html) ? "" : html;

		switch (template.enqueteType) {
		case SinaburoConstant.EnqueteType.EMONITOR:
		case SinaburoConstant.EnqueteType.ORGANIZATION_CONTRIBUTE:
		case SinaburoConstant.EnqueteType.POINT_EXCHANGE:
			return prefix+(html)+".html";//①
		case SinaburoConstant.EnqueteType.PUBLIC_COMMENT:
			return prefix+(html)+"_pub.html";//②
		case SinaburoConstant.EnqueteType.WEB_ENQUETE:
		case SinaburoConstant.EnqueteType.RECRUITMENT:
			return prefix+(html)+"_web_rec.html";//③
		//case SinaburoConstant.EnqueteType.RECRUITMENT:
		//	return prefix+(html)+"4.html";//④
		}

		return "/";
	}
	public MemberService memberService;
	/**
	 * ログイン必要なアンケートの場合はtrue
	 * @return
	 */
	private boolean isLoginTarget(Enquete enquete){


		if(enquete.enqueteType == SinaburoConstant.EnqueteType.EMONITOR
			|| 	enquete.enqueteType == SinaburoConstant.EnqueteType.ORGANIZATION_CONTRIBUTE
				){
			return true;
		}
		return false;
	}
}