Agilepoint中的JS Method 封装

/**====================================================================================================================================================
 * eform helper
 */
efh = function () {

    /**
     * eform help error handler
     */
    function _handleError(fieldId, error, caller) {
        caller = caller ? caller : "[caller undefined]";
        console.log($.format("Error @efh.{0}(fieldId:\"{1}\"):", caller, fieldId));
        console.log(error);
    }

    /**
     * Show control
     * @param {string} fieldId: Field internal name
     */
    var showControl = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        options.propertyName = eFormHelper.constants.fieldProperty.Visible;
        options.value = true;
        eFormHelper.updateFieldProperty(options, function (result) {
            if (!result.isSuccess && result.error.message && !result.error.message.includes("UpdateIsPropertyModifiedForProp")) {
                _handleError(fieldId, result.error, "showControl");
            }
        });
    };

    /**
     * Hide control
     * @param {string} fieldId: Field internal name
     */
    var hideControl = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        options.propertyName = eFormHelper.constants.fieldProperty.Visible;
        options.value = false;
        eFormHelper.updateFieldProperty(options, function (result) {
            if (!result.isSuccess && result.error.message && !result.error.message.includes("UpdateIsPropertyModifiedForProp")) {
                _handleError(fieldId, result.error, "hideControl");
            }
        });
    };

    /**
     * Enable control
     * @param {string} fieldId: Field internal name
     */
    var enableControl = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        options.propertyName = eFormHelper.constants.fieldProperty.Enabled;
        options.value = true;
        eFormHelper.updateFieldProperty(options, function (result) {
            if (!result.isSuccess && result.error.message && !result.error.message.includes("UpdateIsPropertyModifiedForProp")) {
                _handleError(fieldId, result.error, "enableControl");
            }
        });
    };

    /**
     * Disable control
     * @param {string} fieldId Field internal name
     */
    var disableControl = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        options.propertyName = eFormHelper.constants.fieldProperty.Enabled;
        options.value = false;
        eFormHelper.updateFieldProperty(options, function (result) {
            if (!result.isSuccess && result.error.message && !result.error.message.includes("UpdateIsPropertyModifiedForProp")) {
                _handleError(fieldId, result.error, "disableControl");
            }
        });
    };

    /**
     * Mandatory control(强制控制)
     * @param {string} fieldId: Field internal name
     */
    var mandatoryControl = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        options.propertyName = eFormHelper.constants.fieldProperty.Mandatory;
        options.value = true;
        eFormHelper.updateFieldProperty(options, function (result) {
            if (!result.isSuccess && result.error.message && !result.error.message.includes("UpdateIsPropertyModifiedForProp")) {
                _handleError(fieldId, result.error, "requireControl");
            }
        });
    };

    /**
     * Make control non-mandatory(非强制性)
     * @param {string} fieldId: Field internal name
     */
    var nonmandatoryControl = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        options.propertyName = eFormHelper.constants.fieldProperty.Mandatory;
        options.value = false;
        eFormHelper.updateFieldProperty(options, function (result) {
            if (!result.isSuccess && result.error.message && !result.error.message.includes("UpdateIsPropertyModifiedForProp")) {
                _handleError(fieldId, result.error, "notRequiredControl");
            }
        });
    };

    /**
     * Pop up a notification message.(通知消息框)
     * @param {string} message message
     * @param {function} callback
     * @param {function} closeTimeout: the time of the message window close.
     */
    var alertMessage = function (message, callback, closeTimeout) {
        ShowMessage(message, "通知", eFormHelper.constants.messagetype.Info, callback);
        if (closeTimeout) {
            setTimeout(function (message) {
                var $closeButton = $(".popupMessage").filter(function () { return this.innerText == message; }).closest(".k-widget.k-window").find(".k-icon.k-i-close").last();
                if ($closeButton.length > 0) {
                    $closeButton.click();
                }
            }, closeTimeout, message);
        }
    };

    /**
     * Pop up a warning message.(警告框)
     * @param {string} message message
     * @param {function} callback
     */
    var alertWarning = function (message, callback) {
        ShowMessage(message, "警告", eFormHelper.constants.messagetype.Warning, callback);
    };

    /**
     * Pop up an error message.
     * @param {string} error: error message
     * @param {function} callback 
     */
    var alertError = function (error, callback) {
        ShowMessage(error, "エラー", eFormHelper.constants.messagetype.Error, callback);
    };

    /**
     * Pop up a confirmation message.(确认框)
     * @param {string} message message
     * @param {function} callback
     */
    var confirmMessage = function (message, callback) {
        var options = {};
        options.value = message;
        options.callback = callback;
        eFormHelper.confirmMessage(options, function (result) {
            if (result.isSuccess) {
                if (typeof callback == "function") {
                    options.callback(result.data);
                }
            } else {
                _handleError(fieldId, result.error, "confirmMessage");
            }
        });
    };

    /**
     * Call the control rule(执行窗体运行规则)
     * @param {string} fieldId: Field internal name
     */
    var invokeRule = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        eFormHelper.triggerControlRule(options, function (result) {
            if (!result.isSuccess) {
                _handleError(fieldId, result.error, "invokeRule");
            }
        });
    };

    /**
     * Trigger AutoLookup
     * @param {string} fieldId: Field internal name
     * @param {function} done: Successful callback
     * @param {function} fail: Failed callback
     */
    var triggerAutoLookup = function (fieldId, done, fail) {
        var options = {};
        options.fieldId = fieldId;
        eFormHelper.triggerAutoLookup(options, function (result) {
            if (result.isSuccess) {
                if (typeof done == "function") {
                    done();
                }
            } else {
                _handleError(fieldId, result.error, "triggerAutoLookup");
                if (typeof fail == "function") {
                    fail();
                }
            }
        });
    };

    /**
     * execute Lookup
     * @param {string} fieldId fieldId Field internal name
     * @param {function} done: Successful callback
     * @param {function} fail: Failed callback
     */
    var executeLookup = function (lookupName, done, fail) {
        var options = {};
        options.lookupName = lookupName;
        options.lookupType = eFormHelper.constants.lookuptype.multicolumn
        eFormHelper.executeLookup(options, function (result) {
            if (result.isSuccess) {
                if (typeof done == "function") {
                    done(result);
                }
            } else {
                _handleError(lookupName, result.error, "executeLookup");
                if (typeof fail == "function") {
                    fail();
                }
            }
        });
    }

    /**
     * Reset subform(重置子窗体)
     * @param {*} field Field internal name
     * @param {*} rowCount: the blank row after clear subform. 
     */
    var resetSubForm = function (field, rowCount) {

        clearSubForm(field);

        if (!$.isNumeric(rowCount) || rowCount < 1) {
            rowCount = 1;
        }
        var options = {};
        options.fieldId = field;
        options.value = [];
        for (var i = 0; i < rowCount; i++) {
            options.value.push({});
        }
        eFormHelper.addRowsToSubForm(options, $.noop());
    };

    /**
     * Add rows to Subform(子表增加行)
     * @param {*} field Field internal name
     * @param {*} value Multiple values. e.g.[{Field1-1:'value1-1',Field1-2:'value1-2'},{Field2-1:'value2-1',Field2-2:'value2-2'}]
     */
    var addRowsToSubForm = function (fieldId, value) {
        var options = {};
        options.fieldId = fieldId;
        options.value = value;
        eFormHelper.addRowsToSubForm(options, function (result) {
            if (!result.isSuccess) {
                _handleError(fieldId, result.error, "addRowsToSubForm");
            }
        });
    };

    /**
     * clear a Subform(清除子窗体)
     * @param {*} field Field internal name
     */
    var clearSubForm = function (field) {

        var options = {};
        options.fieldId = field;
        options.rowIndex = '*'; 
        _CustomizeDeleteRowsFromSubForm(options, function(result) 
        { 
            if (!result.isSuccess)  
            { 
                console.log(result.error); //Logs the error and error description, if any.
            }
        });
    };

    /**
     * To delete the Row(s) from a SubForm(子表删除行)
     * Copied from the standard API, but it has been fixed so that the confirmation dialog is not displayed when executing from JS 
     * even if it is set to display the delet confirmation dialog on the control property.
     * @param {options} set fieldId and rowIndex 
     * Specifies rowIndex as asterisk (*) to delete all rows, 
     * or you can specify the row number with comma separation to delete specific rows. For example, '1,2'
     * @param {callback} callback
     */
    var _CustomizeDeleteRowsFromSubForm = function (options, callBack) {
        var result = {
            isSuccess: false,
            error: {}
        };
        if (options.fieldId == undefined || options.fieldId == '' || $.isEmptyObject(options.fieldId)) {
            result.error = 'argument exception';
            return callBack(result);
        }
        try {
            var ctrl = '';
            eFormHelper.getField(options, function (res) {
                ctrl = res.data;
            });
            var fb = $(ctrl).closest('.control').parent().data(Constants.previewWidgetKey);
            if (fb === undefined) {
                result.error = "no path found with given fieldId";
            }
            if (typeof options.rowIndex == "string") {
                var strIndices = options.rowIndex;
                var rowIndices = strIndices.split(',');
                if (rowIndices.length >= 1) {
                    var $subFormContent = fb.target._getContentElementWithFb(fb);
                    var fieldId = $subFormContent[0].id;
                    var subFormContentRows = document.getElementById(fieldId).querySelectorAll(".subFormContentRow");
                    var deleteRowsList = [];
                    rowIndices.forEach(function (rowNumber) {
                        if (rowNumber !== '*') {
                            deleteRowsList.push(subFormContentRows[rowNumber - 1]);
                        } else {
                            for (var i = 0; i < subFormContentRows.length; i++) {
                                deleteRowsList.push(subFormContentRows[i]);
                            }
                        }
                    });
                    deleteRowsList.forEach(function (item) {
                        var delButton = item.querySelector(':scope > .subFormContentRowChildWrapper > .rowActionButtons > .deleteSubFormRow');
                        //Changed to call the customized row delete event.
                        _CustomizeExecuteDeleteRowEvent(fb, $(delButton));
                    });
                    result.isSuccess = true;
                } else {

                    result.error = 'no records found';
                }
            }

        } catch (ex) {
            result.isSuccess = false;
            result.error = ex;
        }
        if (typeof callBack == 'function') {
            callBack(result);
        }
    };
    
     /**
     * SubForm Rows delete event.(行删除事件)
     * Copied from the standard API, but not displays the confirmation dialog when delete subform row.
     * @param {e} 
     * @param {t} 
     */
    var _CustomizeExecuteDeleteRowEvent = function (e, t) {
        try {
            var a = e.target._getContentElementWithFb(e);
            if ("true" == t.parents(".subFormContentRow:first").attr("isreadonlyrow")){
                return;
            };
            e.target._handleDataSourceChangeLog(e, t.parents(".subFormContentRow:first"), "Delete");
            e.target._deleteContentRow(e, a.find("> .subFormContentRow").index(t.parents(".subFormContentRow:first")), t);
            e.target._deleteRecordSubFormEvent(e);
        } catch (e) {
            FormBuilder._log(e)
        }
    };


    /**
     * Set the cover
     * @param {*} isShow: if shwo the cover.
     */
    var toggleLoader = function (isShow) {
        __loader = __loader || document.querySelector('.loader');
        var toggler = function () {
            if (isShow) {
                __loader.style.display = 'block';
            } else {
                __loader.style.display = 'none';
            }
        };

        clearTimeout(timeOut);
        timeOut = setTimeout(function () {
            toggler();
        }, 10);
    };

    /**
     * Get field value (Be careful of timing issues!)
     * @param {string} fieldId
     * @returns {string} value
     */
    var getFieldValue = function (fieldId) {
        var options = {};
        options.fieldId = fieldId;
        eFormHelper.getFieldValue(options, function (result) {
            if (!result.isSuccess) {
                _handleError(fieldId, result.error);
            }
            options.result = result;
        });
        if (options.result.isSuccess) {
            return options.result.data;
        }
    };

    /**
     * Set field value (Be careful of timing issues!)
     * @param {string} fieldId
     * @returns {string} value
     */
    function setFieldValue(fieldId, value) {
            var options = {};
            options.fieldId = fieldId;
            if(typeof value == "number")
            {value = value.toString();}
            options.value = value ? value : "";
            eFormHelper.setFieldValue(options, function (result) {
                if (!result.isSuccess) {
                    _handleError(fieldId, result.error);
                }
            });
    }
    
    /**
     * Get field Object
     * @param {string} fieldName
     * @returns fieldld object
     */
    function getFieldObject(fieldName) {
        var fieldObj = {};
        eFormHelper.getField({ fieldId: fieldName }, function (result) { fieldObj = result.data; });
        return fieldObj;
    }    
    
    /**
     * Get field Text
     * @param {string} fieldName
     * @returns fieldld object
     */
    function getFieldText(fieldName) {
      var returndata;
      eFormHelper.getFieldText ({ fieldId: fieldName}, function (result) {returndata = result.data});
      return returndata;
    }

    /*
    * Validation
    * @date : 2021-12-26
    * @author : Joe Ma
    * @version : 1.0.0
    */
    function triggerValidate(fieldName)
    {
        var id= efh.getFieldObject(fieldName).uniqueId().get(0).id;
        efh.mandatoryControl(id);
        var valid=false;
        var options = {};
        options.fieldId = fieldName;
        eFormHelper.triggerControlValidation(options, function (result)
        {
            if (result.isSuccess)
            {
                if ($('#'+id).matchingParent('div').find('.lblValidationMsg').get(0).innerText=="")
                {
                    valid=true;
                }
                console.log(fieldName+":"+valid);
            }else{
                console.log(result.error); // logs the hold exception object
            }
        });
        efh.nonmandatoryControl(id);
        return valid;
    }
    
    /*
     * Asyc Execute Lookup(同步执行lookup)
     * @param (string) lookup name
     */ 
    function asycExecuteLookup(lkName)
    {
        return new Promise(function(resolve, reject)  {
            eFormHelper.executeLookup({ lookupName: lkName, lookupType: eFormHelper.constants.lookuptype.multicolumn }, function (result) {
                    if (result.data) {
                       if (!$.isArray(result.data)) {
                           result.data = [result.data];
                       }  
                        resolve(result.data);
                    }
                    else
                    {
                        reject("Failed");
                    }
            });
        })
    }
    
    /*
    * Validation(执行公式)
    * @date : 2022-03-17
    * @author : Delong
    * @version : 1.0.0
    */
    function triggerFormula(fieldId)
    {
        var options = {};
        options.fieldId = fieldId;
        eFormHelper.triggerFormula(options, function (result)
          {
          if (result.isSuccess) 
            {
            console.log(result.data); //logs the data holds the empty object
            }
          else 
            {
            console.log(result.error); // logs the hold exception object 
            }      
          });
    }

    /**
     * return eform helper
     * @returns {function[]}
     */
    return {
        showControl: showControl,
        hideControl: hideControl,
        enableControl: enableControl,
        disableControl: disableControl,
        mandatoryControl: mandatoryControl,
        nonmandatoryControl: nonmandatoryControl,
        alertMessage: alertMessage,
        alertWarning: alertWarning,
        alertError: alertError,
        confirmMessage: confirmMessage,
        invokeRule: invokeRule,
        triggerAutoLookup: triggerAutoLookup,
        executeLookup: executeLookup,
        resetSubForm: resetSubForm,
        addRowsToSubForm: addRowsToSubForm,
        clearSubForm: clearSubForm,
        toggleLoader: toggleLoader,
        getFieldValue: getFieldValue,
        setFieldValue: setFieldValue,
        getFieldObject: getFieldObject,
        getFieldText: getFieldText,
        triggerValidate: triggerValidate,
        asycExecuteLookup: asycExecuteLookup,
        triggerFormula: triggerFormula
    };
}();

 

posted @ 2022-07-22 14:36  艺洁  阅读(422)  评论(0编辑  收藏  举报