/**
 * It is one of the js in index.html. 
 * index.html is made of operations List , dashboard and topPage.
 * 
 * @since cms:1.4.3.2&1.4.3.3 web:1.0
 */

var CHK_OL = {};

CHK_OL.operationList;  //Operation json data
CHK_OL.operationGroupMaster;  //category(operationGroupMaster) json data
CHK_OL.isOperationGroupMaster = 0;//0: category(operationGroupMaster) not exist 1: category(operationGroupMaster) exist
CHK_OL.operationSearchCriteria;

CHK_OL.sortIndex;
CHK_OL.operationGroupMasterId;

/**
 * process on page load.
 * 1.get all data.
 * 2.show operationList.
 * 3.show category(operationGroupMaster).
 */
 CHK_OL.init = function() {
	console.log("OperationList start");
	
	//get all data of operation list scene
	CHK_OL.getAllDataWeb();
	
	//show operation list
	CHK_OL.createOperationList(CHK_OL.operationList);

	//show category(operationGroupMaster)
	CHK_OL.createCategory();
}

/**
 * get operation list all data
 * 1.operation list
 * 2.category(operationGroupMaster) list
 * 
 * @param {String} searchKeyword
 * @param {Number} sortIndex
 * @param {String} searchStartDate
 * @param {String} searchEndDate
 * @param {Number} operationGroupMasterId
 */
 CHK_OL.getAllDataWeb = function(searchKeyword, sortIndex, searchStartDate, searchEndDate, operationGroupMasterId) {

	let param = {};
	param.cmd = CHK_CONSTANT.ACT_CMD.getOperationList;
	param.sid = CHK_Common.getSid();
	param.operationGroupMasterId = searchKeyword;
	param.sort = sortIndex;
	param.startDate = searchStartDate;
	param.endDate = searchEndDate;
	param.operationGroupMasterId = operationGroupMasterId;

	CHK_Common.sendABookCheckApi(param, false, function(json) {
		CHK_OL.operationList = json.operationList;
		CHK_OL.operationGroupMaster = json.operationGroupMasterList;
		CHK_OL.isOperationGroupMaster = json.isOperationGroupMaster;
		CHK_OL.operationSearchCriteria = json.operationSearchCriteria;
		CHK_OL.setSearchInfoWeb();
		console.log("json.operationList", JSON.stringify(json.operationList));
	 });
}

/**
 * set search criteria when Initial display.
 */
CHK_OL.setSearchInfoWeb = function() {
	CHK_OL.sortIndex = CHK_OL.operationSearchCriteria.sort;
	$("#searchTaskName").val(CHK_OL.operationSearchCriteria.operationName);
    $("#searchStartDate").val(CHK_OL.operationSearchCriteria.startDate);
    $("#searchEndDate").val(CHK_OL.operationSearchCriteria.endDate);
    CHK_OL.operationGroupMasterId = CHK_OL.operationSearchCriteria.operationGroupMasterId;
}

/**
 * create operation list
 */
CHK_OL.createOperationList = function(operationList) {

	//Initialization
	CHK_OL.initActiveSortIndex();
    $('#operationTable').empty();

	if (!operationList) {
		return;
	}

	//create & show
    for (let i = 0; i < operationList.length; i++) {
		let operationTR = $("<tr/>");
		
		const operationNameTd = $("<td class='operationId_" + operationList[i].operationId
		+ "'><a href=\"javascript:CHK_OL.sendOperation('goOperation', '"
				+ operationList[i].operationId + "', '" + operationList[i].operationType+ "', '" + operationList[i].reportType + "');\"  class='d-block text-black text-decoration-none mb-1'>" + operationList[i].operationName
				+ "</a><div class='fa-sm mobile_operation_date'><i class='far fa-clock fa-blue' style='color:blue;margin-right:10px'></i>"
				+ CHK_OL.setOperationDate(operationList[i].operationStartDate) + " ~ "
				+ CHK_OL.setOperationDate(operationList[i].operationEndDate) +"</div></td>");
		const operationStartDateTd = $("<td/>", {class: "operationStartDate"}).text(CHK_OL.setOperationDate(operationList[i].operationStartDate));
		const operationEndDateTd = $("<td/>", {class: "operationEndDate"}).text(CHK_OL.setOperationDate(operationList[i].operationEndDate));

		operationTR.append(operationNameTd);
        operationTR.append(operationStartDateTd);
        operationTR.append(operationEndDateTd);
		
		$(".table tbody").append(operationTR);
	}
};

