package jp.agentec.abook.abv.ui.common.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.json.adf.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import jp.agentec.abook.abv.bl.acms.type.OperationType;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.Callback;
import jp.agentec.abook.abv.bl.common.CommonExecutor;
import jp.agentec.abook.abv.bl.common.Constant;
import jp.agentec.abook.abv.bl.common.constant.ABookKeys;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.ABVDataCache;
import jp.agentec.abook.abv.bl.data.dao.AbstractDao;
import jp.agentec.abook.abv.bl.data.dao.TaskReportDao;
import jp.agentec.abook.abv.bl.download.ContentFileExtractor;
import jp.agentec.abook.abv.bl.download.ContentRefreshApiProfile;
import jp.agentec.abook.abv.bl.dto.ContentDto;
import jp.agentec.abook.abv.bl.dto.MydataDto;
import jp.agentec.abook.abv.bl.dto.OperationDto;
import jp.agentec.abook.abv.bl.dto.OperationTaskDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.ContentReadingLogLogic;
import jp.agentec.abook.abv.bl.logic.LockReportLogic;
import jp.agentec.abook.abv.bl.logic.OperationLogic;
import jp.agentec.abook.abv.bl.logic.ReportStatusLogic;
import jp.agentec.abook.abv.bl.logic.UnlockReportLogic;
import jp.agentec.abook.abv.bl.websocket.MeetingManager;
import jp.agentec.abook.abv.cl.environment.DeviceInfo;
import jp.agentec.abook.abv.cl.helper.ContentMarkingFileHelper;
import jp.agentec.abook.abv.cl.util.AndroidStringUtil;
import jp.agentec.abook.abv.cl.util.ContentLogUtil;
import jp.agentec.abook.abv.cl.util.LocationManagerUtil;
import jp.agentec.abook.abv.cl.util.PreferenceUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType.DefPrefKey;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType.UserPrefKey;
import jp.agentec.abook.abv.ui.common.constant.ErrorCode;
import jp.agentec.abook.abv.ui.common.constant.ErrorMessage;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.abook.abv.ui.common.util.PatternStringUtil;
import jp.agentec.abook.abv.ui.common.view.ABVPopupListWindow;
import jp.agentec.abook.abv.ui.home.helper.ABookCheckWebViewHelper;
import jp.agentec.abook.abv.ui.home.helper.ABookPermissionHelper;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.abook.abv.ui.viewer.activity.NoPdfViewActivity;
import jp.agentec.abook.abv.ui.viewer.foxitPdf.FoxitPdfCore;
import jp.agentec.adf.util.DateTimeFormat;
import jp.agentec.adf.util.DateTimeUtil;
import jp.agentec.adf.util.FileUtil;
import jp.agentec.adf.util.StringUtil;

import static jp.agentec.abook.abv.bl.acms.client.json.OperationDataJSON.Message;
import static jp.agentec.abook.abv.bl.acms.client.json.OperationDataJSON.ReportStartDate;
import static jp.agentec.abook.abv.bl.acms.client.json.OperationDataJSON.ReportStatus;
import static jp.agentec.abook.abv.bl.acms.client.json.OperationDataJSON.TaskKey;
import static jp.agentec.abook.abv.bl.acms.client.json.OperationDataJSON.TaskReportId;


public abstract class ABVContentViewActivity extends ABVAuthenticatedActivity {
	private static final String TAG ="ABVContentViewActivity";

	/** 報告・閲覧コンテンツ側の新着更新は画面別APIセット（事業者共通）。 */
	@Override
	protected ContentRefreshApiProfile getContentRefreshApiProfile() {
		return ContentRefreshApiProfile.REPORT_LIST_SCREEN;
	}
	public final static int ABOOK_CHECK_TASK_IMAGE = 103;
	public final static int ABOOK_CHECK_TASK_VIDEO = 104;
	protected final static int ABOOK_CHECK_SELECT_SCENE = 105;

	protected long contentId;// 表示中のコンテンツID
	protected long objectId;  // オブジェクトID（オブジェクト用のActivityのときのみ使用）
	protected int objectPageNumber; // オブジェクトが配置されているページ番号（オブジェクト用のActivityのときのみ使用）
	protected MeetingManager meetingManager; // 遠隔連動
	protected boolean mActivityFinishFlg = false;
	protected String mContentDir;
	protected String contentType;
	protected ABVPopupListWindow mShowedPopupWindow = null;
	protected int readingLogId;
    protected String path; // PanoViewController
	protected boolean readingLogFlg = true; // HTMLWebViewActivity,PreviewActivityがPDFのアクションとして呼び出されることがあるので、その場合ログは記録しない
	protected ImageButton subMenuBtn;
	protected ImageButton exitMeetingBtn;
	protected ConcurrentHashMap<Long, Object> objectIdPopupMap = new ConcurrentHashMap<>();

    protected int mCurrentPageNumber = 0; // 表示中のページ番号(0からスタート)

	public Long mOperationId;
	protected int mXWalkOpenType = -1;
	protected int mOperationType;
	private int mReportType;
    protected int mEnableReportHistory; //0:履歴無し 1:履歴可
	// 報告可能区分
	protected int mEnableReportEdit; //0:報告無し 1:報告可
	protected String mContentPath;
	protected int mStatusCode;
	protected boolean isOperationPdf = false;
    protected OperationDto operationDto = null;
    protected String linkUrl;

	protected TextView operationNameTitle;
	protected Button operationHomeButton;
	protected ImageButton taskListButton;
    protected ImageButton helpButton;
	// 簡易帳票印刷ボタン
	protected ImageButton printButton;

    protected boolean isPageFinished;
    protected Double latitude;
    protected Double longitude;

    protected String mCmd;
    protected String mTaskKey;
    protected String mAttachedFileName;
    protected File mLocalFile;
	public boolean isLinkedContent;
	public int pageNo;

	public int mButtonStatus;      // 保存ボタンチェック
	protected boolean mAddReport;  // 作業追加区分

	private boolean mLocationSendResult;	// GPS送信フラグ

	@SuppressLint("SourceLockedOrientationActivity")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent intent = getIntent();
	    contentId = intent.getLongExtra(ABookKeys.CONTENT_ID, 0);
	    contentType = intent.getStringExtra(ABookKeys.CONTENT_TYPE);
        objectId = intent.getLongExtra("objectId", -1);
        objectPageNumber = intent.getIntExtra("pageNumber", -1);
        readingLogId = intent.getIntExtra("readingLogId", -1);
        path = intent.getStringExtra("path");
		isLinkedContent = intent.getBooleanExtra("isLinkedContent", false);
		mOperationId = intent.getLongExtra(ABookKeys.OPERATION_ID, -1);

