/**
 * 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 OL = {};

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

OL.sortIndex;
OL.operationGroupMasterId;

/**
 * process on page load.
 * 1.get all data.
 * 2.show operationList.
 * 3.show category(operationGroupMaster).
 */
OL.init = function () {
    console.log('OperationList start');
    sessionStorage.activeHomePage = CONSTANT.PAGE_TAB.OPERATION_LIST;
    sessionStorage.removeItem("operationId");
    sessionStorage.removeItem("RL_searchWord");
    TEMPLATE.loadHeader('#includedHeader');
    
    TEMPLATE.loadMainNavsTitle('#includedMainTitle', 'workList', true, null);
    TEMPLATE.loadConfirmModal('#includedConfirmModal');
    //get all data of operation list scene
    OL.getAllDataWeb(sessionStorage.OL_searchKeyWord, sessionStorage.OL_sortIndex, sessionStorage.OL_searchStartDate, sessionStorage.OL_searchEndDate, sessionStorage.OL_operationGroupMasterId);

    //show operation list
    OL.createOperationList(OL.operationList);

    //show category(operationGroupMaster)
    $('#includedCategoryModal').load('../common/category-modal.html', function () {
        OL.createCategory();
        I18N.initi18n();
    });
};

/**
 * 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
 */
OL.getAllDataWeb = function (searchKeyWord, sortIndex, searchStartDate, searchEndDate, operationGroupMasterId) {
    let param = {};
    param.sid = COMMON.getSid();
    if (typeof searchKeyWord !== 'undefined') {
        param.operationName = searchKeyWord;
    }
    if (typeof sortIndex !== 'undefined') {
        param.sort = sortIndex;
    }
    if (typeof searchStartDate !== 'undefined') {
        param.startDate = searchStartDate;
    }
    if (typeof searchEndDate !== 'undefined') {
        param.endDate = searchEndDate;
    }
    if (typeof operationGroupMasterId !== 'undefined') {
        param.operationGroupMasterId = operationGroupMasterId;
    }

    const url = COMMON.format(ClientData.conf_checkApiUrl(), ClientData.userInfo_accountPath()) + CONSTANT.URL.CMS.API.ALL_OPERATION_LIST;

    COMMON.cmsAjax(url, param, false, function (json) {
        OL.saveSearchKeyWord(searchKeyWord, sortIndex, searchStartDate, searchEndDate, operationGroupMasterId);
        OL.setSearchInfoWeb();
        OL.operationList = json.operationList;
        OL.operationGroupMaster = json.operationGroupMasterList;
        OL.isOperationGroupMaster = json.isOperationGroupMaster;
    });
};

/**
 * Transfer search criteria to session.
 * Keep value after page move.
 *
 * @param {String} searchKeyword
 * @param {String} sortIndex
 * @param {String} searchStartDate
 * @param {String} searchEndDate
 * @param {String} operationGroupMasterId
 */
OL.saveSearchKeyWord = function (searchKeyword, sortIndex, searchStartDate, searchEndDate, operationGroupMasterId) {
    if (typeof searchKeyword !== 'undefined') {
        sessionStorage.OL_searchKeyWord = searchKeyword;
    }
    if (typeof sortIndex !== 'undefined') {
        sessionStorage.OL_sortIndex = sortIndex;
    }
    if (typeof searchStartDate !== 'undefined') {
        sessionStorage.OL_searchStartDate = searchStartDate;
    }
    if (typeof searchEndDate !== 'undefined') {
        sessionStorage.OL_searchEndDate = searchEndDate;
    }
    if (typeof operationGroupMasterId !== 'undefined') {
        sessionStorage.OL_operationGroupMasterId = operationGroupMasterId;
    }
};

/**
 * set search criteria when Initial display.
 */
OL.setSearchInfoWeb = function () {
    if (sessionStorage.OL_sortIndex) {
        OL.sortIndex = sessionStorage.OL_sortIndex;
    }
    if (sessionStorage.OL_searchKeyWord) {
        $('#searchTaskName').val(sessionStorage.OL_searchKeyWord);
    }
    if (sessionStorage.OL_searchStartDate) {
        $('#searchStartDate').val(sessionStorage.OL_searchStartDate);
    }
    if (sessionStorage.OL_searchEndDate) {
        $('#searchEndDate').val(sessionStorage.OL_searchEndDate);
    }
    if (sessionStorage.OL_operationGroupMasterId) {
        OL.operationGroupMasterId = sessionStorage.OL_operationGroupMasterId;
    }
};

