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

PICKUP.newReportList;
PICKUP.continousWorkReport;
PICKUP.reportWithWarning;
PICKUP.pickupActive = "newReport";

PICKUP.countNewReportList = 0;
PICKUP.countContinousWorkReport = 0;
PICKUP.countReportWithWarning= 0;

PICKUP.initCommon = function() {
	PICKUP.countNewReportList = 0;
	PICKUP.countContinousWorkReport = 0;
	PICKUP.countReportWithWarning = 0;
}

PICKUP.defaultPickupList = {
    operationList:[]
}

PICKUP.baseApiUrl = CONSTANT.URL.CMS.BASE + ClientData.userInfo_accountPath() + CONSTANT.URL.CMS.API.BASE + 'pickup/';
PICKUP.getNewReportListApiUrl = PICKUP.baseApiUrl + 'newReportList';
PICKUP.getContinuousWorkListApiUrl = PICKUP.baseApiUrl + 'continuousWorkList';
PICKUP.getReportWithWarningsListApiUrl = PICKUP.baseApiUrl + 'reportWithWarnings';

/**
 * Call get new report list api get data 
 */
 PICKUP.getNewreportListData = function (callback) {
    let param = {
        sid: COMMON.getSid(),
    };
    COMMON.cmsAjax(PICKUP.getNewReportListApiUrl, param, false, function (json) {
        if (callback) {
            callback(json);
        }
    }, function() {
        console.log('DASHBOARD.getNewreportListData error');
        if (callback) {
            callback(PICKUP.defaultPickupList);
        }
    });
};
/**
 * Call get Continuous Work list api get data 
 * @param {*} callback 
 */
PICKUP.getContinuousWorkListData = function (callback) {
    let param = {
        sid: COMMON.getSid(),
    };
    COMMON.cmsAjax(PICKUP.getContinuousWorkListApiUrl, param, false, function (json) {
        if (callback) {
            callback(json);
        }
    }, function() {
        console.log('DASHBOARD.getContinuousWorkListData error');
        if (callback) {
            callback(PICKUP.defaultPickupList);
        }
    });
};

/**
 * Call get Report With Warnings list api get data 
 * @param {*} callback 
 */
PICKUP.getReportWithWarningsListData = function (callback) {
    let param = {
        sid: COMMON.getSid(),
    };
    COMMON.cmsAjax(PICKUP.getReportWithWarningsListApiUrl, param, false, function (json) {
        if (callback) {
            callback(json);
        }
    }, function() {
        console.log('DASHBOARD.getReportWithWarningListData error');
        if (callback) {
            callback(PICKUP.defaultPickupList);
        }
    });
};
/**
 * Initialization pickup html 
 */
PICKUP.init = function() {
	console.log("PICKUP.init");
	TEMPLATE.loadHearder();
	TEMPLATE.loadConfirmModal();
	PICKUP.settingPickup();
}
/**
 * Setting pickup data
 */
PICKUP.settingPickup = function() {
	DashboardSetting.getSettingData(function (settings) {
        if(!settings.newReport)
		{
			$("#liTabNewReport").addClass('d-none');
		}
		else
		{
			$("#liTabNewReport").removeClass('d-none');
			PICKUP.initNewReportTab();
		}
		if(!settings.continousWork)
		{
			$("#liTabContinousWork").addClass('d-none');
		}
		else
		{
			$("#liTabContinousWork").removeClass('d-none');
		}
		if(!settings.reportWarning)
		{
			$("#liTabReportWithWarning").addClass('d-none');
		}
		else
		{
			$("#liTabReportWithWarning").removeClass('d-none');
		}
    });
}

PICKUP.initSettingActivePickup = function() {
	var urlParam = CHK.getUrlParameter();
	PICKUP.pickupActive = urlParam.pickupActive;
	PICKUP.settingActivePickup(PICKUP.pickupActive);
}

PICKUP.settingActivePickup = function(pickupActive) {
	PICKUP.pickupActive = pickupActive;
	$('#liTabNewReport').removeClass('on');
	$('#liTabContinousWork').removeClass('on');
	$('#liTabReportWithWarning').removeClass('on');

	$('#tab-content-NewReport').removeClass('on');
	$('#tab-content-ContinousWork').removeClass('on');
	$('#tab-content-ReportWithWarning').removeClass('on');

	if(pickupActive == "newReport")
	{
		$('#liTabNewReport').addClass('on');
		$('#tab-content-NewReport').addClass('on');
		return;
	}

	if(pickupActive == "continousWork")
	{
		$('#liTabContinousWork').addClass('on');
		$('#tab-content-ContinousWork').addClass('on');
		return;
	}
	if(pickupActive == "reportWarning")
	{
		$('#liTabReportWithWarning').addClass('on');
		$('#tab-content-ReportWithWarning').addClass('on');
		return;
	}
}
PICKUP.changeActivePickup = function(liPickupTab) {
	PICKUP.settingActivePickup($(liPickupTab).attr("data-active"));
}

