// Copyright (c) Pickware GmbH. All rights reserved.
// This file is part of software that is released under a proprietary license.
// You must not copy, modify, distribute, make publicly available, or execute
// its contents or parts thereof without express permission by the copyright
// holder, unless otherwise permitted by law.

Ext.define('Shopware.apps.ViisonSetArticlesArticle.view.detail.Base', {

    override: 'Shopware.apps.Article.view.detail.Base',

    initComponent: function () {
        this.callParent(arguments);
    },

    createLeftElements: function () {
        var items = this.callParent(arguments);

        // Find position of isConfigurator element
        var addAfter = 'isConfigurator';
        var pos = -1;
        Ext.Array.each(items, function (item, index) {
            if (typeof item.name !== 'undefined' && item.name === addAfter) {
                pos = index;
            }
        });

        this.viisonSetarticleActiveCheckbox = Ext.create('Ext.form.field.Checkbox', {
            xtype: 'checkbox',
            itemId: 'setarticles-checkbox',
            labelWidth: 155,
            name: 'mainDetail[viisonSetarticleActive]',
            fieldLabel: ViisonCommonApp.getSnippet('window/checkbox', 'backend/viison_set_articles_article_checkbox/base'),
            inputValue: true,
            uncheckedValue: false,
            listeners: {
                scope: this,
                change: function (checkbox, newValue) {
                    this.viisonSetArticlesArticleOnCheckChange(newValue);
                },
            },
        });

        this.setarticlepanel = Ext.create('Ext.panel.Panel', {
            header: false,
            columnWidth: 0.5,
            defaults: {
                labelWidth: 155,
                anchor: '100%',
            },
            padding: '0 20 0 0',
            layout: 'anchor',
            border: false,
            items: [],
        });

        // Add at pos+1: slice array
        if (pos >= 0) {
            items.splice(pos + 1, 0, this.viisonSetarticleActiveCheckbox, this.setarticlepanel);
        }

        this.articleWindow = this.subApp.articleWindow;
        this.articleWindow.on('storesLoaded', this.viisonSetArticlesArticleOnStoresLoaded, this);

        return items;
    },

    /**
     * React to Checkbox-Change: Enable/Disable set articles tab and lock/unlocks Stockmanager fields
     *
     * @param newValue bool
     */
    viisonSetArticlesArticleOnCheckChange: function (newValue) {
        this.viisonEnableSetArticlesTab(newValue);
        this.viisonUpdateOtherCustomPluginCheckboxes(newValue);
    },

    /**
     * Enables/disables (grey out) set articles tab
     *
     * @param bool value
     */
    viisonEnableSetArticlesTab: function (value) {
        var setarticleTab = this.articleWindow.down('viison_set_articles_article-view-detail-tab');
        if (setarticleTab) {
            setarticleTab.ownerCt.setDisabled((this.article.get('id') === null || value === false));
        }
    },

    /**
     * Updates the 'pickwareStockManagementDisabled' (ViisonPickwareERP plugin) and 'viisonCoupon' (ViisonCoupon plugin)
     * fields according to the value of the 'viisonSetarticleActive' checkbox, if these fields are available. That is,
     * if the 'viisonSetarticleActive' checkbox is ticked, the 'pickwareStockManagementDisabled' checkbox is ticked as
     * well and set to readOnly and vice versa. The 'viisonCoupon' checkbox is set the readOnly, if the set article
     * checkbox is ticked. Also, while the the modified checkboxes are readOnly, a tooltip is added to them, explaining
     * why they cannot be edited.
     *
     * Remark: The checkboxes are set to readOnly instead of being disabled, because values of disabled fields are not
     *         submitted when saving the article, while readOnly values are.
     *
     * @param isSetArticle bool
     */
    viisonUpdateOtherCustomPluginCheckboxes: function (isSetArticle) {
        Ext.each(this.articleWindow.query('field'), function (field) {
            var qtip = '';
            // The name of this attribute was changed to "pickwareStockManagementDisabled" as part of Pickware 5
            var stockManagementDisabledFields = [
                'mainDetail[viisonNotRelevantForStockManager]',
                'mainDetail[pickwareStockManagementDisabled]',
            ];
            if ((stockManagementDisabledFields.indexOf(field.name) !== -1)) {
                field.setReadOnly(isSetArticle);
                field.setValue(isSetArticle);
                qtip = (isSetArticle) ? ViisonCommonApp.getSnippet('form/pickware_stock_management_disabled/read_only_hint', 'backend/viison_set_articles_article_checkbox/base') : '';
            } else if (field.name === 'mainDetail[viisonCoupon]') {
                field.setReadOnly(isSetArticle);
                qtip = (isSetArticle) ? ViisonCommonApp.getSnippet('form/viison_coupon/read_only_hint', 'backend/viison_set_articles_article_checkbox/base') : '';
            } else {
                return;
            }

            // Update the checkbox's tooltip
            field.getEl().set({
                'data-qtip': qtip,
            });
            Ext.QuickTips.init();
        });
    },

    /**
     * On StoresLoaded: check if Article is sub article, update View.
     *
     * @param article Article
     */
    viisonSetArticlesArticleOnStoresLoaded: function (article) {
        this.article = article;

        // Check if already sub article
        var id = article.get('id');
        Ext.Ajax.request({
            url: ViisonCommonApp.assembleBackendUrl('ViisonSetArticlesArticle/checkIfSubArticle', {
                articleid: id,
            }),
            method: 'GET',
            scope: this,
            success: function (response) {
                var json = Ext.JSON.decode(response.responseText, true);
                if (json.success) {
                    this.viisonSetArticlesArticleDisableCheckbox(json.data);
                }
                var value = this.viisonSetarticleActiveCheckbox.getValue();
                this.viisonEnableSetArticlesTab(value);
                // Remark: only update the other custom plugin checkboxes, if this article indeed is a set article to
                // not overwrite any values by mistake
                if (value) {
                    this.viisonUpdateOtherCustomPluginCheckboxes(value);
                }
            },
        });
    },

    /**
     * Disables "SetArticle-Active" Checkbox, displays hint "This Article is already part of..".
     * numbers is a String if it is a single ordernumber, or an array of multiple ordernumbers.
     * @param numbers
     */
    viisonSetArticlesArticleDisableCheckbox: function (numbers) {
        this.viisonSetarticleActiveCheckbox.disable();
        var maxOrdnumbers = 3;
        // First turn numbers into array, if it is a single string
        if (typeof numbers === 'string') {
            numbers = [numbers];
        }
        var numberString = numbers.splice(0, maxOrdnumbers).join(', ');
        if (numbers.length > 0) {
            numberString += ', ...';
        }

        this.setarticlepanel.add({
            xtype: 'label',
            padding: '0 25 10 0',
            border: false,
            style: {
                font: 'italic 11px Arial, Verdana, sans-serif',
                color: '#475c6a;',
            },
            text: ViisonCommonApp.getSnippet('window/disabledcheckboxlabel', 'backend/viison_set_articles_article_checkbox/base') + ' ' + numberString,
        });
    },

});