/**
 * create operation list
 * @param operarionList
 */
OL.createOperationList = function (operationList) {
    //Initialization
    OL.initActiveSortIndex();
    $('#operationTable').empty();
    $('#operationCount').text(0);

    if (!operationList) {
        return;
    }
    $('#operationCount').text(operationList.length);
    //create & show
    for (let i = 0; i < operationList.length; i++) {
        let classIcon;
        switch (operationList[i].reportType) {
            case CONSTANT.REPORT_TYPE_INT.REPORT:
                classIcon = 'report';
                break;
            case CONSTANT.REPORT_TYPE_INT.ROUTINE:
                classIcon = 'inspection';
                break;
            case CONSTANT.REPORT_TYPE_INT.ANSWER:
                classIcon = 'questionary';
                break;
            case CONSTANT.REPORT_TYPE_INT.WORKFLOW:
                classIcon = 'proccess';
                break;
        }
        let messageli = $("<li class='card mb-2' name = 'operationId_" + operationList[i].operationId + "' ></li>");
        let ahrefRequiredFlg = $(
            '<a href="javascript:OL.sendOperation(\'' +
                operationList[i].operationId +
                "', '" +
                operationList[i].operationType +
                "', '" +
                operationList[i].reportType +
                "', '" +
                operationList[i].enableAddReport +
                "');\" class='h-100 d-block px-3 py-2 text-decoration-none text-dark position-relative'></a>",
        );
        let divIcon = $("<div class='position-absolute translate-middle top-50 left-0 ml-3'>" + "<div class='type-icon'>" + "<span class='" + classIcon + "'></span>" + '</div></div>');

        let divDate =
            "<div class='fs-8 text-secondary text-truncate'>" + OL.setOperationDate(operationList[i].operationStartDate) + ' ~ ' + OL.setOperationDate(operationList[i].operationEndDate) + '</div>';

        let divText = $(
            "<div class='pl-5 h-100 d-flex align-items-center'>" + "<div class='w-100'>" + "<div class='fs-12 text-truncate'>" + operationList[i].operationName + '</div>' + divDate + '</div></div>',
        );
        ahrefRequiredFlg.append(divIcon);
        ahrefRequiredFlg.append(divText);
        messageli.append(ahrefRequiredFlg);

        $('#operationTable').append(messageli);
    }
};

/**
 * add color to any sorting type when sortIndex exsist
 *
 * @param {Number} sortIndex
 */
OL.initActiveSortIndex = function (sortIndex) {
    if (!sortIndex && !OL.sortIndex) {
        OL.sortIndex = CONSTANT.SORT_TYPE.START_DATE_DESC;
    }

    $('.sort-type').each(function () {
        const sortType = $(this).data('sort');
        if (sortType == OL.sortIndex) {
            $('.sort-type').removeClass('active');
            $(this).addClass('active');
        }
    });
};

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

/**
 * create category(operationGroupMaster).
 */
OL.createCategory = function () {
    if (!OL.isOperationGroupMaster) {
        return;
    }
    OL.initCategory();
    OL.createBreadcrumbList();
    OL.createCategoryList();
};

/**
 * Initial processing of category(operationGroupMaster).
 */
OL.initCategory = function () {
    if (!OL.isOperationGroupMaster) {
        return;
    }
    $('#operationGroupMasterButton').removeClass('d-none');
};

/**
 * create Breadcrumb List
 */
OL.createBreadcrumbList = function () {
    if (!OL.isOperationGroupMaster) {
        return;
    }

    $('#groupMasterPath').empty();
    if (typeof OL.operationGroupMasterId === 'undefined' || OL.operationGroupMasterId == 0) {
        $('#groupMasterPath').append('<li class="breadcrumb-item"><a href="#" class="text-decoration-none text-underline">' + I18N.i18nText('categoryAll') + '</a></li>');
    } else {
        let treeList = [];
        OL.createBreadcrumbTree(treeList, OL.operationGroupMasterId);
        treeList.forEach(function (operationGroupMaster) {
            if (operationGroupMaster.operationGroupMasterId != OL.operationGroupMasterId) {
                $('#groupMasterPath').append(
                    '<li class="breadcrumb-item"><a onclick="OL.changeOperationGroupMaster(' +
                        operationGroupMaster.operationGroupMasterId +
                        ');" class="text-decoration-none text-underline">' +
                        operationGroupMaster.operationGroupMasterName +
                        '</a></li>',
                );
            } else {
                $('#groupMasterPath').append('<li class="breadcrumb-item active" aria-current="page"><span>' + operationGroupMaster.operationGroupMasterName + '</span></li>');
            }
        });
    }
};