PICKUP.goBack = function() {
    history.back();
}
/**
 * Initialization show not found pickup item html 
 * @param {*} elementId 
 */
PICKUP.showNotFoundPickupItem =  function(elementId) {
	$(elementId).removeClass();
	$(elementId).addClass('p-0 mt-3 card-list');
	let li = $("<li class='card mb-2 not-found'></li>");
	let div = $("<div class='text-dark mb-1 px-3 py-5 text-center m-auto'></div>");
	let imgdiv = $("<img src=\"../common/img/icon_not_found.svg\" alt='該当する作業がありません。' class='not-found-img mb-2'>");
	let childDiv = $("<div class='fs-9 text-secondary font-weight-bold'>該当する作業がありません。</div>");
	div.append(imgdiv);
	div.append(childDiv);
	li.append(div);
	$(elementId).append(li);
}

/**
 * Initialization view pickup menu html 
 * @param {*} elementId 
 * @param {*} count 
 */
PICKUP.showCountDisplayPickupItem =  function(elementId, count) {
	let span = $('<span>' + I18N.i18nText('display')  +'</span>');
	$(elementId).append(count);
	$(elementId).append(span);
}

/**
 * Initialization new report list html 
 */
PICKUP.initNewReportTab = function() {
	PICKUP.getNewreportListData(function (json) {
		PICKUP.createNewReportList(json.operationList);
	});
}
PICKUP.sortNewReportList = function(operationList) {
	operationList = operationList.sort(function(a,b) {
		if (a.operationId < b.operationId) return 1;
		if (a.operationId > b.operationId) return -1;
		return 0;
	});
	return operationList;
}

PICKUP.createNewReportList = function(operationListOld) {
	var operationList = PICKUP.sortNewReportList(operationListOld);
	$('#viewMenuNewReport').removeClass('d-none');
	$("#newReport-list").empty();
	PICKUP.countNewReportList = 0;
	
	if (typeof operationList === 'undefined' || operationList.length < 1) {
		PICKUP.showNotFoundPickupItem("#newReport-list");
		$('#viewMenuNewReport').addClass('d-none');
        return;
    }
    $('#newReport-list').addClass('task-list view-content view-block');

	for (var i = 0; i < operationList.length; i++) {
		//TODO aタグlist.html 転移処理operationList[i].reportType == 2 && operationList[i].enableReportEdit == 0 
		var messageli = $("<li class='card mb-2' name = 'operationId_" + operationList[i].operationId + "' ></li>");
		var ahrefRequiredFlg ;
		if (operationList[i].permitCodeRequiredFlg == 1)
		{
			ahrefRequiredFlg =  $("<a href=\"javascript:CHK.displayAlert('onlyRfid');\" class='d-block px-3 py-3 text-decoration-none text-dark'></a>");
		}
		else
		{
			ahrefRequiredFlg =  $("<a href=\"javascript:CHK_L.sendAppCommand('goOperation', '" + operationList[i].operationId + "', '" + operationList[i].contentId + " ', null ,'NEW_FORM_INPUT' ,'REPORT_LIST',null);\" class='d-block px-3 py-3 text-decoration-none text-dark'></a>");
		}
		var divText = $("<div class='fs-12 text-truncate'>" + operationList[i].operationName + "</div>");
		
		ahrefRequiredFlg.append(divText);
		messageli.append(ahrefRequiredFlg);

		$("#newReport-list").append(messageli);
		PICKUP.countNewReportList  = PICKUP.countNewReportList  + 1;

	}
	// show not found if 
	if (PICKUP.countNewReportList == 0) {
        PICKUP.showNotFoundPickupItem("#newReport-list");
		$('#viewMenuNewReport').addClass('d-none');
		return;
    }
	PICKUP.showCountDisplayPickupItem("#count-NewReport", PICKUP.countNewReportList )
	
}

