// 名前空間
var CHK_L = {};

/**
 * 初期処理
 *
 */
CHK_L.init = function() {
	console.log("CHK_L.init design");
	CHK.useKrpano = false;
	CHK.operationType = CHK.OPERATION_TYPE.LIST;

	//ファンクション登録
	CHK.getSaveHotspotParam = CHK_L.getSaveHotspotParam;
	CHK.afterUpdateReport = CHK_L.afterUpdateReport;
	CHK.afterCancelTask = CHK_L.afterCancelTask;
	CHK.afterDeleteReport = CHK_L.afterDeleteReport;
	// 共通初期表示処理
	CHK.initCommon();
	// リストの場合、フォーム表示を全画面表示とする
	$("#checkInput").css("width", "calc(100% - 0px)");

	if (CHK.isMobile == 1) {
		CHK_L.setMobileDisplay();
	}

	var urlParam = CHK.getUrlParameter();
	if (CHK.reportType == CHK.REPORT_TYPE.INSPECT) {
		//	簡易帳票・改行改列の定期点検
		if (isQRTableInspect != 0) {
			$("#editHeader").hide();
			//	基本領域選択肢の作成
			$(".addition_list").empty();

			for (var i = 0; i < qrParentSelectData.length; i += 3) {
				var selectId = qrParentSelectData;
				var listLi = $("<li></li>", {
					id: "list_" + qrParentSelectData[i],
					class: "check"
				});

				var taskInfo = $("<div/>", {class: "taskInfoDiv"});
				var codeAndExpiration = $("<ul/>", {class: "codeAndExpiration"});

				codeAndExpiration.append($("<li/>", {class: "code"}).text(qrParentSelectData[i + 1]));
				taskInfo.append(codeAndExpiration);

				taskInfo.append($("<p/>").text(qrParentSelectData[i + 2]));

				listLi.append(taskInfo);
				listLi.append($("<p/>", {"style": "float: right; margin: auto; opacity: 0.2; font-size: 5em; width: 75px; text-align: right;"}).text(">"));

				listLi.css("cursor", "pointer");
				listLi.on("click", function() {
					qrSelectCID = $(this).attr('id').substr(5);

					$("#editHeader").show();
					$(".addition").hide();
					$("#checkListSearch").empty();
					$(".updateInspect").show();
					$("#contentType").text(getMsg("inspectList"));
					$(".totalDivPoint").text(getMsg("inspect_totalDivPoint"))

					//作業報告ロード
					if (CHK.isWeb) {
						$("#headerNav").show();
						CHK_I.initInspectWeb(function() {
							CHK_L.initInspect();
						});
						$(".updateInspect").attr("onclick", "CHK_L.updateInspectForWeb()");
					} else {
						CHK_I.initInspect(function() {
							CHK_L.initInspect();
						});
					}
				});

				$(".addition_list").append(listLi);
			}
		}
		//	定期点検プロジェクト
		else {
			$("#editHeader").show();
			$(".addition").hide();
			$("#checkListSearch").empty();
			$(".updateInspect").show();
			$("#contentType").text(getMsg("inspectList"));
			$(".totalDivPoint").text(getMsg("inspect_totalDivPoint"))

//			$("#editHeader").hide();

			//作業報告ロード
			if (CHK.isWeb) {
				$("#headerNav").show();
				CHK_I.initInspectWeb(function() {
					CHK_L.initInspect();
				});
				$(".updateInspect").attr("onclick", "CHK_L.updateInspectForWeb()");
			} else {
				CHK_I.initInspect(function() {
					CHK_L.initInspect();
				});
			}
		}
	} else {
		//通常プロジェクト
		$("#editHeader").show();
		if (CHK.isWeb) {
			$("#headerNav").show();
		}
		//作業報告ロード
		CHK.initReport(function() {
			CHK_L.initReport();
			if (addReportFlg == CHK.ADD_REPORT_FLG.UNABLE) {
				var taskKey = CHK.taskReport["taskReport_0"].length > 0 ? CHK.taskReport["taskReport_0"][0].taskKey : CHK.generateUuid();
				CHK.showReportForm(null, taskKey);
			}
			// タスク追加権限がない場合、作業追加ボタンを隠す
			if (CHK.hasAddTaskAuthority()) {
				$(".addition").show();
			}
        });

        CHK_L.sendAppCommand("finishInit");
        if (CHK.isWindows) {
            CHK.createOperationListBySavedSortType();
        }
	}

	if (CHK.isWeb) {
		// OZDビューワのリサイズ処理
		$(window).bind("resize", function() {
			if ($("#report_dialog").is(":visible")) {
				$(".noTitleDialog:visible").width("80%").height(window.innerHeight*0.9).position({my: 'center', at: "center", of: window});
				$("#report_dialog").height($(".noTitleDialog:visible").height() - 100)
			}
		});
	}
}