/**
 * create Breadcrumb tree List
 *
 * @param {list} treeList
 * @param {string} operationGroupMasterId
 * @returns
 */
OL.createBreadcrumbTree = function (treeList, operationGroupMasterId) {
    if (operationGroupMasterId == 0) {
        return treeList;
    }

    const groupMaster = OL.operationGroupMaster.filter(it => it.operationGroupMasterId == operationGroupMasterId)[0];
    OL.createBreadcrumbTree(treeList, groupMaster.parentOperationGroupMasterId);
    treeList.push(groupMaster);
    return treeList;
};

/**
 * create category(operationGroupMaster) structure
 */
OL.createCategoryList = function () {
    if (!OL.isOperationGroupMaster) {
        return;
    }
    //Create a side menu category structure
    var categoryListElement = $('#categoryListMenu');
    categoryListElement.empty();
    //sort group master list by level low to hight
    OL.operationGroupMaster.sort(function (a, b) {
        if (a.operationGroupMasterLevel < b.operationGroupMasterLevel) return -1;
        if (a.operationGroupMasterLevel > b.operationGroupMasterLevel) return 1;
        return 1;
    });
    let allChecked = '';
    if (typeof OL.operationGroupMasterId === 'undefined' || OL.operationGroupMasterId == 0) {
        allChecked = ' checked';
    }
    const allCategory = $(
        '<ul><li><label><input type="radio" name="category" value="0"' + allChecked + '> <span>' + I18N.i18nText('categoryAll') + '</span></label></li></ul>',
    );
    categoryListElement.append(allCategory);
    //create category(operationGroupMaster) structure
    for (let i = 0; i < OL.operationGroupMaster.length; i++) {
        const item = OL.operationGroupMaster[i];
        // console.log(item);
        let inputLabel = $('<label>');
        let inputRadio = $('<input type="radio" name="category">');
        inputRadio.val(item.operationGroupMasterId);
        if (OL.operationGroupMasterId && OL.operationGroupMasterId == item.operationGroupMasterId) {
            inputRadio.prop('checked', true);
        }
        let groupSpan = $('<span>' + item.operationGroupMasterName + '</span>');
        inputLabel.append(inputRadio);
        inputLabel.append(' ');
        inputLabel.append(groupSpan);
        const isParent = OL.operationGroupMaster.find(function(child) {
            return item.operationGroupMasterId == child.parentOperationGroupMasterId;
        });
        let parentElement = categoryListElement;
        if (item.parentOperationGroupMasterId != 0) {
            parentElement = $('#collapse' + item.parentOperationGroupMasterId + ' > ul');
        }
        if (isParent) {
            //accordion
            const accordionId = 'accordion' + item.operationGroupMasterId;
            const headingId = 'heading' + item.operationGroupMasterId;
            const collapseId = 'collapse' + item.operationGroupMasterId;
            let accordionElm = $('<li class="accordion" id="' + accordionId + '" />');
            //heading
            let headingDiv = $('<div id="' + headingId + '" />');
            let linkA = $('<a class="list-menu-link" />');
            let collapseButton = $('<button type="button" class="collapsed" data-toggle="collapse" aria-expanded="true" />');
            collapseButton.attr('data-target', '#' + collapseId);
            collapseButton.attr('aria-controls', collapseId);
            collapseButton.append('<div class="arrow-icon"></div>');
            linkA.append(collapseButton);
            linkA.append(inputLabel);
            headingDiv.append(linkA);
            //collapse
            let collapseElm = $('<div id="' + collapseId + '" class="collapse">');
            collapseElm.attr('data-parent', '#' + accordionId);
            collapseElm.attr('aria-labelledby', headingId);
            let ul = $('<ul>');
            collapseElm.append(ul);
            accordionElm.append(headingDiv);
            accordionElm.append(collapseElm);
            parentElement.append(accordionElm);
        } else {
            let li = $('<li>');
            li.append(inputLabel);
            parentElement.append(li);
        }
    }
};

/**
 * Handle onclick category selection button
 */
OL.onClickCategorySelection = function () {
    const operationGroupMasterId = $('input[name="category"]:checked').val();
    $('#category-modal .close').click();
    OL.changeOperationGroupMaster(operationGroupMasterId);
};

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

/**
 * sort the operationList
 *
 * @param {Number} sortNumber
 */