PICKUP.sortContinousWorkList = function(operationList) {
    var newOperationList = [];
	for (var i = 0; i < operationList.length; i++) {
		if (operationList[i].reportType === 3)
		{
		    if(typeof operationList[i].processList === 'undefined' ) continue;
		    if (operationList[i].processList && operationList[i].processList.length != 0)
		    {
		        for( var j = 0; j < operationList[i].processList.length; j++ )
		        {
		            if(typeof operationList[i].processList[j].phaseList === 'undefined' ) continue;
		            for(var g = 0; g < operationList[i].processList[j].phaseList.length; g++ )
		            {
		                if(operationList[i].processList[j].phaseList[g].phaseStatus != 999)
                        {
                            var item = {reportType: operationList[i].reportType,
										operationType: operationList[i].operationType,
                                        phaseList: operationList[i].processList[j].phaseList,
                                        processKey: operationList[i].processList[j].processKey,
                                        permitCodeRequiredFlg: operationList[i].permitCodeRequiredFlg,
                                        operationId: operationList[i].operationId,
                                        contentId: operationList[i].contentId,
                                        operationName: operationList[i].operationName,
                                        taskCode: operationList[i].processList[j].taskCode,
                                        taskKey: operationList[i].processList[j].taskKey,
                                        taskName: operationList[i].processList[j].taskName,
                                        updateDate: operationList[i].processList[j].phaseList[g].updateDate,
										phaseNo: operationList[i].processList[j].phaseList[g].phaseNo,
										phaseName: operationList[i].processList[j].phaseList[g].phaseName
                                        };
                            newOperationList.push(item);
                        }

		            }

		        }
		    }
		}
	}
	newOperationList = newOperationList.sort(function(a,b) {
		if (!a.updateDate) {
			a.updateDate = "1900-01-01 09:00:00";
		}
		if (!b.updateDate) {
			b.updateDate = "1900-01-01 09:00:00";
		}
		if (a.updateDate < b.updateDate) return 1;
		if (a.updateDate > b.updateDate) return -1;
		return 0;
	});
	console.log("newOperationList: " + JSON.stringify(newOperationList));
	return newOperationList;
}


PICKUP.sortWarningList = function(operationList) {
    var newOperationList = [];
	for (var i = 0; i < operationList.length; i++) {
		if(typeof operationList[i].warningReportList === 'undefined' ) continue;
		    if (operationList[i].warningReportList && operationList[i].warningReportList.length != 0)
		    {
		        for( var j = 0; j < operationList[i].warningReportList.length; j++ )
		        {
		            var item = {reportType: operationList[i].reportType,
						operationType: operationList[i].operationType,
						permitCodeRequiredFlg: operationList[i].permitCodeRequiredFlg,
						operationId: operationList[i].operationId,
						contentId: operationList[i].contentId,
						operationName: operationList[i].operationName,
						taskCode: operationList[i].warningReportList[j].taskCode,
						taskKey: operationList[i].warningReportList[j].taskKey,
						taskName: operationList[i].warningReportList[j].taskName,
						taskType: operationList[i].warningReportList[j].taskType,
						updateDate: operationList[i].warningReportList[j].updateDate,
						reportStartDateString: operationList[i].warningReportList[j].reportStartDateString,
						reportEndDateString: operationList[i].warningReportList[j].reportEndDateString,
						processKey: operationList[i].warningReportList[j].processKey,
						phaseNo: operationList[i].warningReportList[j].phaseNo,
						phaseName: operationList[i].warningReportList[j].phaseName
						};
					newOperationList.push(item);
		        }
		    }
	}
	newOperationList = newOperationList.sort(function(a,b) {
		if (!a.updateDate) {
			a.updateDate = "1900-01-01 09:00:00";
		}
		if (!b.updateDate) {
			b.updateDate = "1900-01-01 09:00:00";
		}
		if (a.updateDate < b.updateDate) return 1;
		if (a.updateDate > b.updateDate) return -1;
		return 0;
	});
	console.log("newOperationList: " + JSON.stringify(newOperationList));
	return newOperationList;
}