/**
 * モバイルでの表示対応
 *
 */
CHK_L.setMobileDisplay = function() {
	$("#editHeader").css("padding", "10px");
	$("#editHeader").height("auto");
	var headerDiv = $("<div/>", {class: "headerFormForMobile"});
	var childDiv = $("<div/>", {class: "childDiv"});
	if ($("#editHeader").width() < 300) {
		var secondChildDiv = $("<div/>", {class: "childDiv"});
		childDiv.prepend($("#editHeader #listIcon"), $("#editHeader #contentType").width("100%"));
		secondChildDiv.prepend($("#editHeader .totalDiv").width("100%"), $("#editHeader button.addition").width("45%"));
		headerDiv.prependTo($("#editHeader"));
		headerDiv.prepend(childDiv, secondChildDiv);
	} else {
		childDiv.prepend($("#editHeader").children());
		headerDiv.prependTo($("#editHeader"));
		headerDiv.prepend(childDiv);
		$("#contentType").width("auto");
	}
	$(".childDiv >button.addition").text(getMsg("Add"));
	$(".updateInspect").text(getMsg("Update"));
	$("#checkListSearch").appendTo(headerDiv);
	$("#checkListSearch").css("margin-top", "10px");
	$("#listValues").height("calc(100vh - 182px)");
	$(".childDiv").css("justify-content", "left");
}

/**
 * 作業指示初期処理
 *
 */
//CHK_L.initInstruct = function() {
//	$("#instruct").show();
//	CHK_L.updateList();
//}

/**
 * 作業報告初期処理
 *
 */
CHK_L.initReport = function() {
	$("#report").show();
	CHK_L.updateList();
}

/**
 * 作業報告初期処理(定期点検)
 *
 */
CHK_L.initInspect = function() {
	CHK_L.updateInspect();
}

/**
 * リストを更新
 *
 */
CHK_L.updateList = function() {
	$(".addition_list").empty();
	//シーケンスID順でソート
	CHK.taskHotspot.hotspot.sort(function(a, b) {
		if (Number(a.seqId) < Number(b.seqId)) return -1;
		if (Number(a.seqId) > Number(b.seqId)) return 1;
		return 0;
	});

	// 検索文の英文字と数字を半角、小文字に設定
	var searchWord = CHK.kataToHira(CHK.fullwidthTohalfwidth($("#searchWord").val())).toLowerCase();
	// 作業件数の初期化
	var count = 0;
	// 登録されてある作業がない場合、文言を表示して処理を停止
	if (CHK.taskHotspot.hotspot.length == 0) {
		$("#noWork").show();
		$(".totalDiv em").text(count);
		return;
	}
	else {
		$("#noWork").hide();
	}
	// 作業の表示処理で、検索文がある場合作業名に検索文が含まれてある場合は作業件数に1を追加して表示、ない場合非表示にする
	CHK.taskHotspot.hotspot.forEach(function(hotspot) {
		count += CHK_L.addTask(hotspot.taskKey, searchWord);
	});
	$(".totalDiv em").text(count);
	// 検索で表示作業がない場合、文言を表示する
	if (count == 0) {
		$("#nullValue").show();
	}
	else {
		$("#nullValue").hide();
	}
	// style設定
	if (!CHK.isWeb) {
		$(".codeAndExpiration .code").css("margin-bottom", "10px");
		$(".codeAndExpiration .period").css("font-size", "13px");
		$(".taskInfoDiv p").css("max-width", $(".read").width() + "px");
	}
}