/**
 * add color to any sorting type when sortIndex exsist
 * 
 * @param {Number} sortIndex 
 */
CHK_OL.initActiveSortIndex = function(sortIndex) {
    
	if (!sortIndex && !CHK_OL.sortIndex) {
        CHK_OL.sortIndex = CHK_CONSTANT.SORT_TYPE.START_DATE_DESC;
	}
    
	$(".sort-type").each(function() {
        const sortType = $(this).data("sort");
		if (sortType == CHK_OL.sortIndex) {
            $(".sort-type").removeClass("active");
			$(this).addClass("active");
		}
	});
}

/**
 * set date for OperationList
 * 
 * @param {String} date 
 * @returns operationDate
 */
CHK_OL.setOperationDate = function(date) {
	const operationDate = date.replace(/-/g, "/").substring(0,10);
	return operationDate;
};

/**
 * create category(operationGroupMaster).
 */
CHK_OL.createCategory = function() {
	
	if (!CHK_OL.isOperationGroupMaster) {
		return;
	}

	CHK_OL.initCategory();
	CHK_OL.createBreadcrumbList();
	CHK_OL.createCategoryList();
	CHK_OL.acdMenu();
};

/**
 * Initial processing of category(operationGroupMaster).
 */
CHK_OL.initCategory = function() {

	if (!CHK_OL.isOperationGroupMaster) {
		return;
	}

	$("#operationGroupMasterButton").removeClass("d-none");
	$(window).resize(function() {
		CHK_OL.setCategoryHeight();
	});
}

/**
 * change height category(operationGroupMaster)
 */
CHK_OL.setCategoryHeight = function() {

	const CATEGORY_HEIGHT = $('footer').offset().top - $('#category-menu').offset().top;
	console.log(CATEGORY_HEIGHT);
	$("#category-menu").css("overflow", "scroll");
	$('#category-menu').height(CATEGORY_HEIGHT);
	$('#overlayDiv').height(CATEGORY_HEIGHT);
}

/**
 * create Breadcrumb List
 */
CHK_OL.createBreadcrumbList = function() {

	if (!CHK_OL.isOperationGroupMaster) {
		return;
	}
	
	$("#groupMasterPath").empty();
    if (typeof CHK_OL.operationGroupMasterId == 'undefined' || CHK_OL.operationGroupMasterId == 0) {
        $("#groupMasterPath").append('<li class="breadcrumb-item"><a href="#" class="text-decoration-none text-dark">' + CHK_Common.getMsg("all") + '</a></li>');
    } else {
        const groupMaster = CHK_OL.operationGroupMaster.filter(it => it.operationGroupMasterId == CHK_OL.operationGroupMasterId)[0];
        const groupMasterPathIdlist = groupMaster.treePath.split('/');
        groupMasterPathIdlist.forEach( function (parentId){
			const pathOperationGroupMaster = CHK_OL.operationGroupMaster.filter(it => it.operationGroupMasterId == parentId)[0];
            $("#groupMasterPath").append('<li class="breadcrumb-item"><a onclick="CHK_OL.changeOperationGroupMaster('
            + pathOperationGroupMaster.operationGroupMasterId + ');" class="text-decoration-none text-dark">'
            + pathOperationGroupMaster.operationGroupMasterName + '</a></li>');
        });
    }
}

/**
 * create category(operationGroupMaster) structure
 */