        if (!isLinkedContent) {
			operationDto = AbstractLogic.getLogic(OperationLogic.class).getOperation(mOperationId);
            mXWalkOpenType = intent.getIntExtra(Constant.ABookCheck.XWALK_OPEN_TYPE, Constant.XWalkOpenType.DEFAULT);
            if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT || mXWalkOpenType == Constant.XWalkOpenType.PANO_EDIT) {
                if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT) {
                    mOperationType = operationDto.operationType;
                    mReportType = operationDto.reportType;
                    if (mOperationType != OperationType.PDF && isNormalSize()) {
                        // 縦画面固定
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            // 添付ファイル表示のため、キャッシュディレクトリにコピーする
                            ABookCheckWebViewHelper.getInstance().allCopyTaskAttachedMovieFileToCache(mOperationId, getContentId(), operationDto);
                        }
                    }).start();
                    mStatusCode = 0;
                }
				mEnableReportEdit = operationDto.enableReportEdit;
                mEnableReportHistory = operationDto.enableReportHistory;

                linkUrl = intent.getStringExtra("LINKURL"); // LinkURL

                if (operationDto != null && operationDto.operationType == OperationType.PDF) {
                    isOperationPdf = true;
                }
            }
        }

        // 遠隔連動
        meetingManager = MeetingManager.getInstance();
     	
        mContentDir = getIntent().getStringExtra(FILEPATH);

        // Activity登録
        if (objectId == -1) {
        	ActivityHandlingHelper.getInstance().setContentViewActivity(this);
			ContentDto dto = contentDao.getContent(contentId);
			if (dto != null) {
				// 閲覧履歴保存
				contentDao.updateContentReadingDate(DateTimeUtil.getCurrentTimestamp(), getContentId());
			}
        } else {
            ActivityHandlingHelper.getInstance().setObjectViewActivity(this);
        }
        
		contentDownloader.pauseAll();
		
		showUpdateContentAlert(contentId);
	}

	private void showUpdateContentAlert(long contentId) {
		if (meetingManager.isConnected()) {
			ContentDto contentDto = contentDao.getContent(contentId);
			if (contentDto.updatedFlg) {
				handler.post(new Runnable() {
					@Override
					public void run() {
						final ABookAlertDialog confirmDialog = AlertDialogUtil.createAlertDialog(ABVContentViewActivity.this, R.string.confirm);
						confirmDialog.setCancelable(false);
						confirmDialog.setMessage(R.string.msg_content_to_be_updated);
						confirmDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
							@Override
                            public void onClick(DialogInterface dialog, int whichButton) {
								confirmDialog.dismiss();
							}
						});
						confirmDialog.show();
					}
				});
			}
		}
	}

	@Override
	protected void onResume() {
	    super.onResume();

		try {
			if (readingLogFlg) {
				readingLogId = ContentLogUtil.getInstance().startContentReadLog(this, contentId, getABVUIDataCache().getPermissionAccessLocation());
		    }
		} catch (Exception e) {
			Logger.e("Exception", e);
			handleErrorMessageToast(ErrorCode.E107);
		}
		
		try {
			if (ABVEnvironment.getInstance().networkAdapter.isNetworkConnected()) {
				ActivityHandlingHelper.getInstance().reconnectMeeting(); // 会議室入室時に接続切れだった場合に再接続する
			}
		} catch (Exception e) {
			Logger.e(TAG, "reconnectMeeting error.", e); // ignore
		}
	}

	@Override
	protected void onClickHomeButton() {
		super.onClickHomeButton();
	}

	@Override
    protected void onStart() {
        super.onStart();
    }
   
	@Override
    protected void onPause() {
       super.onPause();
	}

	@Override
    protected void onStop() {
        super.onStop();
        
        if (!DeviceInfo.isForegrdound(getApplicationContext()) && readingLogFlg) {
        	ContentReadingLogLogic logic = AbstractLogic.getLogic(ContentReadingLogLogic.class);
        	logic.pauseContentReadLog(contentId);
        }
    }

	@Override
    protected void onDestroy() {
		Logger.d(TAG, "onDestroy");
		if (readingLogFlg) {
			ContentReadingLogLogic logic = AbstractLogic.getLogic(ContentReadingLogLogic.class);
			logic.endContentReadLog(contentId);
		}
		
		super.onDestroy();

		if (meetingManager.isSendable() && objectId != -1) {
			meetingManager.sendWs(MeetingManager.CMD_CLOSEPOPUP, contentId, objectPageNumber, objectId, null);
		}

        if (meetingManager.isSubscribed()) {
        	ActivityHandlingHelper.getInstance().refreshMeetingListActivity();
        }
        if (objectId == -1) {
            ActivityHandlingHelper.getInstance().removeContentViewActivity(this);
        } else {
            ActivityHandlingHelper.getInstance().removeObjectViewActivity(this);
        }

		//キャッシュを使用しない場合、ディレクトリが残っていれば削除
		if (!getRBoolean(R.bool.use_cache) && objectId == -1) {
			ContentFileExtractor.getInstance().removeContentCash(contentId);
		}
	}
	
	public long getContentId() {
		return contentId;
	}

	public long getObjectId() {
		return objectId;
	}

	public void performRemoteEvent(final JSONObject json) {
	}
	
	protected boolean isCursorModeEnable() {
	    if (isOperationPdf()) {
            return false;
        } else {
            return PreferenceUtil.get(this, DefPrefKey.CURSOR_ENABLE, false);
        }
	}
	
	protected void initError() {
		ContentFileExtractor.getInstance().removeContentCash(contentId);
		handleErrorMessageToast(ErrorCode.E105);
		mActivityFinishFlg = true;
		finish();
	}
	
	public static void errorMessageDialog(final Context context,final int title, final ErrorCode value) {
		// アラート内レイアウト
		TextView txtMsg = new TextView(context);	
		txtMsg.setText(R.string.delete_message);
		txtMsg.setTextSize(20);
		txtMsg.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
		txtMsg.setText(ErrorMessage.getMessageByErrorCode(context, value));
				
		int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
		int FP = ViewGroup.LayoutParams.MATCH_PARENT;
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(FP, WC);
		params.leftMargin = 10;
		LinearLayout layout = new LinearLayout(context);
		layout.addView(txtMsg, params);
		layout.setLayoutParams(new LinearLayout.LayoutParams(FP, WC));
		
		ABookAlertDialog alert = AlertDialogUtil.createAlertDialog(context, title);
		alert.setView(layout);
		alert.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int whichButton) {
				dialog.dismiss();
			}
		});
		alert.show();
	}
	
	// 指定ページへのジャンプ
	@Override
    public void startContentViewActivity(long contentId, int pageNum) {
			Logger.d(TAG, "startContentViewActivity:%s, pageNum=%s", contentId, pageNum);
			releaseInit();
			Intent intent = new Intent();
			intent.putExtra("page", pageNum);
//			intent.putExtra("removeOtherActivity", true); // これは行わない
			startContentViewActivity(intent, contentId);
		}
	
	/**
	 * 閲覧履歴一覧を表示する
	 * @param anchor ツールバーの閲覧履歴ボタン
	 */
	protected void showHistoryList(View anchor) {
		mShowedPopupWindow = new ABVPopupListWindow(this);
		if (isNormalSize()) {
			mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_normal));
		} else {
			mShowedPopupWindow.setWidth(getRDimensionSize(R.dimen.popup_size_large));
		}
		
		ArrayList<String> menuNameList = new ArrayList<>();
		
		final List<MydataDto> list = contentDao.getReadingContent();
		list.remove(0); // 自分自身を削除

		for (MydataDto MyDataDto : list) {
			menuNameList.add(MyDataDto.contentName);
		}
		
		if (menuNameList.size() == 0) {
			menuNameList.add(getRString(R.string.no_content_history));
		}
		
		mShowedPopupWindow.setRepresentNames(menuNameList);
		mShowedPopupWindow.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if (list.size() > 0) {
					MydataDto dto = list.get(position);
					startContentViewActivity(dto.contentId, dto.pageNum);
					mShowedPopupWindow.dismiss();
				}
			}
		});
		
		mShowedPopupWindow.showAsDropDown(anchor);
	}
	
	protected void releaseInit() {
		// Activity終了時に初期化が必要な処理を作成
		// 各自必要な場合に実装する
	}
	
	/**
	 * 会議室を正常に退室
	 */
	protected void setMeetingEnteredFlg() { // TODO: 移動
		PreferenceUtil.putUserPref(this, UserPrefKey.MEETING_ENTERED_FLG, false);
	}

	protected void sendPromoteRequest() {
		JSONObject json = new JSONObject();
		json.put(MeetingManager.ID, meetingManager.getSkey());
		json.put(MeetingManager.LOGIN_ID, ABVDataCache.getInstance().getMemberInfo().loginId);
		meetingManager.sendWs(MeetingManager.CMD_PRESENTERREQUEST, getContentId(), null, null, json);
		ABVToastUtil.showMakeText(this, getString(R.string.msg_request_promotion), Toast.LENGTH_SHORT);
	}

	@Override
    public void finish() {
		// ホームをリロードさせる
		ActivityHandlingHelper.getInstance().setRequireHomeReload(true);
		super.finish();
		Logger.d(TAG, "finish");
	}

    protected void commonConfigureRemote() {
    }

	public void configureRemote() {
	}
	
	public void switchMeetingExitButton() {
		handler.post(new Runnable() {
			@Override
			public void run() {
				if (meetingManager.isSendable()) { // 会議室退室ボタン表示
					RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
					params.addRule(RelativeLayout.LEFT_OF, R.id.btn_exitMeeting);
					params.addRule(RelativeLayout.CENTER_VERTICAL);
					params.rightMargin = (int) (getResources().getDisplayMetrics().density * 5);
					subMenuBtn.setLayoutParams(params);
					exitMeetingBtn.setVisibility(View.VISIBLE);

					if (helpButton != null && helpButton.getVisibility() == View.VISIBLE) {
                        helpButton.setLayoutParams(params);
                    }
				}
				else { // 会議室退室ボタン非表示
					exitMeetingBtn.setVisibility(View.GONE);
					RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(WC, WC);
					params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
					params.addRule(RelativeLayout.CENTER_VERTICAL);
					params.rightMargin = (int) (getResources().getDisplayMetrics().density * 5);
					subMenuBtn.setLayoutParams(params);

                    if (helpButton != null && helpButton.getVisibility() == View.VISIBLE) {
                        helpButton.setLayoutParams(params);
                    }
				}
			}
		});
	}
	
	protected void showMeetingExitDialog() {
		ABookAlertDialog alert = AlertDialogUtil.createAlertDialog(this, R.string.confirm);
		if (meetingManager.isOwner()) {
			alert.setMessage(AndroidStringUtil.format(this, R.string.msg_leave_all, R.string.meeting_leave));
		}
		else {
			alert.setMessage(R.string.msg_leave);
		}
		alert.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int whichButton) {
				// 遠隔連動中に保存したマーキングファイルを削除
				ContentMarkingFileHelper contentMarkingFileHelper = new ContentMarkingFileHelper();
				contentMarkingFileHelper.deleteRemoteMarkingFile(contentId);

				setMeetingEnteredFlg();
		    	if (meetingManager.isOwner()) {
		    		try {
						meetingManager.deleteMeeting();
					} catch (Exception e) {
						Logger.e(TAG, "showMeetingExitDialog deleteMeeting error", e);
						ABVToastUtil.showMakeText(ABVContentViewActivity.this, getString(R.string.E126), Toast.LENGTH_SHORT);
					}
		    	}
				//会議室に参加する前のonCloseと識別するため
	    		meetingManager.close();
				configureRemote();

				ActivityHandlingHelper handlingHelper = ActivityHandlingHelper.getInstance();
				handlingHelper.saveMeetingInfo(null, null, null, false);
				handlingHelper.finishAllContentViewActivity();
			}
		});
		alert.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
			@Override
            public void onClick(DialogInterface dialog, int whichButton) {
				dialog.cancel();
			}
		});
		alert.show();
	}

	@Override
	protected void onApplicationBroughtFromBackground() {
		new Handler().post(new Runnable() {
			@Override
			public void run() {
				// コンテンツビューワーでは定期パスワード変更以外のチェックを行う
				if (checkForceOfflineLogout()) {
					finish();
				} else if (checkValidAuthTime()) {
					finish();
				}
			}
		});
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		Logger.v(TAG, "[dispatchTouchEvent]:start");
		try {
			return super.dispatchTouchEvent(ev);
		} catch (IllegalArgumentException e) {
			Logger.w(TAG, "dispatchTouchEvent failed.", e);
			//  java.lang.IllegalArgumentException: pointerIndex out of range
			return true;
		}
	}

	@Override
	public boolean contentValidCheckAndDownload(long contentId) {
		return false; // dummy
	}

	protected void setMeetingParticipantCount(boolean isVisible, View toolBar) {
		final TextView textView = (TextView)toolBar.findViewById(R.id.txt_meeting_participant);
		if (textView == null) {
			return;
		}
        textView.setVisibility(View.GONE);
		if (isVisible) {
			if (meetingManager.isConnected() && meetingManager.isOwner()) {
		        textView.setVisibility(View.VISIBLE);
		        CommonExecutor.execute(new Runnable() {
		        	@Override
                    public void run() {
		        		final int count = meetingManager.getParticipantCount();
		        		handler.post(new Runnable() {
							@Override
							public void run() {
								textView.setText(getRString(R.string.meeting_participant_count) + ":" + count);
							}
						});
		        	}
                });
			}
			
		}
	}

	@Override
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (this instanceof NoPdfViewActivity) {
				if(isLinkedContent) {
					goToBack();
				} else {
					this.finish();
					moveToBack();
				}
			} else {
				return super.onKeyUp(keyCode, event);
			}
			return false;
		} else {
			return super.onKeyUp(keyCode, event);
		}
	}

    public int getCurrentPageNumber() {
        return mCurrentPageNumber;
    }

    /**
     * 戻る用コンテンツIDリストをリセット
     */
    public void resetReturnContentIdList () {
		getABVUIDataCache().resetReturnContentIdList();
	}

	/**
	 * 戻る用コンテンツIDリストを取得
	 */
	public List<long[]> getReturnContentIdList() {
		return getABVUIDataCache().getReturnContentIdList();
	}

	/**
	 * コンテンツビューから戻るボタンタップ時の処理
	 */
    public void moveToBack() {
		//戻る用コンテンツIDの数
		int listSize = getReturnContentIdList().size();
        if (listSize == 0) {
            finish();
        } else {
            long[] contentInfo = getReturnContentIdList().get(listSize - 1);
            // 直前のコンテンツが360コンテンツか確認⇒画面遷移ではなくfinish()で廃棄することで戻る
            if (ActivityHandlingHelper.getInstance().hasPreviousPanoContentId(contentInfo[0])) {
                finish();
            } else {
				ActivityHandlingHelper.getInstance().startContentActivity(contentInfo[0], (int) contentInfo[1]);
            }

			getReturnContentIdList().remove(listSize - 1);
        }
    }

	/**
	 * コンテンツビューから戻るボタンタップ時の処理(ABookCheck専用)
	 */
	public void goToBack() {
		releaseInit();
		finish();
	}

    @SuppressLint("SourceLockedOrientationActivity")
	protected void createCheckToolbar() {
		final RelativeLayout fl;
		if (operationDto != null && operationDto.operationType == OperationType.PDF && mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT) {
			fl = (RelativeLayout) findViewById(R.id.RelativeLayout2);
		} else {
			fl = (RelativeLayout) findViewById(R.id.frameTopbar);
		}
        fl.setBackgroundColor(getResources().getColor(R.color.operation_color));

        operationHomeButton = (Button) findViewById(R.id.btn_operation_home);
        operationHomeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mXWalkOpenType == Constant.XWalkOpenType.PANO_EDIT) {
                    ABookAlertDialog alertDialog = AlertDialogUtil.createAlertDialog(ABVContentViewActivity.this, PatternStringUtil.patternToInt(getApplicationContext(),
							R.string.pano_edit,
							getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
					// リソースパターンの適用
					alertDialog.setMessage(PatternStringUtil.patternToString(getApplicationContext(),
							R.string.msg_confirm_save_pano_edit,
							getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
                    alertDialog.setNegativeButton(R.string.cancel, null);
                    alertDialog.setPositiveButton(R.string.ok,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    callUnloadAuth();
                                    dialog.dismiss();
                                    finish();
                                }
                            });
                    alertDialog.show();
                } else {
					// 作業終了する時、作業ID設定して作業一覧で使用するメソットを行う。
					putUserPref(AppDefType.UserPrefKey.SYNC_TARGET_OPERATION_ID, mOperationId);
					finishActivity();  // 開いてる画面を閉じる
				}
            }
        });
        operationHomeButton.setVisibility(View.VISIBLE);

        taskListButton = (ImageButton) findViewById(R.id.btn_show_task_list);
        taskListButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 作業一覧表示
                showTaskList();
            }
        });

        if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT  || mXWalkOpenType == Constant.XWalkOpenType.PANO_EDIT) {
            if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT) {
                if (mOperationType != OperationType.PDF && isNormalSize()) {
                    // 縦画面固定
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                mOperationType = operationDto.operationType;
                String cacheDirPath = ABVEnvironment.getInstance().getContentCacheDirectoryPath(getContentId());
                if (operationDto.operationType == OperationType.LIST) {
                    mContentPath = ABVEnvironment.getInstance().getTaskListDirName(cacheDirPath);
                } else if (operationDto.operationType == OperationType.PDF) {
                    mContentPath = ABVEnvironment.getInstance().getTaskPdfDirName(cacheDirPath);
                } else {
                    mContentPath = ABVEnvironment.getInstance().getPanoImageDirName(cacheDirPath);
                }
                mStatusCode = 0;
            }

            operationNameTitle = (TextView) findViewById(R.id.title);
            operationNameTitle.setText(operationDto.operationName);
            if (isNormalSize()) {
                operationNameTitle.setWidth(getRDimensionSize(R.dimen.operation_title_normal_width));
            } else {
                operationNameTitle.setWidth(getRDimensionSize(R.dimen.operation_title_large_width));
            }
            operationNameTitle.setVisibility(View.VISIBLE);
        }
    }

	/**
	 * 360編集画面を閉じた時、呼び出す
	 */
	public void callUnloadAuth() {
		Logger.v(TAG, "run javaScript for ABookCheck : callUnloadAuth");
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				webViewLoadUrl("javascript:EDC.callUnloadAuth()");
			}
		});
	}

	/**
	 * 作業一覧表示
	 */
	public void showTaskList() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				webViewLoadUrl("javascript:CHK.showTaskList()");
			}
		});
	}

	//以下のメッソドは子ActivityにOverideで使用
	protected void finishActivity() {}
	protected void webViewLoadUrl(String url){}

    public void onClickOperationHome(View v) {
        if (mXWalkOpenType == Constant.XWalkOpenType.PANO_EDIT) {
			// リソースパターンの適用
            ABookAlertDialog alertDialog = AlertDialogUtil.createAlertDialog(ABVContentViewActivity.this, PatternStringUtil.patternToString(getApplicationContext(),
																													R.string.pano_edit,
																													getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
			// リソースパターンの適用
            alertDialog.setMessage(PatternStringUtil.patternToString(getApplicationContext(),
									R.string.msg_confirm_save_pano_edit,
									getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
            alertDialog.setNegativeButton(R.string.cancel, null);
            alertDialog.setPositiveButton(R.string.ok,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            callUnloadAuth();
                            dialog.dismiss();
                            finish();
                        }
                    });
            alertDialog.show();
        } else {
			// 作業終了する時、作業ID設定して作業一覧で使用するメソットを行う。
			putUserPref(AppDefType.UserPrefKey.SYNC_TARGET_OPERATION_ID, mOperationId);  // 作業IDの設定
			finishActivity();  // 開いてる画面を閉じる
        }
    }

    /**
     * Be override
     */
    protected void onActionOperationPdfWebView(Map<String, String> checkParam, OperationTaskDto operationTaskDto) {}

    public void onClickShowHelpView(View v) {
        int helpViewType = 0;
        switch (mStatusCode) {
            case Constant.XWalkWebViewDisplayStatus.InitView:
                if (mXWalkOpenType == Constant.XWalkOpenType.PANO_EDIT) {
                    helpViewType = Constant.HelpViewType.PanoContentEdit;
                } else {
                    switch (mOperationType) {
                        case OperationType.LIST:
                            switch (mXWalkOpenType) {
                                case Constant.XWalkOpenType.TASK_DERECTION:
                                    helpViewType = Constant.HelpViewType.ListOperationDirector;
                                    break;
                                case Constant.XWalkOpenType.TASK_REPORT:
                                    if (operationDto.reportType == Constant.ReportType.RoutineTask) {
                                        helpViewType = Constant.HelpViewType.RoutineTaskOperation;
                                    } else {
                                        helpViewType = Constant.HelpViewType.ListOperationReporter;
                                    }
                                    break;
                            }
                            break;
                        case OperationType.DRAWING:
                        case OperationType.PDF:
                            switch (mXWalkOpenType) {
                                case Constant.XWalkOpenType.TASK_DERECTION:
                                    helpViewType = Constant.HelpViewType.DrawingOperationDirector;
                                    break;
                                case Constant.XWalkOpenType.TASK_REPORT:
                                    helpViewType = Constant.HelpViewType.DrawingOperationReporter;
                                    break;
                            }
                            break;
                        case OperationType.PANO:
                            switch (mXWalkOpenType) {
                                case Constant.XWalkOpenType.TASK_DERECTION:
                                    helpViewType = Constant.HelpViewType.PanoOperationDirector;
                                    break;
                                case Constant.XWalkOpenType.TASK_REPORT:
                                    helpViewType = Constant.HelpViewType.PanoOperationReporter;
                                    break;
                            }

                            break;
                    }
                }
                break;
            case Constant.XWalkWebViewDisplayStatus.TaskView:
                if (mXWalkOpenType == Constant.XWalkOpenType.TASK_DERECTION) {
                    helpViewType = Constant.HelpViewType.DirectorTask;
                } else if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT) {
                    if (operationDto.reportType == Constant.ReportType.RoutineTask) {
                        helpViewType = Constant.HelpViewType.RoutineTaskOperationReport;
                    } else {
                        helpViewType = Constant.HelpViewType.ReportTask;
                    }
                }
                break;
            case Constant.XWalkWebViewDisplayStatus.ReportPreView:
                helpViewType = Constant.HelpViewType.ReportPreview;
                break;
            case Constant.XWalkWebViewDisplayStatus.TaskListView:
                if (mXWalkOpenType == Constant.XWalkOpenType.TASK_DERECTION) {
                    helpViewType = Constant.HelpViewType.DirectorTaskList;
                } else if (mXWalkOpenType == Constant.XWalkOpenType.TASK_REPORT) {
                    helpViewType = Constant.HelpViewType.ReportTaskList;
                }
                break;
        }

        showHelpViewDialog(helpViewType);
    }

    public void commonShouldOverrideUrlLoading (Uri uri, final OperationTaskDto operationTaskDto) {
        //parent method
        Map<String, String> abookCheckParam = new HashMap<String, String>();
        for (String key : uri.getQueryParameterNames()) {
            abookCheckParam.put(key, uri.getQueryParameter(key));
        }
        mCmd = abookCheckParam.get(ABookKeys.CMD);
		if (abookCheckParam.containsKey(ABookKeys.TASK_KEY)) {
			mTaskKey = abookCheckParam.get(ABookKeys.TASK_KEY);
		}

		int taskReportLevel = 0;  // 作業報告レベル（0：報告、１：報告（回答）、２：報告（回答））
		if (abookCheckParam.containsKey(ABookKeys.TASK_REPORT_LEVEL)) {
			taskReportLevel = Integer.parseInt(abookCheckParam.get(ABookKeys.TASK_REPORT_LEVEL));  // 作業報告レベル
		}
		// 作業追加区分の値を取得する
		mAddReport = true;

		// 定期点検の場合、以下のフラグを変更しない（mAddReport trueのみ）
		if (abookCheckParam.containsKey(ABookKeys.ADD_REPORT)) {
			mAddReport = Integer.parseInt(abookCheckParam.get(ABookKeys.ADD_REPORT)) > 0 ? true : false;
		}

		long taskReportId = 0;
		String reportStartDate = "";

		if (operationDto.reportType == Constant.ReportType.RoutineTask && abookCheckParam.get(ABookKeys.TASK_REPORT_ID) != null && abookCheckParam.get(ABookKeys.REPORT_START_DATE) != null) {
			taskReportId = Long.parseLong(abookCheckParam.get(ABookKeys.TASK_REPORT_ID));
			reportStartDate = abookCheckParam.get(ABookKeys.REPORT_START_DATE);
		}

		if (StringUtil.equalsAny(mCmd, ABookKeys.CMD_MOVE_HOT_SPOT, ABookKeys.CMD_INSERT_TASK_REPORT, ABookKeys.CMD_UPDATE_TASK_REPORT,
				ABookKeys.CMD_DELETE_TASK_REPORT, ABookKeys.CMD_CANCEL_TASK_REPORT, ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT, ABookKeys.CMD_CHANGE_TASK_REPORT)) {

			try {
                if (StringUtil.equalsAny(mCmd, ABookKeys.CMD_INSERT_TASK_REPORT, ABookKeys.CMD_UPDATE_TASK_REPORT)) {
					// リソースパターンの適用
					showProgressPopup(PatternStringUtil.patternToString(getApplicationContext(),
										R.string.file_initialization,
										getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
                }

				if (isOperationPdf && operationTaskDto != null && StringUtil.equalsAny(mCmd,
						ABookKeys.CMD_INSERT_TASK_REPORT,
                        ABookKeys.CMD_UPDATE_TASK_REPORT,
                        ABookKeys.CMD_MOVE_HOT_SPOT,
						ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT)) {
					String taskCode = "";

					if (abookCheckParam.get(ABookKeys.TASK_REPORT) != null) {
						JSONObject tastReportJson = new JSONObject(abookCheckParam.get(ABookKeys.TASK_REPORT));
						JSONObject taskJson = tastReportJson.getJSONObject(ABookKeys.TASK);
						Iterator taskKeys = taskJson.keys();
						while (taskKeys.hasNext()) {
							String itemKey = (String) taskKeys.next();
							if (itemKey.startsWith("q_1_")) {
								taskCode = taskJson.getString(itemKey);
							}
						}
					}

					if (abookCheckParam.get(ABookKeys.HOT_SPOT) != null) {
						JSONObject hotSpot = new JSONObject(abookCheckParam.get(ABookKeys.HOT_SPOT));
						hotSpot.put(ABookKeys.SCENE_ID, mCurrentPageNumber + 1);

						hotSpot.put(ABookKeys.PDF_X, operationTaskDto.pdfX);
						hotSpot.put(ABookKeys.PDF_Y, operationTaskDto.pdfY);

						if (!StringUtil.isNullOrEmpty(taskCode)) {
							hotSpot.put(ABookKeys.TASK_CODE, taskCode);
						}

						abookCheckParam.put(ABookKeys.HOT_SPOT, hotSpot.toString());
					}
				}

				final Callback finishCallback = new Callback() {
					@Override
					public Object callback(Object ret) {
						final boolean isError = (boolean)ret;
						closeProgressPopup();
						// 報告・報告（回答）の切り替えボタンタップ
						if (mCmd.equals(ABookKeys.CMD_CHANGE_TASK_REPORT)) {
							afterABookCheckApi(mCmd, mTaskKey, 0, "", null, isOperationPdf());
							return null;
						}

						if (ActivityHandlingHelper.getInstance().searchOzdActivityStack()) {  // OZD作業画面があるかを確認
							// PDF且つ、一時保存の場合は、以下の処理を行わないでreturn null;で処理を終わらせる
							if (mCmd.equals(ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT) && isOperationPdf) {
								return null;
							}
							if (!isError) {  // エラーがなしの場合
								if (mAddReport) {  // 作業追加ありの場合
									// コールバック処理のみ行う。
									afterABookCheckApi(mCmd, mTaskKey, 0, "", null, isOperationPdf());
								}
								// 画面遷移処理(一時保存以外)
								if (!mCmd.equals(ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT)) {
									closeCurrentScreen(mReportType);
								}
							}
						} else {
							// ozd画面ではない一時保存処理時、コールバックを呼び出す
							if (mCmd.equals(ABookKeys.CMD_LOCAL_SAVE_TASK_REPORT)) {
								afterABookCheckApi(mCmd, mTaskKey, 0, "", null, isOperationPdf());
								return null;
							}
							if (mCmd.equals(ABookKeys.CMD_INSERT_TASK_REPORT) || mCmd.equals(ABookKeys.CMD_UPDATE_TASK_REPORT)) {
								// データを同期する fixme かなり邪道なことをしているので、非同期処理全体を整理する必要がある
								ActivityHandlingHelper helper = ActivityHandlingHelper.getInstance();
								helper.getPreviousOperationListActivity().syncOperation(operationDto.operationId, operationDto.reportType, false);
								OperationLogic logic = AbstractLogic.getLogic(OperationLogic.class);
								try {
									logic.createJsonForOperationContent(operationDto.operationId, mContentPath, operationDto.reportType == Constant.ReportType.RoutineTask);
								} catch (IOException e) {
									Logger.e(TAG, e.getLocalizedMessage());
								}
								// コールバック
								ReportStatusLogic.TaskReportExtParam extParam = ReportStatusLogic.TaskReportExtParam.pick();
								JSONObject extJson = new JSONObject();
								if (extParam != null) {
									extJson.put(ReportStatus, extParam.reportStatus);
									extJson.put(Message, extParam.message);
								}
								afterABookCheckApi(mCmd, mTaskKey, 0, "", extJson.toString(), isOperationPdf());
							} else if (mAddReport) {  // 作業追加ありの場合
								// コールバック処理のみ行う。
								String extParam = null;
								if (mCmd.equals(ABookKeys.CMD_UNLOCK_REPORT)) {
									extParam = "{'reportStatus':0, 'message':''}";
								}
								afterABookCheckApi(mCmd, mTaskKey, 0, "", extParam, isOperationPdf());
							} else {
								// 作業追加無しの場合、エラー発生時フォーム画面表示を維持するためにコールバックresult:1でする
								if (isError) {
									afterABookCheckApi(mCmd, mTaskKey, 1, "", null, isOperationPdf());
									return null;
								}
							}
							// 画面遷移処理
							closeCurrentScreen(mReportType);
						}
						return null;
					}
				};

				ABookCheckWebViewHelper.getInstance().doABookCheckParam(ABVContentViewActivity.this,
						mCmd, mTaskKey, mEnableReportHistory, abookCheckParam, mOperationId, mContentPath, getContentId(),
						operationDto.reportType, finishCallback, taskReportLevel);

			} catch(Exception e) {
				Logger.e(TAG, "doABookCheckParam error", e);
			}
			if(isOperationPdf) {
				onActionOperationPdfWebView(abookCheckParam, operationTaskDto);
			}
		} else if (mCmd.equals(ABookKeys.CMD_CHANGE_DISPLAY_STATUS)) {
			mStatusCode = Integer.valueOf(abookCheckParam.get(ABookKeys.STATUS_CODE));
			commonConfigureHeader();
			if(isOperationPdf) {
				onActionOperationPdfWebView(abookCheckParam, operationTaskDto);
			}
		} else if (mCmd.equals(ABookKeys.CMD_SAVE_ATTACHED)) {
			mAttachedFileName = abookCheckParam.get(ABookKeys.FILE_NAME);
			getAttachedDataUrl(abookCheckParam.get(ABookKeys.TASK_KEY));
		} else if (mCmd.equals(ABookKeys.CMD_SHOW_REPORT_OZD)) {
			// 帳票コンポーネントを削除したので、ダイアログを表示するだけで何もしない
			showOzFileOpenErrorDialog();
		} else if (mCmd.equals(ABookKeys.CMD_PREVIEW_REPORT_OZD)) {
			// 帳票コンポーネントを削除したので、ダイアログを表示するだけで何もしない
			showOzFileOpenErrorDialog();
		} else if (mCmd.equals(ABookKeys.CMD_CONTENT_EDIT_CLOSE)) {
            showProgressPopup();
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    closeProgressPopup();
                    finish();
                }
            }, 5000);
        } else if (mCmd.equals(ABookKeys.CMD_GET_GPS_INFO)) {
        	// #32926 作業報告画面改善 start
            setLocation((Integer.valueOf(abookCheckParam.get(ABookKeys.GPS_TYPE)) != 1));
            // #32926 作業報告画面改善 end
        } else if (mCmd.equals(ABookKeys.CMD_SCENE_REGIST)) {
            String successFlg = abookCheckParam.get(ABookKeys.SUCCESS_FLG);
            if(Integer.parseInt(successFlg) == 0) {
				// リソースパターンの適用
                ABookAlertDialog alertDialog = AlertDialogUtil.createAlertDialog(this, PatternStringUtil.patternToInt(getApplicationContext(),
																									R.string.pano_edit,
																									getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
                alertDialog.setMessage(PatternStringUtil.patternToInt(getApplicationContext(),
											R.string.msg_sence_regist_failed,
											getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
                alertDialog.setPositiveButton(R.string.ok,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();

                            }
                        });
                alertDialog.show();
            } else {
				progressDialog.setProgress(100);
                // 成功
                Logger.i(TAG, ABookKeys.CMD_SCENE_REGIST + "is success");
				progressDialog.setProgress(0);
			}
            closeProgressPopup();
        } else if (mCmd.equals(ABookKeys.CMD_MOVE_PAGE)) {
            onActionOperationPdfWebView(abookCheckParam, operationTaskDto);
		} else if (mCmd.equals(ABookKeys.CMD_SHOW_RELATED_CONTENT)) {
			try {
				long linkedContentId = Long.valueOf(abookCheckParam.get(ABookKeys.CONTENT_ID));
				int pageNum = Integer.valueOf(abookCheckParam.get(ABookKeys.CMD_PAGE_NUM));

				//ダウンロード完了後、開く時に必要
				isLinkedContent = true;
				pageNo = pageNum -1 ;

				if (ActivityHandlingHelper.getInstance().checkContent(linkedContentId, pageNo)) { // コンテンツをチェックし、なければDL後開く
					ActivityHandlingHelper.getInstance().startContentActivityForLinkedConent(mOperationId, linkedContentId, pageNo);
				}
			} catch (Exception e) {
				Logger.e(TAG, "startContentActivity failed.", e);
				ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
			}
		} else if (mCmd.equals(ABookKeys.CMD_GET_DEVICE_INFO)) {
			// ビーコンデータを受信して目的のデバイスIDの信号から値を取得する
			// 1:中心温度計  2:置くだけセンサー　3:バーコード
			getDeviceInfo(abookCheckParam);
		} else if (mCmd.equals(ABookKeys.CMD_LOCK_REPORT)) {
			String taskKey = abookCheckParam.get(TaskKey);
			Date startDate = dateOrNull(abookCheckParam.get("reportStartDate"));
			TaskReportDao dao = AbstractDao.getDao(TaskReportDao.class);
			// ロック
			LockReportLogic.Result r = LockReportLogic.newInstance().lock(taskKey, taskReportId, startDate);
			// JSコールバック
			afterABookCheckApi(mCmd, mTaskKey, r.getResult(), r.getMessage(), r.getExtParam().json());
		} else if (mCmd.equals(ABookKeys.CMD_UNLOCK_REPORT)) {
			String taskKey = abookCheckParam.get(TaskKey);
			Date startDate = dateOrNull(abookCheckParam.get("reportStartDate"));
			// アンロック
			UnlockReportLogic.Result r = UnlockReportLogic.newInstance().unlock(taskKey, taskReportId, startDate);
			// JSコールバック
			JSONObject extParam = new JSONObject();
			extParam.put(ReportStatus, 0);
			extParam.put(TaskReportId, taskReportId);
			extParam.put(ReportStartDate, DateTimeUtil.toStringInTimeZone(startDate, DateTimeFormat.yyyyMMddHHmmss_hyphen, "UTC"));
			afterABookCheckApi(mCmd, mTaskKey, 0, "", extParam.toString());
		}
    }

	/**
	 * 帳票コンポーネントが削除されたので、OZが使えなくなったので、エラーダイアログを表示する。
	 */
	private void showOzFileOpenErrorDialog() {
		final ABookAlertDialog confirmDialog = AlertDialogUtil.createAlertDialog(ABVContentViewActivity.this, R.string.confirm);
		confirmDialog.setCancelable(false);
		confirmDialog.setMessage(R.string.msg_error_open_ozd_content);
		confirmDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {
				mStatusCode = Constant.XWalkWebViewDisplayStatus.TaskListView;
				commonConfigureHeader();
				confirmDialog.dismiss();
			}
		});
		confirmDialog.show();
	}

    public void commonAttachedDataUrl (String taskKey, String data) {
        boolean isError = false;
        if (data != null) {
            try {
				String imagePath = ABVEnvironment.getInstance().getTempFilePath(getContentId(), taskKey, mAttachedFileName);
                ABookCheckWebViewHelper.getInstance().decodeToImage(data, imagePath);
                //アプリ内のファイルのみ削除（Galleryファイルは削除しない）
                if (mLocalFile != null && mLocalFile.getPath().contains(getPackageName())) {
                    FileUtil.delete(mLocalFile);
                }
                mLocalFile = null;
            } catch (Exception e) {
                isError = true;
                Logger.e(TAG, e);
            }
        }
        afterABookCheckApi(mCmd, taskKey, isError ? 1 : 0, "", null);
    }

    protected Uri attachmentImageProcessing(Uri uri) throws Exception {
        if (uri == null) {
            return null;
        }
        String[] operationion = {MediaStore.MediaColumns.DATA};
        Cursor cursor = getContentResolver().query(uri, operationion, null, null, null);
        String photoFilePath = ABookCheckWebViewHelper.getInstance().contentSchemeUriToFilePath(cursor);
        try {
			int rotationAngle = ABookCheckWebViewHelper.getInstance().rotateBitmapOrientation(photoFilePath);
			if (rotationAngle == 0) {
				mLocalFile = new File(photoFilePath);
			} else {
				mLocalFile = ABookCheckWebViewHelper.getInstance().rotateBitmapToImageFile(rotationAngle, photoFilePath, ABVEnvironment.getInstance().getContentCacheDirectoryPath(getContentId()));
			}
			if (mLocalFile.exists()) {
				return Uri.fromFile(mLocalFile);
			}
		} catch (FileNotFoundException e) {
			Logger.e(TAG, "image file is not found", e);
		}
        return null;
    }

    public void afterABookCheckApi(final String cmd, final String taskKey, final int result, final String message, final String extParam) {
        afterABookCheckApi(cmd, taskKey, result, message, extParam, false);
    }

    public void afterABookCheckApi(final String cmd, final String taskKey, final int result, final String message, final String extParam, final boolean isParent) {
        Logger.v(TAG, "run javaScript for ABookCheck : cmd=%s, taskKey=%s, result=%s, message=%s", cmd, taskKey, result, message);
        final String finalParent = isParent ? "window.parent." : "";
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (extParam != null) {
                    Logger.i(TAG, String.format("javascript:%sCHK.afterABookCheckApi('%s', '%s', '%s', '%s', %s)", finalParent, cmd, taskKey, result, message, extParam));
                    webViewLoadUrl(String.format("javascript:%sCHK.afterABookCheckApi('%s', '%s', '%s', '%s', %s)", finalParent, cmd, taskKey, result, message, extParam));
                } else {
                    Logger.i(TAG, String.format("javascript:%sCHK.afterABookCheckApi('%s', '%s', '%s', '%s')", finalParent, cmd, taskKey, result, message));
                    webViewLoadUrl(String.format("javascript:%sCHK.afterABookCheckApi('%s', '%s', '%s', '%s')", finalParent, cmd, taskKey, result, message));
                }
			}
        });
    }

    protected  void commonConfigureHeader() {
    }

    /**
     * 添付ファイルのBase64文字列取得
     */
	public void getAttachedDataUrl(final String taskKey) {
		runOnUiThread(new Runnable() {
            @Override
            public void run() {
				webViewLoadUrl("javascript:android.getAttachedDataUrl('" + taskKey + "', CHK.getAttachedDataUrl())");
			}
        });
    }

    /**
     * 位置情報取得
     * @param showPermissionDialogFlg
     */
    // #32926 作業報告画面改善 start
    protected void setLocation(final boolean showPermissionDialogFlg) {
		mLocationSendResult = false;
    	// #32926 作業報告画面改善 end
        ABookPermissionHelper helper = new ABookPermissionHelper(this, Constant.ABookPermissionType.AccessFineLocation, null);
        if (helper.checkMultiPermissions(showPermissionDialogFlg)) {
            // 位置情報取得
            LocationManagerUtil locationManagerUtil = new LocationManagerUtil(this, new LocationManagerUtil.LocationManagerUtilListener() {
                @Override
                public void onGetLocationFailed() {
                    Logger.w(TAG, "onGetLocationFailed");
                    // #32926 作業報告画面改善 end
                        afterABookCheckApi(mCmd, "", 1, PatternStringUtil.patternToString(getApplicationContext(),
																			R.string.msg_location_search_fail,
																			getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)), null);
                }

                @Override
                public void onGetLocation(final Location location) {
                	if (!mLocationSendResult) {
						latitude = location.getLatitude();
						longitude = location.getLongitude();
						Logger.v(TAG, "location latitude(%s), longitude(%s)", latitude, longitude);
						CommonExecutor.execute(new Runnable() {
							@Override
							public void run() {
								JSONObject json = new JSONObject();
								json.put("latitude", latitude);
								json.put("longitude", longitude);
								afterABookCheckApi(mCmd, "", 0, "", json.toString());
							};
						});
						mLocationSendResult = true;
					}
                }
            });
            locationManagerUtil.startLocationService();
        } else {
            Logger.w(TAG,"onGetLocationFailed AccessFineLocation false");
			// リソースパターンの適用
			afterABookCheckApi(mCmd, "", 1, PatternStringUtil.patternToString(getApplicationContext(),
					R.string.msg_location_search_fail,
					getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)), null);
		}
    }

    protected boolean isOperationPdf() {
	    return isOperationPdf;
    }

	/**
	 * 報告可能フラグ
	 * @return
	 */
	public boolean isReportEdit() {
        return mEnableReportEdit == Constant.EnableReportEdit.YES;
    }

	/**
	 * PDF操作インスタンスを作成
	 * @param pdfFileName
	 * @return
	 * @throws Exception
	 */
	public FoxitPdfCore initPdf(String pdfFileName) throws Exception {
		Logger.d(TAG, "post intent to open file pdfFileName=" + pdfFileName);
		String filepath = mContentDir + "/" + pdfFileName;
		if (!FileUtil.exists(filepath)) {
			return null;
		}
		return new FoxitPdfCore(this, filepath);
	}

	// 保存処理
	public void ozdSaveProcess() {
		runOnUiThread(new Runnable() {
			@Override
			public void run () {
				// 実行Javascript - 保存
				ActivityHandlingHelper.getInstance().callOzdHtmlScript("javascript:CHK.saveOzReport()");
				Logger.d(TAG, "ozdSaveProcess");
			}
		});
	}

	// 一時保存処理
	public void ozdLocalSaveProcess() {
		runOnUiThread(new Runnable() {
			@Override
			public void run () {
				// 実行Javascript - 一時保存
				ActivityHandlingHelper.getInstance().callOzdHtmlScript("javascript:CHK.localSaveOzReport()");
				Logger.d(TAG, "ozdLocalSaveProcess");
			}
		});
	}

	// 閉じる処理
	public void ozdCancelProcess() {
		runOnUiThread(new Runnable() {
			@Override
			public void run () {
				// 実行Javascript - 閉じる
				ActivityHandlingHelper.getInstance().callOzdHtmlScript("javascript:CHK.cancelOzReport()");
				Logger.d(TAG, "ozdCancelProcess");
			}
		});
	}

	// 削除処理
	public void ozdDeleteProcess() {
		runOnUiThread(new Runnable() {
			@Override
			public void run () {
				// 実行Javascript - 閉じる
				ActivityHandlingHelper.getInstance().callOzdHtmlScript("javascript:CHK.deleteOzReport()");
				Logger.d(TAG, "ozdDeleteProcess");
			}
		});
	}

	// 作業一覧画面に遷移
	public void goToMain() {
		ActivityHandlingHelper.getInstance().finishAllContentViewActivity(); // 一覧画面に遷移
	}

	// 押したボタンによってHTML側の処理を行う
	public void doProcess() {
	}

	// 作業終了する時、作業ID設定し、画面遷移処理
	public void closeCurrentScreen(int reportType) {

		if (mAddReport) { // 作業追加あり
			if (ActivityHandlingHelper.getInstance().searchOzdActivityStack()) {  // OZD画面で画面遷移処理
				ActivityHandlingHelper.getInstance().selectedOzdActivityClose();  // 開いてる画面を閉じる
			}
		} else {  // 作業追加なし
			putUserPref(AppDefType.UserPrefKey.SYNC_TARGET_OPERATION_ID, mOperationId);  // 作業IDの設定
			if (ActivityHandlingHelper.getInstance().searchOzdActivityStack()) {  // OZD画面で画面遷移処理
				goToMain();  // 一覧画面に遷移
			} else {
				finishActivity();  // 一覧画面に遷移
			}
		}
	}

	//ABVCheckContentViewActivityから処理
	protected void getDeviceInfo(Map<String, String> abookCheckParam) {}

	private Date dateOrNull(String s) {
		try {
			return DateTimeUtil.toDate(s, "UTC", DateTimeFormat.yyyyMMddHHmmss_hyphen);
		} catch (Exception e) {
			return null;
		}
	}
}
