/**
 * 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');

    //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)
    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
 */
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 = CONSTANT.URL.CMS.BASE + ClientData.userInfo_accountPath() + CONSTANT.URL.CMS.API.BASE + 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
 */
OL.createOperationList = function (operationList) {
    //Initialization
    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:OL.sendOperation('" +
                operationList[i].operationId +
                "', '" +
                operationList[i].operationType +
                "', '" +
                operationList[i].reportType +
                "', '" +
                operationList[i].enableAddReport +
                "');\"  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>" +
                OL.setOperationDate(operationList[i].operationStartDate) +
                ' ~ ' +
                OL.setOperationDate(operationList[i].operationEndDate) +
                '</div></td>',
        );
        const operationStartDateTd = $('<td/>', { class: 'operationStartDate' }).text(OL.setOperationDate(operationList[i].operationStartDate));
        const operationEndDateTd = $('<td/>', { class: 'operationEndDate' }).text(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
 */
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();
    OL.acdMenu();
};

/**
 * Initial processing of category(operationGroupMaster).
 */
OL.initCategory = function () {
    if (!OL.isOperationGroupMaster) {
        return;
    }

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

/**
 * change height category(operationGroupMaster)
 */
OL.setCategoryHeight = function () {
    const CATEGORY_HEIGHT = $('footer').offset().top - $('#category-menu').offset().top;
    $('#category-menu').css('overflow', 'scroll');
    $('#category-menu').height(CATEGORY_HEIGHT);
    $('#overlayDiv').height(CATEGORY_HEIGHT);
};

/**
 * 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-dark">' + COMMON.getMsg('all') + '</a></li>');
    } else {
        let treeList = [];
        OL.createBreadcrumbTree(treeList, OL.operationGroupMasterId);
        treeList.forEach(function (operationGroupMaster) {
            $('#groupMasterPath').append(
                '<li class="breadcrumb-item"><a onclick="OL.changeOperationGroupMaster(' +
                    operationGroupMaster.operationGroupMasterId +
                    ');" class="text-decoration-none text-dark">' +
                    operationGroupMaster.operationGroupMasterName +
                    '</a></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
    $('.group-category-list').remove();
    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='OL.changeOperationGroupMaster(0);'>" + COMMON.getMsg('all') + '</a></dt></dl>');

    $('#category-menu').append(noCategory);

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

/**
 * Open/close category(operationGroupMaster) drawer menu
 */
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
 */
OL.changeSortType = function (sortType) {
    $('.sort-type').removeClass('active');
    $(sortType).addClass('active');
    OL.sortIndex = $(sortType).attr('data-sort');
    const sortStr = sortType.dataset.sort;
    const sortNumber = parseFloat(sortStr);
    OL.sortOperationList(sortNumber);
    OL.createOperationList(OL.operationList);
};

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

OL.sortOperationList = function (sortNumber) {
    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 () {
    window.scrollTo(0, 0);
    if ($('#category-menu').hasClass('open')) {
        $('body').css('overflow', 'visible');
    } else {
        $('body').css('overflow', 'hidden');
    }
};

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

/**
 * Transition to the report form or operation list screen
 *
 * @param {String} operationId
 */
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
    let params = {};
    params.sid = COMMON.getSid();
    params.operationId = operationId;
    params.returnUrl = CONSTANT.URL.WEB.BASE + CONSTANT.URL.WEB.OPERATION_LIST;
    const url = OL.createUrlOfOperation(enableAddReport, reportType);
    COMMON.postCommunication(url, params);
};

/**
 * 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 = CONSTANT.URL.CMS.BASE + ClientData.userInfo_accountPath() + CONSTANT.URL.CMS.API.BASE + 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 = CONSTANT.URL.CMS.BASE + 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;
    }
};