CHK_OL.createCategoryList = function() {

	if (!CHK_OL.isOperationGroupMaster) {
		return;
	}
	
	//Create a side menu category structure
	$('.group-category-list').remove();
	CHK_OL.operationGroupMaster.sort(function(a, b) {
		if (a.operationGroupMasterLevel < b.operationGroupMasterLevel) return -1;
		if (a.operationGroupMasterLevel > b.operationGroupMasterLevel) return 1;
		return 1;
	});

	//common
	const noCategory = $("<dl id='groupMasterId_0' class='group-category-list'><dt><a onclick='CHK_OL.changeOperationGroupMaster(0);'>"+ CHK_Common.getMsg(CHK_CONSTANT.MSG_MAP.all) + "</a></dt></dl>");
	$('#category-menu').append(noCategory);

	//create category(operationGroupMaster) structure
	for (let i = 0; i < CHK_OL.operationGroupMaster.length; i++) {

		if (CHK_OL.operationGroupMaster[i].operationGroupMasterLevel == 0 ){
	        const categoryParent = $("<dl id=groupMasterId_" + CHK_OL.operationGroupMaster[i].operationGroupMasterId
			+ " class='group-category-list' style='overflow-x:auto;'><dt class='menu-ttl'><a onclick='CHK_OL.changeOperationGroupMaster("
	            + CHK_OL.operationGroupMaster[i].operationGroupMasterId + ");'>" + CHK_OL.operationGroupMaster[i].operationGroupMasterName
	            + "</a></dt></dl>");
            $('#category-menu').append(categoryParent);
	    } else {
            if ($('#groupMasterId_'+ CHK_OL.operationGroupMaster[i].parentOperationGroupMasterId + '>ul').length > 0){
                const categoryChild = $("<li  id='groupMasterId_" + CHK_OL.operationGroupMaster[i].operationGroupMasterId
				+ "' class=''><p class='category-li group-level-" + CHK_OL.operationGroupMaster[i].operationGroupMasterLevel
                    + "'><a class='category-a' onclick='CHK_OL.changeOperationGroupMaster("
                    + CHK_OL.operationGroupMaster[i].operationGroupMasterId + ");'>" + CHK_OL.operationGroupMaster[i].operationGroupMasterName
                    + "</a></p></li>");
					$('#groupMasterId_' + CHK_OL.operationGroupMaster[i].parentOperationGroupMasterId + ' >ul').append(categoryChild);
				} else {
					const groupParents = '#groupMasterId_' + CHK_OL.operationGroupMaster[i].parentOperationGroupMasterId;
					$(groupParents + " > p").addClass("sub-menu-ttl");
					const categoryChild = $("<ul style='display:none;' class=''><li class='' id='groupMasterId_" + CHK_OL.operationGroupMaster[i].operationGroupMasterId
					+ "' class=''><p class='category-li group-level-"
					+ CHK_OL.operationGroupMaster[i].operationGroupMasterLevel
					+ "'><a class='category-a' onclick='CHK_OL.changeOperationGroupMaster(" + CHK_OL.operationGroupMaster[i].operationGroupMasterId
					+ ");'>" + CHK_OL.operationGroupMaster[i].operationGroupMasterName + "</a></p></li></ul>");
                	$('#groupMasterId_' + CHK_OL.operationGroupMaster[i].parentOperationGroupMasterId).append(categoryChild);
            }
	    }
	}
}

/**
 * Open/close category(operationGroupMaster) drawer menu
 */
CHK_OL.acdMenu = function() {

	//Hide accordion contents by default
    $(".drawer-menu dd").css("display", "none");
    $(".drawer-menu2 ul").css("display", "none");

    //second accordion
    $(".drawer-menu dt").on('click', function() {
		$(".sub-menu-ttl").removeClass("openAcd").next().slideUp("fast");
        $(".drawer-menu dt").not(this).removeClass("open").next().slideUp("fast");
        $(this).toggleClass("open").next().slideToggle("fast");
    });
	
    //third accordion
    $(".sub-menu-ttl").on('click', function() {
		$(".sub-menu-ttl").not($(this)).not($(this).parents().siblings("p")).removeClass("openAcd").next().slideUp("fast");
        $(this).toggleClass("openAcd").next().slideToggle("fast");
    });
}

/**
 * Sort the operationList by screen operation
 * 
 * @param {Object} sortType 
 */
CHK_OL.changeSortType = function(sortType) {
	$(".sort-type").removeClass("active");
    $(sortType).addClass("active");
    CHK_OL.sortIndex = $(sortType).attr("data-sort");
	CHK_OL.sortOperationList(sortType);
	CHK_OL.createOperationList(CHK_OL.operationList);
}

/**
 * sort the operationList
 * 
 * @param {Number} sortType 
 */
