window.switchModal = function()
{
    const system = $('[name=system]').val();
    loadModal($.createLink('publishtemplate', 'create', 'type=' + system));
};
window.getEnvBySystem = function (envId = 0)
{
    toggleLoading('#publishtemplateCreateForm', true);
    const $picker = $('[name=envID]').zui('picker');
    $picker.$.clear();
    const system = $('[name=system]').val();
    $.getJSON($.createLink('env', 'ajaxGetEnv', 'system=' + system), function (items)
    {
        $picker.render({items: items});
        if (typeof items !== 'undefined')
        {
            const matchedItem = items.find(item => item.value === envId);
            if (matchedItem) $picker.$.setValue(matchedItem.value);
        }
        toggleLoading('#publishtemplateCreateForm', false);
    });
};

window.getHostBySystem = function (hosts = [])
{
    toggleLoading('#publishtemplateCreateForm', true);
    const $picker = $('[name^=hosts]').zui('picker');
    $picker.$.clear();

    const system = $('[name=system]').val();
    $.getJSON($.createLink('host', 'ajaxGetHostList', 'system=' + system), function (items)
    {
        $picker.render({items: items});
        if (typeof items !== 'undefined') $picker.$.setValue(hosts);
        toggleLoading('#publishtemplateCreateForm', false);
    });
};
window.getSystemList = function(systemId = 0)
{
    toggleLoading('#publishtemplateCreateForm', true);
    const $picker = $('[name=systemID]').zui('picker');
    $picker.$.clear();

    const productID = $('[name=productID]').val();
    $.getJSON($.createLink('build', 'ajaxGetSystemList', 'productID=' + productID), function (items)
    {
        $picker.render({items: items});
        if (typeof items !== 'undefined')
        {
            const matchedItem = items.find(item => item.value === systemId);
            if (matchedItem) $picker.$.setValue(matchedItem.value);
        }
        toggleLoading('#publishtemplateCreateForm', false);
    });
};
window.getSystemApp = function ()
{
    toggleLoading('#publishtemplateCreateForm', true);
    const systemId = $('[name=systemID]').val();
    $.getJSON($.createLink('publishtemplate', 'ajaxGetSystemApp', 'systemId=' + systemId), function (resp)
    {
        if (typeof (resp) !== 'undefined')
        {
            $('[name=appKey]').val(resp.appKey);
            $('[name=productName]').val(resp.productName);
        }
        toggleLoading('#publishtemplateCreateForm', false);
    });
};

window.addItem = function(name)
{
    const container = $('#' + name + 'Box');
    const className = '.item-' + name;
    let counter     = container.find(className).length;
    const item      = container.find(className).first();
    const clone     = item.clone(true);
    clone.find('input[name="settings[' + name + 'Command][0][title]"]').attr('name', 'settings[' + name + 'Command][' + counter + '][title]').val('');
    clone.find('[name="settings[' + name + 'Command][0][data]"]').attr('name', 'settings[' + name + 'Command][' + (counter++) + '][data]').val('');
    container.append(clone);
};

window.removeItem = function(name)
{
    const container = $('#' + name + 'Box');
    const className = '.item-' + name;
    const items     = container.find(className);
    if (items.length > 1) items.last().remove();
};

window.changeStep = function (next, prev, templateID = 0)
{
    if ($('#changeStep span.text').text() === next)
    {
        const $form    = $('.modal').find('form');
        let formData   = $form.serialize();
        $form.find('input:disabled').each(function ()
        {
            formData += '&' + $(this).attr('name') + '=' + $(this).val();
        });

        let httpBuild = 'type=' + $('[name=system]').val() + '&step=1';
        if (templateID > 0) httpBuild = 'id=' + templateID + '&' + httpBuild;
        const formAction = $.createLink('publishtemplate', rawMethod, httpBuild);
        $.post(formAction, formData, function (response)
        {
            response = JSON.parse(response);
            if (response.result === 'success')
            {
                $('#changeStep span.text').text(prev);
                $('#templateStep-1').addClass('hidden');
                $('#templateStep-2').removeClass('hidden');
                $('#save-button').removeClass('hidden');
            }
            else
            {
                for (let field in response.message)
                {
                    let fieldName = field.replace('[]', '');
                    let inputField = $form.find('#' + fieldName);
                    if (inputField.length)
                    {
                        let formGroup = inputField.closest('.form-group');
                        inputField.addClass('has-error');

                        formGroup.find('.form-tip').remove();

                        formGroup
                            .attr('name', `field-${fieldName}`)
                            .addClass('has-error')
                            .append(`<div class="form-tip" id="field-${fieldName}Tip">${response.message[field]}</div>`);
                    }
                }
            }
        }, 'json');
    }
    else
    {
        $('#changeStep span.text').text(next);
        $('#templateStep-1').removeClass('hidden');
        $('#templateStep-2').addClass('hidden');
        $('#save-button').addClass('hidden');
    }
};