{{ header }}
<header class="background-white bottom-margin-large">
  <div class="container-fluid">
    <div class="row no-space-xs">
      <div class="col-xs-12">
        <div class="content-box vertical-padding-large flex between-xs middle-xs">
          <div>
            <span class="text-x-large text-dark">{{ heading_title }}</span>
            <div class="adm-breadcrumb">
              {% for breadcrumb in breadcrumbs %}
              <i class="fas fa-angle-right text-x-small text-gray horizontal-padding-small"></i>
              <a class="text-x-small text-gray text-decoration-none"
                href="{{ breadcrumb.href }}">{{ breadcrumb.text }}</a>
              {% endfor %}
            </div>
          </div>
          <div class="flex flex-row middle-xs">
            <a href="{{ cancel }}" class="btn-default btn-medium btn-outline right-margin-small">
              <span>Cancelar</span>
            </a>
            <button class="btn-default btn-medium btn-primary js-submit-user-form">
              <span>Salvar</span>
            </button>
          </div>
          {% if error_warning %}
          <div class="warning full-width top-margin-medium">{{ error_warning }}</div>
          {% endif %}
          {% if success %}
          <div class="success full-width top-margin-medium">{{ success }}</div>
          {% endif %}
        </div>
      </div>
    </div>
  </div>
</header>
<div class="container-fluid">
  <div class="row center-xs">
    <div class="col-xs-12">
      <form action="{{ action }}" method="post" class="js-user-form">
        <label class="field field-medium bottom-margin-x-large">
          <span class="field-label"><span class="required">*</span>{{ entry_name }}</span>
          <input type="text" name="name" value="{{ name }}" class="field-entry" >
          {% if error_name %}
          <span class="error">{{ error_name }}</span>
          {% endif %}
        </label>
        <div class="row end-xs no-space-xs padding-medium bottom-padding-small">
          <div class="col-xs-3">
            <div class="content-box">
              <label class="checkbox checkbox-medium">
                <input type="checkbox" id="access-checkbox" class="power checkbox-entry" name="permission[accesscheckbox]"
                  value="{{ accesscheckbox ? 'true' : 'false' }}" {% if accesscheckbox %}checked{% endif %}>
                <span class="checkbox-text">Apenas Visualização</span>
              </label>
            </div>
          </div>
          <div class="col-xs-3">
            <div class="content-box">
              <label class="checkbox checkbox-medium">
                <input type="checkbox" id="modify-checkbox" class="power checkbox-entry" name="permission[modifycheckbox]"
                  value="{{ modifycheckbox ? '1' : '0' }}" {% if modifycheckbox %}checked{% endif %}>
                <span class="checkbox-text">Visualizar e Editar</span>
              </label>
            </div>
          </div>
        </div>
        {% for key_arquivo, arquivo in arquivos %}
        <div
          class="js-toggle-control background-white hover:shadow-large shadow-small horizontal-padding-medium vertical-padding-x-small top-margin-small cursor-pointer">
          <div class="row middle-xs no-space-xs">
            <div class="col-xs">
              <i class="fas fa-chevron-down text-small text-gray right-padding-x-small"></i>
              <span class="text-medium text-dark text-bold">
                {{ groupnames[key_arquivo] }}
                <input type="text" id="{{ key_arquivo }}" class="feedback hidden"
                  name="permission[category][checked][{{ key_arquivo }}]" readonly="readonly"
                  value="{{ category.checked.key_arquivo is defined ? category.checked.key_arquivo : 0 }}">
              </span>
            </div>
            <div class="col-xs-3">
              <label class="checkbox checkbox-medium">
                <input type="checkbox" id="access-{{ key_arquivo }}" class="access-checkbox power checkbox-entry"
                  name="permission[category][access][{{ key_arquivo }}]" value="{{ category.access.key_arquivo }}"
                  {% if category.access.key_arquivo is defined %}checked{% endif %}>
                <span class="checkbox-text vertical-middle"></span>
              </label>
            </div>
            <div class="col-xs-3">
              <label class="checkbox checkbox-medium">
                <input type="checkbox" id="modify-{{ key_arquivo }}" class="modify-checkbox power checkbox-entry"
                  name="permission[category][modify][{{ key_arquivo }}]" value="{{ category.modify.key_arquivo }}"
                  {% if category.modify.key_arquivo is defined %}checked{% endif %}>
                <span class="checkbox-text vertical-middle"></span>
              </label>
            </div>
          </div>
        </div>
        <div class="hidden bottom-margin-x-large">
          {% for group in arquivo %}
          <div class="row middle-xs no-space-xs top-padding-medium horizontal-padding-medium">
            {% if group.action.access %}
            <div class="col-xs-6 rel">
              <span class="text-medium text-dark">{{ group.name }}</span>
              {% if group.description %}
              <div class="full-max-width text-transform-inherit visible-inline" data-tooltip="{{ group.description }}">
                <i class="fas fa-question-circle text-medium text-primary"></i>
              </div>
              {% endif %}
            </div>
            <div class="col-xs-3">
              <label class="checkbox checkbox-small">
                <input type="checkbox" class="access-checkbox access-{{ key_arquivo }} checkbox-entry access-checkbox-item"
                  name="permission[access][]" value="{{ group.value }}" {% if group.value in access %}checked{% endif %} />
                <span class="checkbox-text vertical-middle"></span>
              </label>
            </div>
            {% if group.action.modify %}
            <div class="col-xs-3">
              <label class="checkbox checkbox-small">
                <input type="checkbox" class="modify-checkbox modify-{{ key_arquivo }} checkbox-entry"
                  name="permission[modify][]" value="{{ group.value }}" {% if group.value in modify %}checked{% endif %} />
                <span class="checkbox-text vertical-middle"></span>
              </label>
            </div>
            {% endif %}
            {% endif %}
          </div>
          {% endfor %}
        </div>
        {% endfor %}
      </form>
    </div>
  </div>