CHK_OL.sortOperationList = function(sortType) {

	switch(sortType) {
		case CHK_CONSTANT.SORT_TYPE.NAME:
			CHK_OL.operationList.sort(function(a,b) {
				if (a.operationName > b.operationName) return 1;
				if (a.operationName < b.operationName) return -1;
				return 0;
			});
			break;
			case CHK_CONSTANT.SORT_TYPE.START_DATE_DESC:
				CHK_OL.operationList.sort(function(a,b) {
				if (setOperationDate(a.operationStartDate) < setOperationDate(b.operationStartDate)) return 1;
				if (setOperationDate(a.operationStartDate) > setOperationDate(b.operationStartDate)) return -1;
				return 0;
			});
			break;
			case CHK_CONSTANT.SORT_TYPE.START_DATE_ASC:
				CHK_OL.operationList.sort(function(a,b) {
					if (setOperationDate(a.operationStartDate) > setOperationDate(b.operationStartDate)) return 1;
					if (setOperationDate(a.operationStartDate) < setOperationDate(b.operationStartDate)) return -1;
					return 0;
				});
			break;
		case CHK_CONSTANT.SORT_TYPE.TYPE:
			CHK_OL.operationList.sort(function(a,b) {
				if (a.operationType < b.operationType) return 1;
				if (a.operationType > b.operationType) return -1;
				return 0;
			});
			break;
			case CHK_CONSTANT.SORT_TYPE.LAST_EDIT_DATE:
			const defaultDate = "1900-01-01 09:00:00";
			CHK_OL.operationList.sort(function(a,b) {
				if (!a.operationOpenDate) {
					a.operationOpenDate = defaultDate; 
				}
				if (!b.operationOpenDate) {
					b.operationOpenDate = defaultDate;
				}
				if (a.operationOpenDate < b.operationOpenDate) return 1;
				if (a.operationOpenDate > b.operationOpenDate) return -1;
				return 0;
			});
			break;
	}
}

/**
 * search operarionList
 */
CHK_OL.search = function() {
	CHK_Common.showLoading();
    const searchKeyword = $("#searchTaskName").val();
    const searchStartDate = $("#searchStartDate").val();
    const searchEndDate = $("#searchEndDate").val();
	
	if((searchStartDate && searchEndDate) && (searchStartDate > searchEndDate)){
		CHK_Common.closeLoading();
		CHK_Common.displayAlert("dateError");
		return;
	}

	CHK_OL.getAllDataWeb(searchKeyword, CHK_OL.sortIndex, searchStartDate, searchEndDate, CHK_OL.operationGroupMasterId);
    CHK_OL.createOperationList(CHK_OL.operationList);
	CHK_Common.closeLoading();
};

/**
 * change the operationList by select the category(OperationGroupMaster)
 * @param {Number} operationGroupMasterId 
 */
CHK_OL.changeOperationGroupMaster = function(operationGroupMasterId) {
    if ($("#category-menu").hasClass("open")) {
         $('#category-toggle-button').click();
		 $("body").css("overflow", "visible");
		}
		CHK_OL.operationGroupMasterId = operationGroupMasterId;
		CHK_OL.search();
}

/**
 * open the category(OperationGroupMaster)
 */
CHK_OL.openCategory = function() {
	window.scrollTo(0,0);
    if ($("#category-menu").hasClass("open")) {
		$("body").css("overflow", "visible");
   	}else{
		   $("body").css("overflow", "hidden");
	}
}

/**
 * reset search
 */
CHK_OL.resetSearch = function() {
	$('#searchTaskName').val('');
    $('#searchStartDate').val('');
    $('#searchEndDate').val('');
    CHK_OL.changeSortType($('#defaultSort'));
}

/**
 * Transition to the report form or operation list screen
 * 
 * @param {String} operationId
 */
CHK_OL.sendOperation = function(operationId, operationType, reportType) {

	//save operation logs. needed for sorting
	let saveParams = {};
	saveParams.sid = CHK_Common.getSid();
	saveParams.cmd = CHK_CONSTANT.ACT_CMD.saveOperationLog;
	saveParams.deviceType = 4;
	saveParams.operationType = operationType;
	saveParams.reportType = reportType;
	const date = new Date();
	saveParams.viewingStartDate = date.toLocaleString();

	CHK_Common.sendABookCheckApi(saveParam, false)

	//Transition to the report form or operation list screen
	let postParams = {};
	postParams.sid = CHK_Common.getSid();
	postParams.cmd = CHK_CONSTANT.ACT_CMD.goOperation;
	postParams.operationId = operationId;
	const url = CHK_Common.getUrlWeb(postParams.cmd);
	postCommunication(url, postParams);
};