PICKUP.createContinousWorkList = function(operationListOld, isSearched = false) {
    var operationList = PICKUP.sortContinousWorkList(operationListOld);
	$("#continousWork-list").empty();
	PICKUP.countContinousWorkReport = 0;
	if (typeof operationList === 'undefined' || operationList.length < 1) {
        $('#notFoundContinousWork').removeClass('d-none');
        return;
    }
    $('#notFoundContinousWork').addClass('d-none');

    for (var i = 0; i < operationList.length; i++) {
		var directKey = operationList[i].processKey;
		if (operationList[i].operationType == CHK.OPERATION_TYPE.VTOUR || operationList[i].operationType == CHK.OPERATION_TYPE.PDF) {
			directKey = operationList[i].taskKey;
		}
		var messageli  = $("<li class='item list-unstyled rounded border mb-2' id = 'list_" + operationList[i].processKey + "'></li>") ;
        var ahrefRequiredFlg ;
        if (operationList[i].permitCodeRequiredFlg == 1)
        {
            ahrefRequiredFlg =  $("<a href=\"javascript:CHK.displayAlert('onlyRfid');\" class='d-block px-3 py-3 text-decoration-none text-dark'></a>");
        }
        else
        {
            ahrefRequiredFlg =  $("<a href=\"javascript:CHK_L.sendAppCommand('goOperation', '" + operationList[i].operationId + "', '" + operationList[i].contentId
            + " ', null ,'DETAIL_FORM_INPUT' ,'CONTINOUS_WORK','" + directKey + "','" + operationList[i].phaseNo  + "');\" class='d-block px-3 py-2 text-decoration-none text-dark'></a>");
        }
        var divTitle = $("<div class='title'>" + operationList[i].operationName + "</div>");
        var divSubTitleWrap = $("<div class='sub-title-wrap'> </div>");
        var iIcon = $("<i class='fas fa-chevron-right fs-12''></i>");
        var divProccess = $("<div class='tag fs-8 text-secondary px-2 py-1 mr-2 rounded border mb-1'>" + operationList[i].phaseName + "</div>");
        var divCode = $(" <div class='fs-8 text-secondary mr-2'><div class='data'>" + operationList[i].taskCode + "</div></div>");
        var divSubTitle = $("<div class='sub-title'>" + operationList[i].taskName + "</div>");
        divSubTitleWrap.append(divCode);
        divSubTitleWrap.append(divSubTitle);
        ahrefRequiredFlg.append(divProccess);
        ahrefRequiredFlg.append(divTitle);
        ahrefRequiredFlg.append(divSubTitleWrap);
        ahrefRequiredFlg.append(iIcon);
        messageli.append(ahrefRequiredFlg);
        $("#continousWork-list").append(messageli);
        PICKUP.countContinousWorkReport = PICKUP.countContinousWorkReport + 1;
	}
	
	// show not found if 
	if (PICKUP.countContinousWorkReport < 1) {
        $('#notFoundContinousWork').removeClass('d-none');
    }

	if(CHK.isAndroid) {
        android.hideLoading();
    }
};


