<!DOCTYPE html>
<html lang="en" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{default}">
<head>
</head>
<body>
<div layout:fragment="content">
  <h1>Отчет</h1>
  <select  id="positionSelect" name="positionId" class="form-select" required>
    <option selected disabled>Выберите должность</option>
    <option th:each="position, iterator: ${positions}" th:value="${position.id}" th:text="${position.name}">
    </option>
  </select>
  <div class="table-responsive">
    <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 scope="col">Компания</th>
      </tr>
      </thead>
      <tbody id="employees">
      </tbody>
    </table>
  </div>
</div>
</body>
<th:block layout:fragment="scripts">
  <script th:inline="javascript">
        $(document).on('change', '#positionSelect', function (e) {
              var url = 'http://localhost:8080/api/employee/position?pos=id';
              $("#employees > tr").remove();
              $.ajax({
                url: url.replace("id", $("#positionSelect").val()),
                method: 'GET'
              }).then(function (data) {
                $.each(data, function (index, value) {
                    const row = $("<tr>");
                    const number = $("<th>")
                        .attr("scope", "row")
                        .text(index + 1);
                    const id = $("<td>").text(value.id);
                    const surname = $("<td>").text(value.surname);
                    const name = $("<td>").text(value.name);
                    const positions = $("<td>").text(value.positions.map(x => x.name).join(", "));
                    const phoneNumber = $("<td>").text(value.phoneNumber);

                    const company = $("<td>").html(`<a href="/company/one/${value.company.id}">${value.company.name}</a>`);
                    row.append(number);
                    row.append(id);
                    row.append(surname);
                    row.append(name);
                    row.append(positions);
                    row.append(phoneNumber);
                    row.append(company);
                    $("#employees").append(row);
                });
            });
            });
    </script>
</th:block>
</html>