<!DOCTYPE html>
<html lang="en"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{default}">
<head>
    <link th:href="@{/styles/company.css}" rel="stylesheet" />
</head>
<body>
<div layout:fragment="content">
    <h1>Название: <span th:text="${company.name}"></span></h1>
    <h2>Количество сотрудников: <span th:text="${#arrays.length(company.employees.toArray())}"></span></h2>
    <div sec:authorize="hasRole('ROLE_ADMIN')">
        <a class="btn btn-success button-fixed"
           data-bs-target="#hireModal" data-bs-toggle="modal">
            Нанять сотрудника
        </a>
    </div>
    <table class="table">
        <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">ID</th>
            <th scope="col">Фамилия</th>
            <th scope="col">Имя</th>
            <th scope="col">Номер телефона</th>
            <th scope="col">Должности</th>
            <th sec:authorize="hasRole('ROLE_ADMIN')" scope="col"></th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="employee, iterator: ${company.employees}">
            <th scope="row" th:text="${iterator.index} + 1"/>
            <td th:text="${employee.id}"/>
            <td th:text="${employee.surname}" />
            <td th:text="${employee.name}" />
            <td th:text="${employee.phoneNumber}" />
            <td th:text="${#strings.listJoin(employee.positions.![name],',')}"></td>
            <th sec:authorize="hasRole('ROLE_ADMIN')" style="width: 20%">
                <a class="btn btn-danger button-fixed button-sm" th:data-employee="${employee.id}"
                   data-bs-target="#dismissModal" data-bs-toggle="modal"
                   th:onclick="openModalDismiss(this.getAttribute('data-employee'))">Уволить</a>
                <a class="btn btn-info button-fixed button-sm" th:data-employee="${employee.id}"
                   data-bs-target="#managePositionModal" data-bs-toggle="modal"
                   th:onclick="openModalManagePosition(this.getAttribute('data-employee'))">Должности</a>
            </th>
        </tr>
        </tbody>
    </table>
    <!-- Modal -->
    <div class="modal" id="dismissModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">Увольнение</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="form-dismiss">
                        <div class="mb-3">
                            <label class="form-label" for="employeeSelect">Сотрудник</label>
                            <select class="form-select"  id="employeeSelect" name="employeeId" required>
                                <option th:each="employee, iterator: ${company.employees}" th:value="${employee.id}"
                                        th:text="${employee.surname} + ' ' + ${employee.name}">
                                </option>
                            </select>
                        </div>
                        <button class="btn btn-danger" type="submit">Уволить</button>
                        <a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
                            Назад
                        </a>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="hireModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="hireModalLabel">Найм</h5>
                    <button type="button" class="close" data-bs-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="form-hire">
                        <div class="mb-3">
                            <label class="form-label" for="employeeHireSelect">Сотрудник</label>
                            <select class="form-select" id="employeeHireSelect" name="employeeId" required>
                                <option selected disabled>Выберите сотрудника</option>
                                <option th:each="employee, iterator: ${freeEmployees}" th:value="${employee.id}"
                                        th:text="${employee.surname} + ' ' + ${employee.name}">
                                </option>
                            </select>
                        </div>
                        <button class="btn btn-info" type="submit">Нанять</button>
                        <a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
                            Назад
                        </a>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <div class="modal" id="managePositionModal">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="managePositionModalLabel">Назначение должности</h5>
                    <button type="button" class="close" data-bs-dismiss="modal">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form id="form-positions">
                        <div class="mb-3">
                            <label class="form-label"  for="employeePosSelect">Сотрудник</label>
                            <select class="form-select"  id="employeePosSelect" name="employeeId" required>
                                <option value="0" selected disabled>Выберите сотрудника</option>
                                <option th:each="employee, iterator: ${company.employees}" th:value="${employee.id}"
                                        th:text="${employee.surname} + ' ' + ${employee.name}">
                                </option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label class="form-label" for="employeeSelect">Должности</label>
                            <div class="prokrutka">
                                <div style="200px;" th:each="position, iterator: ${positions}">
                                    <input type="checkbox" th:value="${position.id}"
                                           th:text="${position.name}">
                                </div>
                            </div>
                        </div>
                        <button class="btn btn-info" type="submit">Назначить</button>
                        <a class="btn btn-secondary button-fixed" data-bs-dismiss="modal">
                            Назад
                        </a>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<th:block layout:fragment="scripts">
    <script th:inline="javascript">
        $(document).on('submit', '#form-dismiss', function (e) {
              e.preventDefault();
              var company = [[${company}]];
              var url = 'http://localhost:8080/api/company/id/dismiss?employeeId=empId';
              url = url.replace("id", company.id).replace("empId", $("#employeeSelect").val())
              alert(url);
              $.ajax({
                url: url,
                method: 'PUT',
                contentType: "application/json;"
              })
              .done(function() {
                location.reload();
              })
              .fail((err) => {
                alert(err);
              });
            });
         $(document).on('submit', '#form-hire', function (e) {
              e.preventDefault();
              var company = [[${company}]];
              var url = 'http://localhost:8080/api/company/id/hire?employeeId=empId';
              url = url.replace("id", company.id).replace("empId", $("#employeeHireSelect").val())
              alert(url);
              $.ajax({
                url: url,
                method: 'PUT',
                contentType: "application/json;"
              })
              .done(function() {
                location.reload();
              })
              .fail((err) => {
                alert(err);
              });
            });
          $(document).on('submit', '#form-positions', function (e) {
              e.preventDefault();
              var company = [[${company}]];
              var employeeId = $("#employeePosSelect").val();
              var employee = company.employees.find(x => x.id + '' === employeeId);
              var positions = employee.positions.map(x => x.id + '');
              var urlAdd = 'http://localhost:8080/api/employee/id/addPos?position=posId';
              var urlDel = 'http://localhost:8080/api/employee/id/delPos?position=posId';
              $('input[type=checkbox]').each(function(){
                  if(positions.indexOf($(this).val()) !== -1 && $(this).is(":checked") === false){
                    $.ajax({
                        url: urlDel.replace("id", employee.id).replace("posId", $(this).val()),
                        method: 'PUT',
                        contentType: "application/json;"
                      })
                      .done(function() {
                            location.reload();
                      })
                      .fail((err) => {
                        alert(err);
                      });

                  } else if (positions.indexOf($(this).val()) == -1 && $(this).is(":checked")){
                    $.ajax({
                        url: urlAdd.replace("id", employee.id).replace("posId", $(this).val()),
                        method: 'PUT',
                        contentType: "application/json;"
                      })
                      .done(function() {
                            location.reload();
                      })
                      .fail((err) => {
                        alert(err);
                      });
                  }
              });
            });

           $(document).ready(function(){
              $('#employeePosSelect').change(function(){
                var selectedEmployee = $(this).val();
                var company = [[${company}]];
                var employee = company.employees.find(x => x.id + '' === selectedEmployee);
                var positions = employee.positions.map(x => x.id + '');
                $('input[type=checkbox]').prop('checked', false);
                $('input[type=checkbox]').each(function(){
                  if(positions.indexOf($(this).val()) !== -1){
                    $(this).prop('checked', true);
                  }
                });
              });
            });

           function openModalDismiss(id) {
                $('#employeeSelect').val(id);
                $( "#employeeSelect" ).prop( "disabled", true );
            }
           function openModalManagePosition(id) {
                $('#employeePosSelect').val(id);
                $( "#employeePosSelect" ).prop( "disabled", true );
                var company = [[${company}]];
                var employee = company.employees.find(x => x.id + '' === id);
                var positions = employee.positions.map(x => x.id + '');
                $('input[type=checkbox]').prop('checked', false);
                $('input[type=checkbox]').each(function(){
                  if(positions.indexOf($(this).val()) !== -1){
                    $(this).prop('checked', true);
                  }
                });
            }
    </script>
</th:block>
</html>