/**
 * アプリにコマンド送信
 * @param {any} command
 */
CHK_L.sendAppCommand = function (command, operationId, contentId, operationGroupMasterId, directPage, backPage, directTaskKey ) {
    var param = {};
    param.cmd = CHK.getCommand(command);
    param.operationId = operationId;
    param.contentId = contentId;
    param.operationGroupMasterId = operationGroupMasterId;
	param.directPage = directPage;
	param.backPage = backPage;
	param.directTaskKey = directTaskKey;
	console.log("CHK_L.sendAppCommand " + JSON.stringify(param));
    CHK.sendABookCheckApi(param);
}
/**
 * 定期点検リストを更新
 *
 */
CHK_L.updateInspect = function() {
	$(".addition_list").empty();
	$(".totalDiv em").text(CHK.taskReport.taskReport_0.length);

	//作業開始日時順でソート
	CHK.taskReport["taskReport_0"].sort(function(a, b) {
	    if (CHK.isWeb && isIE()) {
	    	a.reportStartDate = a.reportStartDate.replace(/-/g, '/');
			b.reportStartDate = b.reportStartDate.replace(/-/g, '/');
		}

		var aDate = new Date(a.reportStartDate);
		var bDate = new Date(b.reportStartDate);
		if (Number(aDate.getTime()) < Number(bDate.getTime())) return -1;
		if (Number(aDate.getTime()) > Number(bDate.getTime())) return 1;
		return 0;
	});

	//リスト作成
	var count = 0;

	CHK.taskReport["taskReport_0"].forEach(function(taskReport, idx, ar) {
		var taskKey = null;
		//	簡易帳票・改行改列時
		if (qrSelectCID > 0) {
			//	選択したデータか確認
			taskKey = qrTaskKeyList[qrSelectCID];
			//	削除が行われた直後は、taskReport 内の taskKey が消されているので、taskReportInfoId でチェックする
			if (taskReport.taskReportInfo.length <= 0) {
				if (qrTaskReportInfoIdChoiceIdList[taskReport.taskReportInfoId] != qrSelectCID) {
					return
				}
			}
			//	通常は taskKey でチェック
			else {
				if (taskReport.taskReportInfo[0].taskKey != taskKey) {
					return;
				}
			}
			//	デフォルトの基本領域選択値の設定
			CHK.taskReport.taskReportId = qrTaskReportIdList[qrSelectCID];
		}

		var now = new Date();
	    if (CHK.isWeb && isIE()) {
	    	taskReport.reportStartDate = taskReport.reportStartDate.replace(/-/g, '/');
			taskReport.reportEndDate = taskReport.reportEndDate.replace(/-/g, '/');
		}
		var reportStartDate = new Date(taskReport.reportStartDate);
		var reportEndDate = new Date(taskReport.reportEndDate);
		var startDateStr = taskReport.reportStartDate.replace(/\//g, "").replace(/:/g, "").replace(/ /, "");
		var isReported;
		if (qrSelectCID > 0) {
			isReported = (taskReport.taskReportInfo && (taskReport.taskReportInfo.length > 0) && (Object.keys(taskReport.taskReportInfo[0].task).length > 0));
		}
		else {
			isReported = taskReport.taskReportInfoId || taskReport.task || (taskReport.taskReportInfo && taskReport.taskReportInfo.length > 0);
		}

		var listLi = $("<li></li>", {
			id: "list_" + startDateStr,
			class: isReported ? "check" : "read"
		});
		var taskInfo = $("<div/>", {class: "taskInfoDiv"});
		var codeAndExpiration = $("<ul/>", {class: "codeAndExpiration"});
		codeAndExpiration.append($("<li/>", {class: "code"}).text(getMsg(isReported ? "inspect_check" : "inspect_read")));
		// モバイルの場合、文字列を縦に分けて表示
		if (CHK.isMobile) {
			taskInfo.css("width", "100% - 100px)");
			var period = $("<div/>").text(getMsg("Period") + ":");
			var startDate = $("<div/>").text(CHK_I.getInspectDate(reportStartDate));
			var tilde = $("<div/>").text("~");
			var endDate = $("<div/>").text(CHK_I.getInspectDate(reportEndDate));
			codeAndExpiration.append($("<li/>", {class: "period"}).append(period, startDate, tilde, endDate));
		} else {
			codeAndExpiration.append($("<li/>", {class: "period"}).text(getMsg("Period") + ":" + CHK_I.getInspectDate(reportStartDate) + " ~ " + CHK_I.getInspectDate(reportEndDate)));
		}
		taskInfo.append(codeAndExpiration);
		taskInfo.append($("<p/>"));
		taskInfo.append($("<p/>", {class: "workContent"}));
		listLi.append(taskInfo);
		if (taskKey == null) {
			taskKey = CHK.taskHotspot.hotspot[0].taskKey;
		}

		if (now < reportStartDate) {
			//点検不可のため非表示
			listLi.css("cursor", "default");
			listLi.append($("<p/>", {"style": "float: right; margin: auto; color: #e82e00; font-size: 3em; width: 200px; text-align: right;"}).text(getMsg("unreportable")));
		} else if (CHK_I.enableReport(taskReport.reportStartDate, taskReport.reportEndDate, isReported, taskReport.localSaveFlg)) {
			//作業報告
			listLi.css("cursor", "pointer");
			listLi.on("click", function() {
				//	簡易帳票・改行改列時
				if (qrSelectCID > 0) {
					//	バックアップの作成
					CHK_L.qrSelTaskKey = taskKey;
					CHK_L.qrSelTaskReportInfo = taskReport.taskReportInfo;
				}

				if (CHK.isWeb) {
					CHK_I.initInspectWeb(function() {
						CHK_L.updateInspect();
						CHK_I.showTaskReportForm(taskReport, taskKey, isReported);
					});
				} else {
					CHK_I.showTaskReportForm(taskReport, taskKey, isReported);
				}
			});
			listLi.append($("<p/>", {"style": "float: right; margin: auto; color: #00a200; font-size: 3em; width: 200px; text-align: right;"}).text(getMsg("reportable")));
		} else {
			//報告内容
			listLi.css("cursor", "pointer");
			listLi.on("click", function() {
				CHK_I.showTaskReportForm(taskReport, taskKey, isReported);
			});
			listLi.append($("<p/>", {"style": "float: right; margin: auto; color: #00a6e8; font-size: 3em; width: 200px; text-align: right;"}).text(getMsg("reportReference")));
		}
		listLi.append($("<p/>", {"style": "float: right; margin: auto; opacity: 0.2; font-size: 5em; width: 75px; text-align: right;"}).text(">"));

		$(".addition_list").append(listLi);
		count++;
	});

	$(".totalDiv em").text(count);
}

/**
 * タスクをリストに追加する
 *
 * @param taskKey タスクキー
 * @param searchWord 検索文
 */
CHK_L.addTask = function(taskKey, searchWord) {
	var taskReport = CHK.getRecentVersionReport(taskKey);
	var pointNo = CHK.getPointNo(taskReport);
	var taskName = CHK.getTaskName(taskReport);

	// 検索文があり、対象作業名に検索文が含まれてない場合0を返して作業の追加・表示処理を停止
	if (searchWord && !CHK.hasSearchWord(taskName, searchWord)) return 0;

	var listLi = $("<li></li>", {
		id: "list_" + taskKey,
		class: CHK_L.getListClass(taskKey)
	});

	var taskInfo = $("<div/>", {class: "taskInfoDiv"});
	var codeAndExpiration = $("<ul/>", {class: "codeAndExpiration"});

	codeAndExpiration.append($("<li/>", {class: "code"}).text(pointNo));
	taskInfo.append(codeAndExpiration);

	taskInfo.append($("<p/>").text(taskName));

	listLi.append(taskInfo);
	listLi.append($("<p/>", {"style": "float: right; margin: auto; opacity: 0.2; font-size: 5em; width: 75px; text-align: right;"}).text(">"));

	listLi.css("cursor", "pointer");
	listLi.on("click", function() {
		CHK.showReportForm(null, taskKey);
	});

	$(".addition_list").append(listLi);
	return 1;
}


/**
 * 作業登録フォームを表示
 *
 * @param taskKey taskKey
 */
CHK_L.addTaskReport = function(taskKey) {
	if (!taskKey) taskKey = CHK.generateUuid();
	CHK.showReportForm(null, taskKey);
}

/**
 * 保存処理時のホットスポット情報を取得
 *
 * @param param 入力パラメータ
 */
CHK_L.getSaveHotspotParam = function(param) {
	var newHotspot = "";
	// 登録・修正
	if (param.mode == "0") {
		newHotspot = {
			sceneId: "",
			seqId: param.seqId,
			taskKey: param.taskKey,
			name: "",
			ath: "",
			atv: "",
			x: "",
			y: ""
		};
		if (CHK.debug == "1") CHK.taskHotspot.hotspot.push(newHotspot); //DEBUG
	} else {
		newHotspot = CHK.getTaskHotspot(param.name, param.taskKey);
	}
	return newHotspot;
}


/**
 * 作業報告更新後の処理
 *
 * @param taskKey taskKey
 */
CHK_L.afterUpdateReport = function(taskKey, isLocalSave) {
	// 定期点検
	if (CHK.reportType == CHK.REPORT_TYPE.INSPECT) {
		CHK_L.updateInspect();
	} else {
		CHK_L.updateList();
		if (taskKey) {
			$("#list_" + taskKey).attr("class", CHK_L.getListClass(taskKey));
		}
	}
	if (!isLocalSave) CHK.hideReportForm();
}


/**
 * 作業指示・報告キャンセル後の処理
 *
 * @param taskKey taskKey
 */
CHK_L.afterCancelTask = function(taskKey) {
	if (CHK.changeReportFlg && taskKey) {
		CHK.showReportForm(null, taskKey, null, CHK.taskReplyNo);
	} else {
		CHK.hideReportForm();
	}
}

/**
 * 作業報告削除後の処理
 *
 * @param taskKey taskKey
 */
CHK_L.afterDeleteReport = function(taskKey, json) {
	if (CHK.reportType == CHK.REPORT_TYPE.INSPECT) {
		if (CHK.isWeb) {
			CHK_L.updateInspectForWeb();
		} else {
			CHK_I.initInspect(function() {
				CHK_L.updateInspect();
			});
		}
	} else {
		// 指示報告の削除対応
		if (CHK.taskReplyNo == CHK.BASE_TASK_REPLY_NO) {
			var callback = function() {
				CHK_L.afterUpdateReport();
			};
			if (CHK.debug != "1" && CHK.isWeb) {
				CHK.updateReportJsonWeb(json, callback);
			} else {
				CHK.loadJson(CHK.jsonPath.taskHotspot, function(jsonData) {
					CHK.taskHotspot = jsonData;
					callback();
				});
			}
		} else {
			$("#list_" + taskKey).attr("class", CHK_L.getListClass(taskKey));
		}
	}
	CHK.hideReportForm();
}

/**
 * リストのスタイルを取得
 *
 * @param taskKey taskKey
 */
CHK_L.getListClass = function(taskKey) {
	var ret;
	var progress = CHK.getTaskProgress(null, taskKey);
	// 作業状況別の表示
	if (progress == "999") {
		ret = "check";
	} else {
		ret = "read";
	}
	return ret;
}

/**
 * ウェブ版の場合、アップデートでサーバから最新の情報を取得
 *
 */
CHK_L.updateInspectForWeb = function() {
	CHK_I.initInspectWeb(function() {
		CHK_L.updateInspect();
	})
}