PICKUP.createReportWithWarning = function(operationListOld, isSearched = false) {
	var operationList = PICKUP.sortWarningList(operationListOld);
	$("#reportWithWarning-list").empty();
	PICKUP.countReportWithWarning = 0;

	if (typeof operationList === 'undefined' || operationList.length < 1) {
        $('#notFoundReportWithWarning').removeClass('d-none');
        return;
    }
    $('#notFoundReportWithWarning').addClass('d-none');
	var msgLevelReport =  getMsg("reportLevelReport") ;
	console.log("msgLevelReport :" + msgLevelReport);
	var msgLevelAnswer =  getMsg("reportLevelAnswer") ;
	console.log("msgLevelAnswer :" + msgLevelAnswer);
    for (var i = 0; i < operationList.length; i++) {
		//TODO aタグlist.html 転移処理
		var operationNameLi;
		switch (operationList[i].reportType)
			{
				case 0:
					operationNameLi = $("<li class='item list-unstyled rounded border mb-2' id = 'list_" + operationList[i].taskKey
						+ "'><a href=\"javascript:CHK_L.sendAppCommand('goOperation', '" + operationList[i].operationId + "', '" + operationList[i].contentId
						+ " ', null ,'DETAIL_FORM_INPUT' ,'REPORT_WARNING','" + operationList[i].taskKey + "');\" class='d-block px-3 py-2 text-decoration-none text-dark'>"
						+"<div class='title'>" + operationList[i].operationName
						+ "</div> <div class='sub-title-wrap'> <div class='fs-8 text-secondary mr-2'><div class='data'>" + operationList[i].taskCode
						+ "</div></div> <div class='sub-title'>" + operationList[i].taskName
						+ "</div></div> <i class='fas fa-chevron-right fs-12'></i> </a></li>");
					break;
				case 1:
					operationNameLi = $("<li class='item list-unstyled rounded border mb-2' id = 'list_" + operationList[i].taskKey
						+ "'><a href=\"javascript:CHK_L.sendAppCommand('goOperation', '" + operationList[i].operationId + "', '" + operationList[i].contentId
						+ " ', null ,'DETAIL_FORM_INPUT' ,'REPORT_WARNING','" + operationList[i].taskKey + "');\" class='d-block px-3 py-2 text-decoration-none text-dark'>"
						+"<div class='title'>" + operationList[i].operationName
						+ "</div>  <div class='sub-title-wrap'> <div class='fs-8 text-secondary mr-2'><div class='sub-title'>" + PICKUP.getInspectDate(operationList[i].reportStartDateString) + " ～ " +  PICKUP.getInspectDate(operationList[i].reportEndDateString)
						+ "</div></div> </div> <i class='fas fa-chevron-right fs-12'></i> </a></li>");
					break;
				case 2:
					operationNameLi = $("<li class='item list-unstyled rounded border mb-2' id = 'list_" + operationList[i].taskKey + "'></li>");
					var ahrefRequiredFlg = $("<a href=\"javascript:CHK_L.sendAppCommand('goOperation', '" + operationList[i].operationId + "', '" + operationList[i].contentId
					+ " ', null ,'DETAIL_FORM_INPUT' ,'REPORT_WARNING','" + operationList[i].taskKey + "','" + operationList[i].taskType  + "');\" class='d-block px-3 py-2 text-decoration-none text-dark'></a>");
					var liTagTitle = $("<div class='title'>" + operationList[i].operationName + "</div>") ;
					var liTagReportType;
					if( operationList[i].taskType == 0 )
					{
						liTagReportType =  $("<div class='tag fs-8 text-secondary px-2 py-1 mr-2 rounded border mb-1'>" + msgLevelReport + "</div>") ;
					}
					else
					{
						liTagReportType =  $("<div class='tag fs-8 text-secondary px-2 py-1 mr-2 rounded border mb-1'>" + msgLevelAnswer + "</div>") ;
					}
					
					var divCode = $("<div class='sub-title-wrap'> <div class='fs-8 text-secondary mr-2'><div class='data'>" + operationList[i].taskCode
					+ "</div></div> <div class='sub-title'>" + operationList[i].taskName + "</div></div>");
					var iIcon = $("<i class='fas fa-chevron-right fs-12'></i>");
					ahrefRequiredFlg.append(liTagReportType);
					ahrefRequiredFlg.append(liTagTitle);
					ahrefRequiredFlg.append(divCode);
					ahrefRequiredFlg.append(iIcon);
					operationNameLi.append(ahrefRequiredFlg);
					break;
				case 3:
					var directKey = operationList[i].processKey;
					if (operationList[i].operationType == CHK.OPERATION_TYPE.VTOUR || operationList[i].operationType == CHK.OPERATION_TYPE.PDF) {
						directKey = operationList[i].taskKey;
						if (operationList[i].phaseNo > 1) {
							//find taskKey of phaseNo 1
							for (var k = 0; k < operationList.length; k++) {
								if (operationList[k].phaseNo == 1 && operationList[k].processKey == operationList[i].processKey) {
									directKey = operationList[k].taskKey;
									break;
								}
							}
						}
					}
					operationNameLi = $("<li class='item list-unstyled rounded border mb-2' id = 'list_" + operationList[i].taskKey
	                        + "'><a href=\"javascript:CHK_L.sendAppCommand('goOperation', '" + operationList[i].operationId + "', '" + operationList[i].contentId
							+ " ', null ,'DETAIL_FORM_INPUT' ,'REPORT_WARNING','" + directKey + "','" + operationList[i].phaseNo  + "');\" class='d-block px-3 py-2 text-decoration-none text-dark'>"
	                        +"<div class='tag fs-8 text-secondary px-2 py-1 mr-2 rounded border mb-1'>" +  operationList[i].phaseName
	            		    + "</div> <div class='title'>" + operationList[i].operationName
	            		    + "</div> <div class='sub-title-wrap'> <div class='fs-8 text-secondary mr-2'><div class='data'>" + operationList[i].taskCode
	            		    + "</div></div> <div class='sub-title'>" + operationList[i].taskName
	            		    + "</div></div> <i class='fas fa-chevron-right fs-12'></i> </a></li>");
					break;

			}
			$("#reportWithWarning-list").append(operationNameLi);
			PICKUP.countReportWithWarning = PICKUP.countReportWithWarning + 1;
	}
	// show not found if 
	if (PICKUP.countReportWithWarning < 1) {
        $('#notFoundReportWithWarning').removeClass('d-none');
    }
	if(CHK.isAndroid) {
        android.hideLoading();
    }
};


PICKUP.getInspectDate = function(dateString) {
	var date = new Date(dateString)
	return date.getFullYear() + "/" + ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + " "
    	     + ("0" + date.getHours()).slice(-2) + ":" + ("0" + date.getMinutes()).slice(-2);
}