OL.sortOperationList = function (sortNumber) {
    if (!OL.operationList) {
        return;
    }
    switch (sortNumber) {
        case CONSTANT.SORT_TYPE.NAME:
            OL.operationList.sort(function (a, b) {
                if (a.operationName > b.operationName) return 1;
                if (a.operationName < b.operationName) return -1;
                return 0;
            });
            break;
        case CONSTANT.SORT_TYPE.START_DATE_DESC:
            OL.operationList.sort(function (a, b) {
                if (OL.setOperationDate(a.operationStartDate) < OL.setOperationDate(b.operationStartDate)) return 1;
                if (OL.setOperationDate(a.operationStartDate) > OL.setOperationDate(b.operationStartDate)) return -1;
                return 0;
            });
            break;
        case CONSTANT.SORT_TYPE.START_DATE_ASC:
            OL.operationList.sort(function (a, b) {
                if (OL.setOperationDate(a.operationStartDate) > OL.setOperationDate(b.operationStartDate)) return 1;
                if (OL.setOperationDate(a.operationStartDate) < OL.setOperationDate(b.operationStartDate)) return -1;

                return 0;
            });
            break;
        case CONSTANT.SORT_TYPE.TYPE:
            OL.operationList.sort(function (a, b) {
                if (a.operationType < b.operationType) return 1;
                if (a.operationType > b.operationType) return -1;
                return 0;
            });
            break;
        case CONSTANT.SORT_TYPE.LAST_EDIT_DATE:
            const defaultDate = '1900-01-01 09:00:00';
            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
 */
OL.search = function () {
    COMMON.showLoading();
    const searchKeyword = $('#searchTaskName').val();
    const searchStartDate = $('#searchStartDate').val();
    const searchEndDate = $('#searchEndDate').val();

    if (searchStartDate && searchEndDate && searchStartDate > searchEndDate) {
        COMMON.closeLoading();
        COMMON.displayAlert('dateError');
        return;
    }

    OL.getAllDataWeb(searchKeyword, OL.sortIndex, searchStartDate, searchEndDate, OL.operationGroupMasterId);
    OL.createOperationList(OL.operationList);
    OL.createCategory();
    COMMON.closeLoading();
};

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

/**
 * open the category(OperationGroupMaster)
 */
OL.openCategory = function () {};

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

/**
 * Transition to the report form or operation list screen
 * @param {*} operationId
 * @param {*} operationType
 * @param {*} reportType
 * @param {*} enableAddReport
 */
OL.sendOperation = function (operationId, operationType, reportType, enableAddReport) {
    //save operation logs. needed for sorting
    OL.saveOperationReadingLog(operationId, operationType, reportType);
    //Transition to the report form or operation list screen
    sessionStorage.setItem("operationId", operationId);
    if (enableAddReport == '1' || reportType == CONSTANT.REPORT_TYPE.ROUTINE) {
        COMMON.avwScreenMove('reportList.html');
    } else {
        const url = 'reportForm.html?operationId=' + operationId + "&addReport=" + enableAddReport;
        COMMON.avwScreenMove(url);
    }
};

/**
 * save operation logs. needed for sorting
 *
 * @param {String} operationId
 * @param {String} operationType
 * @param {String} reportType
 */
OL.saveOperationReadingLog = function (operationId, operationType, reportType) {
    let params = {};
    params.sid = COMMON.getSid();
    params.operationId = operationId;
    params.deviceType = CONSTANT.DEVICE_TYPE.WEB;
    params.operationType = operationType;
    params.reportType = reportType;
    params.viewingStartDate = COMMON.currentTime();
    const url = COMMON.format(ClientData.conf_checkApiUrl(), ClientData.userInfo_accountPath()) + CONSTANT.URL.CMS.API.OPERATION_VIEW_LOG;
    COMMON.cmsAjax(url, params, false);
};

/**
 * return url of cms Operation Scene
 *
 * @param {boolean} enableAddReport
 * @param {Number} reportType
 * @returns url
 */
OL.createUrlOfOperation = function (enableAddReport, reportType) {
    let baseUrl = COMMON.format(ClientData.conf_checkApiUrl(), ClientData.userInfo_accountPath()) + CONSTANT.URL.CMS.HTML.BASE;
    if (reportType == CONSTANT.REPORT_TYPE.ROUTINE || enableAddReport == '1') {
        return baseUrl + CONSTANT.URL.CMS.HTML.TASK_REPORT_LIST;
    } else {
        return baseUrl + CONSTANT.URL.CMS.HTML.LIST_REPORT_FORM;
    }
};