</div>

<script>
  var control = document.querySelectorAll('.js-toggle-control');
  for (let i = 0; i < control.length; i++) {
    control[i].onclick = toggleContent.bind(control[i]);
  }
   function toggleContent(){
     var content = this.nextElementSibling;
     content.classList.toggle('hidden');
   }

  $(document).ready(function () {

    //Marca os Controladores de acordo com a quantidade de checkbox controlados que estão marcados
    function set_controlers_state(element) {

      if (element.attr('id')) {
        var complemento = element.attr('id');
      } else {
        var complemento = element.attr('class').split(' ')[1].substr(7);
      }

      if ($('.modify-' + complemento).length == $('.modify-' + complemento + ':checked').length) {
        $('#modify-' + complemento).prop('checked', true).val(1).next().removeClass('partial');
      } else if ($('.modify-' + complemento).length == $('.modify-' + complemento + ':not(:checked)').length) {
        $('#modify-' + complemento).prop('checked', false).val(0).next().removeClass('partial');;
      } else {
        $('#modify-' + complemento).prop('checked', false).val(0).next().addClass('partial');
      }

      if ($('.access-' + complemento).length == $('.access-' + complemento + ':checked').length) {
        $('#access-' + complemento).prop('checked', true).val(1).next().removeClass('partial');;
      } else if ($('.access-' + complemento).length == $('.access-' + complemento + ':not(:checked)').length) {
        $('#access-' + complemento).prop('checked', false).val(0).next().removeClass('partial');;
      } else {
        $('#access-' + complemento).prop('checked', false).val(0).next().addClass('partial');
      }
    }

    // chama a função que marca os Controladores para cada categoria
    $('.feedback').each(function () {
      set_controlers_state($(this));
    });

    //Marca o Controlador "Todos" de acordo com a quantidade de checkbox controlados que estão marcados
    function set_checkbox_all_state() {
      if ($('.modify-checkbox').length == $('.modify-checkbox:checked').length) {
        $('#modify-checkbox').prop('checked', true).val(1).next().removeClass('partial');
      } else if ($('.modify-checkbox').length == $('.modify-checkbox:not(:checked)').length) {
        $('#modify-checkbox').prop('checked', false).val(0).next().removeClass('partial');
      } else {
        $('#modify-checkbox').prop('checked', false).val(0).next().addClass('partial');
      }
      if ($('.access-checkbox').length == $('.access-checkbox:checked').length) {
        $('#access-checkbox').prop('checked', true).val(1).next().removeClass('partial');
      } else if ($('.access-checkbox').length == $('.access-checkbox:not(:checked)').length) {
        $('#access-checkbox').prop('checked', false).val(0).next().removeClass('partial');
      } else {
        $('#access-checkbox').prop('checked', false).val(0).next().addClass('partial');
      }
    }
    set_checkbox_all_state();

    function set_category_feedback() {
      //define o feedback de cada categoria com o numero de checkbox marcados
      $('.feedback').each(function () {
        $(this).val($('[class$=' + $(this).attr('id') + ']:checked').length);
      });
    }
    set_category_feedback();

    function set_controler_values() {
      //define o valor dos controladores como 0 se unchecked, ou 1 se checked
      $('.power').each(function () {
        $(this).val($(this).prop('checked') ? 1 : 0);
      });
    }

    //marca os checkbox ao marcar o controlador
    $('.power').change(function () {
      $(this).val($(this).prop('checked') ? 1 : 0).next().removeClass('partial');

      var elements_controlled = '.' + $(this).attr('id');

      if ($(this).prop('checked') == true) {
        if ($(this).attr('id').substr(0, 6) == 'modify') {
          elements_controlled += ', .access' + $(this).attr('id').substr(6) + ', #access' + $(this).attr('id').substr(6);
        }
        $(elements_controlled).prop('checked', true).next().removeClass('partial');
      } else {
        if ($(this).attr('id').substr(0, 6) == 'access') {
          elements_controlled += ', .modify' + $(this).attr('id').substr(6) + ', #modify' + $(this).attr('id').substr(6);
        }
        $(elements_controlled).prop('checked', false).next().removeClass('partial');
      }

      // $('#'+$(this).attr('id').substr(7)).val($('.access'+$(this).attr('id').substr(6)+':checked').length + $('.modify'+$(this).attr('id').substr(6)+':checked').length);

      //define no feedback a quantidade de checkbox marcado em cada categoria
      if ($(this).attr('id').substr(7) == 'checkbox') {
        set_category_feedback();
      }
      set_checkbox_all_state();
      set_controler_values();
    });

    //demarca os controladores ao desmarcar algum checkbox
    $('[class^=access], [class^=modify]').change(function () {

      var controllers = $(this).attr('class').split(' ');
      var element_controller = '#' + controllers[0] + ', #' + controllers[1];
      if ($(this).prop('checked') == false) {
        $(element_controller).prop('checked', false);
      }

      if ($(this).hasClass('access-checkbox') && $(this).prop('checked') == false) {
        $(this).parent().parent().next().find('[class^=modify]').prop('checked', false);
        $('#' + $(this).attr('class').split(' ')[0]).prop('checked', false);

        //desmarca os controladores de "modificação"
        $('#modify' + controllers[0].substr(6)).prop('checked', false);
        $('#modify' + controllers[1].substr(6)).prop('checked', false);
      }
      if ($(this).hasClass('modify-checkbox') && $(this).prop('checked') == true) {
        $(this).parent().parent().prev().find('[class^=access').prop('checked', true);
      }

      if ($(this).hasClass('modify-checkbox') && $(this).prop('checked') == true) {
        if ($('.access' + controllers[0].substr(6)).length == $('.access' + controllers[0].substr(6) + ':checked').length) {
          $('#access' + controllers[0].substr(6)).prop('checked', true);
        }
      }

      $('#' + controllers[1].substr(7)).val($('.access' + controllers[1].substr(6) + ':checked').length + $('.modify' + controllers[1].substr(6) + ':checked').length);

      set_controlers_state($(this));
      set_checkbox_all_state();
      set_category_feedback();
      set_controler_values();
    });

    $('.js-submit-user-form').click(function (e) {
      e.preventDefault();
      $('.js-user-form').submit();
    });

    $('.js-user-form').on('submit', function (event) {
      event.preventDefault();

      var dataForm = new FormData($(this)[0]);

      var list = [];
      $(this).find('.access-checkbox-item').each(function (index, item) {
        list.push(item.value);
      });

      dataForm.append('list', JSON.stringify(list));

      var btnSave = $('.js-submit-user-form');
      btnSave.addClass('btn-loading');
      axiosApi({
        method: 'POST',
        url: $(this).attr('action'),
        data: dataForm,
      }).then(({data})=>{
        if (data.redirect){
          window.location.href = data.redirect;
        }
      }).catch(error=>console.log(error.response)).finally(()=> {
        setTimeout(()=>btnSave.removeClass('btn-loading'), 3000)
      });
    });
  });
</script>

{{ footer }}