define('DS/TestCommand/TestCommand', [
    'UWA/Core',
    'DS/ApplicationFrame/Command',
    'DS/ENOXEngineerCommonUtils/XENModal',
    'DS/Utilities/Utils',
    'DS/ENOXEngineerCommonUtils/XENMask',
    'DS/ENOXEngineerCommonUtils/xEngAlertManager',
    'DS/EngineeringItemCmd/SetPartNumberCmd/setPartNumberListView',
    'DS/ENOXEngineerCommonUtils/XENPlatform3DXSettings',
    'DS/ENOXEngineerCommonUtils/PromiseUtils',
    'DS/EngineeringItemCmd/SetPartNumberCmd/setPartNumberHttpClient',
    'DS/ENOXEngineerCommonUtils/XENCommandsAppContextProxy',
    'DS/PlatformAPI/PlatformAPI',
    'DS/ENOXEngineerCommonUtils/XENWebInWinHelper',
    'DS/EngineeringItemCmd/SetPartNumberCmd/SetPartProgressDialog',
    'DS/EngineeringItemCmd/SetPartNumberCmd/SetPartConstants',
    'i18n!DS/EngineeringItemCmd/assets/nls/ExposedCmdsNls.json',
    'text!DS/TestCommand/index.html'
], function (
    UWA,
    AFRCommand,
    XEngineerModal,
    Utils,
    Mask,
    xEngAlertManager,
    PartNumberListView,
    XENPlatform3DXSettings,
    PromiseUtils,
    xAppWSCalls,
    XENCommandsAppContextProxy,
    PlatformAPI,
    XENWebInWinHelper,
    SetPartProgressDialog,
    SetPartConstants,
    nlsKeys,
    HTMLsetPartNumberListView) {
    'use strict';

    var SetPartNumber = AFRCommand.extend({
        _setPartNumberListView: null,
        items: [],
        modal: null,
        transactionParameters: null,
        sTenentID: "OnPremise",
        securityContext: null,
        myBaseAppURL: null,
        init: function (options) {
            console.log(111);
            options = UWA.extend(options, {
                isAsynchronous: false
            });
            this._parent(options);

            // IR-749796-3DEXPERIENCER2021x
            // The initialization is to early to get the app Security context to correct it
            // the initialization has been deplaced in isUserGranted call and the that.enable() is now check with isUserGranted
            // XENCommandsAppContextProxy.loadCommandsSetting();
            this._initCommandPrereqs();
        },
        isUserGranted: function () {
            var that = this;
            if (this.grantingPromise)
                return this.grantingPromise;
            this.grantingPromise = PromiseUtils.wrappedWithCancellablePromise(function (resolve, reject) {
                XENCommandsAppContextProxy.loadCommandsSetting()
                    .then(function (settings) {
                        if (settings && settings.isGrantedEnterpriseExtension) {
                            resolve(true);
                        } else {
                            if (XENPlatform3DXSettings.isCatiaV6Environment()) { //Setting added for IR-788376-3DEXPERIENCER2020x
                                resolve(true);
                            } else {
                                reject('user is not granted');
                            }
                        }
                    }).catch(function (reason) {
                        if (XENPlatform3DXSettings.isCatiaV6Environment()) { //Setting added for IR-788376-3DEXPERIENCER2020x
                            resolve(true);
                        } else {
                            console.error(reason);
                            reject('some failure');
                        }
                    });
            });
            return this.grantingPromise;
        },
       
        bindEditModeListener: function () {
            console.log(444);
            var that = this;
            if (that.options.context &&
                typeof that.options.context.addEvent === "function") {
                that.options.context.addEvent('editModeModified', function (state) {
                    if (state === true) {
                        that._checkSelection();
                    } else {
                        that.disable();
                    }
                });
            }
        },
        _checkSelection: function () {
            console.log(555);
            var that = this;
            if (that.options.context &&
                typeof that.options.context.getEditMode === "function") {
                if (!that.options.context.getEditMode())
                    return that.disable();
            }

            if (!Array.isArray(that.options.context.getSelectedNodes()) ||
                that.options.context.getSelectedNodes().length === 0) {
                return that.disable();
            } else {
                var SelectedNodes = that.options.context.getSelectedNodes();
                for (var i = 0; i < SelectedNodes.length; i++) {
                    var node = SelectedNodes[i];
                    if (!node || !node.getID()) { // for not saved items
                        return that.disable();
                    }
                    if (node.options.type === 'VPMReference')
                        continue;

                    if (node.options.type === 'Drawing' ||
                        !node.options.padgrid ||
                        node.options.padgrid['ds6w:globalType'] !== 'ds6w:Part') {
                        return that.disable();
                    }
                }
                that.isUserGranted().then(function () {
                    that.enable();
                }).catch(function (reason) {
                    console.error(reason);
                    that.disable();
                });
            }
        },
        //
        _buildSetPartNumDialog: function () {
            console.log(666);
            if (this._setPartNumberListView) {
                this._setPartNumberListView.destroy();
                this._setPartNumberListView = null;
            }
            var that = this;

            that._setPartNumberListView = new PartNumberListView();
            that._setPartNumberListView.render();
            console.log(123123);
            console.log(that._setPartNumberListView.render());
            that.retrievePartNumber();
        },
        //删除视图
        destroyView: function (isErrorThrown) {
            console.log(777);
            var that = this;
            if (that._setPartNumberListView) {
                that._setPartNumberListView.destroy();
                that._setPartNumberListView = null;
            }
            if (that.modal && that.modal.isNotDestroyed()) {
                that.modal.dispose();
                that.modal = null;
            }

            if (XENWebInWinHelper) {
                if (isErrorThrown == true) {
                    XENWebInWinHelper.closePanel(isErrorThrown);
                } else {
                    XENWebInWinHelper.closePanel();
                }
            }
        },
        buildModal: function () {
            console.log(888);
            var that = this;
            widget.innerHtml = HTMLsetPartNumberListView;

            this.modal = new XEngineerModal({
                // title: nlsKeys.get("edit_test_command"),
                // className: 'set-partNumber-modal',
                withFooter: true,
                customFooter: function () {
                    if (that._setPartNumberListView.isEINSettingBlockedForUsers()) {
                        return '<button type="button" name="closeButton" class="btn btn-default closeButton">' + nlsKeys.get('eng.ui.button.close') + '</button>';
                    } else {
                        return '<button type="button" name="setEINButton" class="btn btn-primary setEINButton">' + nlsKeys.get('eng.ui.button.ok') + '</button>' +
                            '<button type="button" name="cancelButton" class="btn btn-default">' + nlsKeys.get('eng.ui.button.cancel') + '</button>';
                    }
                },
                persitId: 'edit_test_command',
                relatedCommand: that,
                onClose: function () {
                    that.destroyView();
                    that.end();
                    that.modal = undefined;
                }
            });
        },
        formatForRefreshView: function (data) {
            console.log(999);
            if (!data || !Array.isArray(data.references)) return [];

            return data.references.map(function (item) {
                return {
                    physicalid: item.physicalid,
                    attributes: [{
                        name: "ds6wg:EnterpriseExtension.V_PartNumber",
                        value: item.partNumber
                    }]
                }
            })
        },
        getProvidedSC: function () {
            console.log(1010);
            if (!this.options.context || !this.options.context.getSecurityContext)
                return null;

            var _sc = this.options.context.getSecurityContext() || {};
            var value = _sc.SecurityContext;
            if (_sc.SecurityContext) {
                if (value.startsWith('ctx::'))
                    value = value.substring(5);
                XENPlatform3DXSettings.setDefaultSecurityContext(value);
            }

            if (_sc.tenant) {
                XENPlatform3DXSettings.setPlatformId(_sc.tenant);
            }

            return value;
        },
        execute: function () {
            console.log(1012);
            var that = this;
            var selectedObjetcsCount = that.options.context.getSelectedNodes().length;
            if (selectedObjetcsCount > SetPartConstants.CONSTANT_LIMIT_EIN) {
                xEngAlertManager.errorAlert(nlsKeys.get("eng.partNumber.limit.title").replace('$1', selectedObjetcsCount));
                return;
            }
            this.progressDialog = new SetPartProgressDialog();
            this.progressDialog.createProgress(widget.body, nlsKeys.get("eng.partNumber.loading.mask.title"));
            XENCommandsAppContextProxy.getAppContextPromise(this).then(function (context) {

                if (!Array.isArray(that.options.context.getSelectedNodes()) ||
                    that.options.context.getSelectedNodes().length === 0) {
                    throw new Error('No Selected Items!');
                }

                that.transactionParameters = (that.options.context.getTransactionParameters) ? that.options.context.getTransactionParameters() : null;
                that.items = that.options.context.getSelectedNodes().map(function (item) {
                    return {
                        physicalId: item.getID(),
                        name: item.getLabel(),
                        sessionStoredEIN: (item.getSessionStoredEIN && item.getSessionStoredEIN()) ? item.getSessionStoredEIN() : undefined,
                        partNumber: item.options.grid['ds6wg:EnterpriseExtension.V_PartNumber']
                    };
                });
                that.items = that.items.reduce(function (result, item) {
                    var idx = result.filter((function (cp) {
                        return item.physicalId === cp.physicalId;
                    }))[0];
                    if (!UWA.is(idx)) {
                        result.push(item);
                    }
                    return result;
                }, []);
                that.sTenentID = (that.options.context.getTenentID) ? that.options.context.getTenentID() : "OnPremise";
                that.myBaseAppURL = (that.options.context.getMyBaseAppURL) ? that.options.context.getMyBaseAppURL() : null;
                that.securityContext = (that.options.context.getSC) ? that.options.context.getSC() : null;
                if (XENPlatform3DXSettings.isBuildSecurityContext() && XENPlatform3DXSettings.isCloud()) {
                    var _platform = {};
                    var strTenentId = that.sTenentID;
                    var sURL = that.myBaseAppURL;
                    _platform[strTenentId] = {
                        "3DSpace": sURL
                    }
                    XENPlatform3DXSettings._platforms = _platform;
                    XENPlatform3DXSettings.setDefaultSecurityContext(that.securityContext.replace("ctx : ", ""));
                    that._buildSetPartNumDialog();
                } else {
                    var needSC = (!that.getProvidedSC());
                    XENPlatform3DXSettings.bindCommandsToABackend(needSC /* need to retrieve SC */ ).then(function () {
                        that.isUserGranted().then(function () {
                            that._buildSetPartNumDialog();
                        }).catch(function (reason) {
                            console.log(reason);
                            xEngAlertManager.errorNotif({
                                title: nlsKeys.get("error.not.granted"),
                                subtitle: nlsKeys.get("error.contact.admin"),
                            });
                            that.progressDialog.close();
                        });
                    }).catch(function (error) {
                        console.error(error);
                        //notify the user
                        xEngAlertManager.unexpectedFailure(nlsKeys.get('failure.setPartNumber.cmd.launch'));
                        that.progressDialog.close();
                    })
                }
            }).catch(function (error) {
                console.error(error);
                xEngAlertManager.unexpectedFailure(nlsKeys.get('failure.setPartNumber.cmd.launch'));
                that.progressDialog.close();
            })
        },
        retrievePartNumber: function () {
            // console.log(1013);
            var that = this;
            var sessionStoredEINValues = {};
            var physicalIds = this.items.map(function (item) {
                sessionStoredEINValues[item.physicalId] = item.sessionStoredEIN;
                return item.physicalId;
            });
            this.retrievePartNumberAttr(physicalIds).then(function (data) {
                that._setPartNumberListView.destroy();
                var mappedReferencesData = data.references.map(function (current) {
                    // IE :(
                    var item = that.items.filter(function (item) {
                        if (item.physicalId === current.physicalid) {
                            return true;
                        }
                        return false;
                    })[0];

                    return {
                        id: item.physicalId,
                        name: item.name,
                        oldpartnumber: (sessionStoredEINValues && sessionStoredEINValues[item.physicalId]) ? sessionStoredEINValues[item.physicalId] : current.partNumber,
                        editable: (current[SetPartConstants.CONSTANT_STATUS] !== SetPartConstants.CONSTANT_COMPUTED) ? true : false,
                        newpartnumber: current[SetPartConstants.CONSTANT_COMPUTED_PARTNUMBER],
                        status: current[SetPartConstants.CONSTANT_STATUS],
                        [SetPartConstants.CONSTANT_DEFORMED]: current[SetPartConstants.CONSTANT_DEFORMED],
                        [SetPartConstants.CONSTANT_SUGGESTED_EIN]: current[SetPartConstants.CONSTANT_SUGGESTED_EIN] ? current[SetPartConstants.CONSTANT_SUGGESTED_EIN] : "",
                        [SetPartConstants.CONSTANT_KEY_ITEMNUMBER_GENERATOR]: data[SetPartConstants.CONSTANT_KEY_ITEMNUMBER_GENERATOR]
                    };
                });
                var einFormat = data[SetPartConstants.CONSTANT_BLOCK_EIN_CONFIGURED] == SetPartConstants.CONSTANT_TRUE ? SetPartConstants.CONSTANT_EIN_TYPE_NONE : data[SetPartConstants.CONSTANT_EIN_FORMAT];
                var manualInput = data[SetPartConstants.CONSTANT_BLOCK_EIN_CONFIGURED] == SetPartConstants.CONSTANT_TRUE ? SetPartConstants.CONSTANT_FALSE : data[SetPartConstants.CONSTANT_MANUAL_OR_FREE_INPUT];
                var collection = {
                    [SetPartConstants.CONSTANT_KEY_ITEMNUMBER_GENERATOR]: data[SetPartConstants.CONSTANT_KEY_ITEMNUMBER_GENERATOR],
                    [SetPartConstants.CONSTANT_KEY_ITEMNUMBER_UNIQUENESS]: data[SetPartConstants.CONSTANT_KEY_ITEMNUMBER_UNIQUENESS],
                    [SetPartConstants.CONSTANT_FORMULA_CONFIGURED]: data[SetPartConstants.CONSTANT_FORMULA_CONFIGURED],
                    [SetPartConstants.CONSTANT_CONFIGURED_FORMULA_EXPRESSION]: data[SetPartConstants.CONSTANT_CONFIGURED_FORMULA_EXPRESSION],
                    [SetPartConstants.CONSTANT_MANUAL_OR_FREE_INPUT]: manualInput,
                    [SetPartConstants.CONSTANT_EIN_FORMAT]: einFormat,
                    [SetPartConstants.CONSTANT_PHYSICAL_PRODUCT_ATTRIBUTES]: data[SetPartConstants.CONSTANT_PHYSICAL_PRODUCT_ATTRIBUTES],
                    [SetPartConstants.CONSTANT_BLOCK_EIN_CONFIGURED]: data[SetPartConstants.CONSTANT_BLOCK_EIN_CONFIGURED],
                    [SetPartConstants.CONSTANT_IS_V6_ENVIRONMENT]: XENPlatform3DXSettings.isCatiaV6Environment(),
                    references: mappedReferencesData
                }
                console.log(1099);
                console.log(collection);

                that.showDialog(collection);

                XENWebInWinHelper.commandViewReady();
            }).catch(function (errors) {
                console.warn(errors);
                var errorReason = (errors && errors.error && errors.error.message) ? errors.error.message : (errors.message ? errors.message : errors);
                errorReason = (errors && errors.response && errors.response.message) ? errors.response.message : errorReason;

                if (errorReason) {
                    xEngAlertManager.errorAlert(errorReason);
                } else {
                    xEngAlertManager.unexpectedFailure(nlsKeys.get('failure.setPartNumber.cmd.launch'));
                }

                if (that.modal && that.modal.isNotDestroyed())
                    Mask.unmask(that.modal.getBody());

                that.destroyView(true);
                that.end();
            }).finally(function () {
                that.progressDialog.close();
            });
        },

        getTargetedNode: function () {
            console.log(1014);
            var nodes = this.options.context.getSelectedNodes();
            return nodes.length > 0 ? nodes[0] : null;
        },
        retrievePartNumberAttr: function (physicalIds) {
            console.log(1015);
            var myRetrievePartNumCommand = XENPlatform3DXSettings.getCommand('mcs_retrievePartNumber');
            var parameters = this.transactionParameters;
            var payload = {
                references: physicalIds.map(function (physicalid) {
                    return {
                        physicalid: physicalid
                    };
                })
            };
            if (parameters) {
                payload["winTransactionParameters"] = parameters;
            }

            return PromiseUtils.wrappedWithCancellablePromise(function (resolve, reject) {
                xAppWSCalls.perform(myRetrievePartNumCommand, JSON.stringify(payload)).then(function (res) {
                    //app.core.settingManager.setApplicationMode('authoring');

                    // Sorting the result in the order of payload - start
                    var payloadArray = payload.references;

                    if (payloadArray.length > 1) {
                        var resultJson = {};
                        var resArray = res.references;
                        var phyId;
                        for (var i = 0; i < resArray.length; i++)
                            resultJson[resArray[i].physicalid] = resArray[i];

                        var sortedResArray = [];
                        for (var i = 0; i < payloadArray.length; i++)
                            sortedResArray.push(resultJson[payloadArray[i].physicalid]);
                        res.references = sortedResArray;
                    }
                    // Sorting the result in the order of payload - end
                    return resolve(res);
                }).catch(function (errors) {
                    reject(errors);
                });
            });
        },
        updatePartNumberAttr: function (collection) {
            console.log(1016);
            var myUpdatePartNumCommand = XENPlatform3DXSettings.getCommand('mcs_setPartNumber');
            var parameters = this.transactionParameters;
            var payload = {};

            payload = this.buildUpdateEINPayload(collection, parameters);

            return PromiseUtils.wrappedWithCancellablePromise(function (resolve, reject) {
                xAppWSCalls.perform(myUpdatePartNumCommand, JSON.stringify(payload)).then(function (res) {
                    //app.core.settingManager.setApplicationMode('authoring');
                    return resolve(res);
                }).catch(function (errors) {
                    reject(errors);
                });
            });
        },
        updateModalTitleInfo: function (selectedValidObjects, allObjects) {
            console.log(1017);
            var that = this;
            var selectionDetails = "";
            if (allObjects == 1 && selectedValidObjects == 1) {
                selectionDetails = nlsKeys.get("eng.partNumber.selected.object.count").replace("$1", selectedValidObjects);
            } else if (selectedValidObjects > 0) {
                var selectionDetails = (selectedValidObjects == 1) ? nlsKeys.get("eng.partNumber.selected.object.count").replace("$1", selectedValidObjects) :
                    nlsKeys.get("eng.partNumber.selected.multiple.objects.count").replace("$1", selectedValidObjects);
            }
            that.modal.modal.setTitle(nlsKeys.get("edit_part_number_title") + selectionDetails);
        },
        showDialog: function (collection) {
            console.log(1018);
            var that = this;
            var setPartCont = that._setPartNumberListView.setCollection(collection).render();

            if (that._setPartNumberListView.collection && that._setPartNumberListView.collection.references && that._setPartNumberListView.invalidObjectsCount != that._setPartNumberListView.collection.references.length) {
                that.buildModal();

                // var nowNode = document.querySelector(".modal-body");
                // setPartCont.inject(body)
                // var divTest = document.createElement('div');
                // h1.innerHTML = "123";
                
                var divTest = widget.createElement('div');
                divTest.setHTML(HTMLsetPartNumberListView);
                divTest.inject(that.modal.getBody());
                //todo
                that.modal.modal.setNewSize({
                    width: 1000,
                    height: 500
                });
                that.modal.modal.centerIt();
                that.modal.show();
                that.updateModalTitleInfo(that._setPartNumberListView.successCount, that._setPartNumberListView.collection[SetPartConstants.CONSTANT_KEY_REFERENCES].length);
            }
        },
        enableSetPartCmdButtons: function () {
            console.log(1019);
            var that = this;
            that.modal.modal.getFooter().getElements('.btn').forEach(function (element) {
                element.disabled = false;
            })
        },
        disableSetPartCmdButtons: function () {
            console.log(1020);
            var that = this;
            that.modal.modal.getFooter().getElements('.btn').forEach(function (element) {
                element.disabled = true;
            })
        },
        buildUpdateEINPayload: function (collection, parameters) {
            console.log(1021);
            
            var payload = {};

            var parameters = this.transactionParameters;
            if (parameters) {
                payload["winTransactionParameters"] = parameters;
            }

            if (collection[SetPartConstants.CONSTANT_KEY_REFERENCES].length > 0) {
                payload[SetPartConstants.CONSTANT_KEY_REFERENCES] = collection[SetPartConstants.CONSTANT_KEY_REFERENCES];
            }

            if (Object.keys(collection[SetPartConstants.CONSTANT_USER_MAPPED_PN]).length > 0) {
                payload[SetPartConstants.CONSTANT_USER_MAPPED_PN] = collection[SetPartConstants.CONSTANT_USER_MAPPED_PN];
            }

            payload[SetPartConstants.CONSTANT_KEY_ALL_REV_SKIP] = collection[SetPartConstants.CONSTANT_KEY_ALL_REV_SKIP];
            return payload;
        }
    });
    return SetPartNumber;
});