<template>
  <v-container fluid class="body-color">
    <!-- ****** STUDENTS TABLE ****** -->
    <v-toolbar color="transparent" flat>
      <v-spacer></v-spacer>
      <v-flex xs12 sm4 md2>
        <v-select
          small
          :items="addclass"
          label="Select Class"
          v-model="getReport.classId"
          item-text="classNum"
          item-value="_id"
          name="Select Class"
          @change="getCourses(getReport.classId)"
          class="mr-2"
          required
        ></v-select>
      </v-flex>
      <v-flex xs12 sm4 md2>
        <v-select
          :items="courseData"
          label="Select Course"
          v-model="getReport.courseId"
          item-text="courseName"
          item-value="_id"
          required
          class="ml-2"
          @change="getStudentTable(getReport.courseId)"
        ></v-select>
      </v-flex>
      <v-card-title class="body-1" v-show="show">
        <v-btn icon large flat @click="displaySearch">
          <v-avatar size="27">
            <img src="/static/icon/search.png" alt="icon" />
          </v-avatar>
        </v-btn>
      </v-card-title>
      <v-flex xs8 sm8 md3 lg2 v-if="showSearch">
        <v-layout>
          <v-text-field
            autofocus
            v-model="search"
            label="Search"
            prepend-inner-icon="search"
            color="primary"
          ></v-text-field>
          <v-icon @click="closeSearch" color="error">close</v-icon>
        </v-layout>
      </v-flex>
    </v-toolbar>
    <v-data-table
      :headers="headers"
      :items="studentsData"
      :pagination.sync="pagination"
      :search="search"
      select-all
      v-model="selected"
      item-key="_id"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr" :active="props.selected" @click="props.selected = !props.selected">
          <td class="text-xs-center td td-row">
            <v-checkbox
              v-model="props.item.enroll"
              @change="selectParticularStudent(props.item)"
              primary
              hide-details
            ></v-checkbox>
          </td>
          <td class="text-xs-center td td-row">
            <v-avatar size="40">
              <img :src="props.item.profilePicUrl" v-if="props.item.profilePicUrl" />
              <img src="/static/icon/user.png" v-else-if="!props.item.profilePicUrl" />
            </v-avatar>
          </td>
          <td class="text-xs-center td td-row">{{ props.item.name}}</td>
          <td class="text-xs-center td td-row">{{ props.item.fatherCellNo}}</td>
          <td class="text-xs-center td td-row">{{ props.item.email }}</td>
        </tr>
      </template>
      <template slot="headers" slot-scope="props">
        <tr>
          <th>
            <v-checkbox
              :input-value="props.all"
              :indeterminate="props.indeterminate"
              primary
              hide-details
              @click.native="toggleAll"
            ></v-checkbox>
          </th>
          <th
            v-for="header in props.headers"
            :key="header.text"
            :class="['column sortable', pagination.descending ? 'desc' : 'asc', header.value === pagination.sortBy ? 'active' : '']"
            @click="changeSort(header.value)"
          >
            <v-icon small>arrow_upward</v-icon>
            {{ header.text }}
          </th>
        </tr>
      </template>
      <v-alert
        slot="no-results"
        :value="true"
        color="error"
        icon="warning"
      >Your search for "{{ search }}" found no results.</v-alert>
    </v-data-table>
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      color="success"
    >{{ text }}</v-snackbar>
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>
  </v-container>
</template>

<script>
import http from "@/Services/http.js";
import moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    y: "top",
    x: "right",
    mode: "",
    timeout: 3000,
    text: "",
    show: true,
    showSearch: false,
    showLoader: false,
    loading: false,
    date: null,
    search: "",
    addclass: [],
    pagination: {
      rowsPerPage: 10,
    },
    headers: [
      {
        text: "Profile Pic",
        value: "profilprofilePicUrlePicUrl",
        sortable: false,
        align: "center",
      },
      { text: "Name", value: "name", sortable: false, align: "center" },
      {
        text: "Mobile No",
        value: "fatherCellNo",
        sortable: false,
        align: "center",
      },
      { text: "Email", value: "email", sortable: false, align: "center" },
      // { text: "Action", value: "", sortable: false, align: "center" }
    ],
    token: "",
    selectStudents: {
      select: "",
      selectSection: "",
    },

    role: "",
    schoolRole: "",
    menu: false,
    valid: true,

    getReport: {},
    studentsData: [],
    courseData: [],
    addSection: [],
    selected: [],
  }),
  methods: {
    save(date) {
      this.$refs.menu.save(date);
    },
    getAllClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.addclass = response.data.data;
        })
        .catch((error) => {
          // console.log("err====>", err);
          // this.$router.replace({ path: "/" });
        });
    },
    getCourses(classId) {
      this.showLoader = true;
      this.studentsData = [];
      this.getReport.courseId = "";
      http()
        .get("/getCourseesList", {
          params: {
            classId: classId,
          },
        })
        .then((response) => {
          this.courseData = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          //   console.log("err====>", err);
          this.showLoader = false;
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    getStudents(message) {
      this.showLoader = true;
      http()
        .get("/getStudentsList", {
          params: {
            classId: this.getReport.classId,
          },
        })
        .then((response) => {
          this.studentsData = response.data.data.filter((item) => item.status);
          //this.studentsData = response.data.data;
          this.showLoader = false;
          // this.addStudentAttendenceDialog = false;
          var attendence = "";
          for (let i = 0; i < this.studentsData.length; i++) {
            this.studentsData[i].attendence = true;
          }
          this.getParticularCourse(message);
        })
        .catch((error) => {
          //   console.log("err====>", error);
          this.showLoader = false;
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    getStudentTable(id) {
      // console.log("id", this.getReport.courseId);
      this.getStudents("noSnackbar");
    },
    update() {
      var studentsAttendence = [];
      for (var j = 0; j < this.studentsData.length; j++) {
        studentsAttendence.push({
          studentId: this.studentsData[j]._id,
          isPresent: this.studentsData[j].attendence,
        });
      }
      if (this.$refs.form.validate()) {
        let attendanceData = {
          sectionId: this.getReport.sectionId,
          date: this.date,
          students: studentsAttendence,
        };
        http()
          .put("/updateAttendance", attendanceData)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            this.addStudentAttendenceDialog = false;
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },
    toggleAll() {
      let withdraw = false;
      if (this.selected.length === this.studentsData.length) withdraw = true;

      if (withdraw) {
        var payload = {
          courseId: this.getReport.courseId,
          enrollStudents: [],
        };
        http()
          .put("/enrollStudents", payload)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            this.selected = [];
            for (let i = 0; i < this.studentsData.length; i++) {
              this.studentsData[i].enroll = false;
            }
            this.getParticularCourse();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      } else {
        let selectedStudentsArray = [];
        for (let item of this.studentsData) {
          if (item.enroll === false || !item.enroll) {
            selectedStudentsArray.push({ studentId: item._id });
          }
        }

        var payload = {
          courseId: this.getReport.courseId,
          enrollStudents: selectedStudentsArray,
        };
        http()
          .put("/enrollStudents", payload)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            for (let i = 0; i < this.studentsData.length; i++) {
              this.studentsData[i].enroll = true;
            }
            this.getParticularCourse();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },

    selectParticularStudent(selected) {
      let selectedStudentsArray = [];
      selectedStudentsArray.push({ studentId: selected._id });

      let isExists = false;
      for (let item of this.selected) {
        if (item._id === selected._id) {
          isExists = true;
          break;
        }
      }

      if (selected.enroll === true) {
        if (!isExists) this.selected.push(selected);
        var payload = {
          courseId: this.getReport.courseId,
          enrollStudents: selectedStudentsArray,
        };
        http()
          .put("/enrollStudents", payload)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            this.getParticularCourse("noSnackbar");
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
      if (
        selected.enroll == false &&
        selected.enroll != undefined &&
        selected.enroll != null
      ) {
        var payloadDeleteStudents = {
          courseId: this.getReport.courseId,
          enrollStudentsId: selected.enrollId,
        };
        http()
          .put("/deleteStudents", payloadDeleteStudents)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            this.getParticularCourse();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },
    getParticularCourse(message) {
      this.selected = [];
      var payload = {
        courseId: this.getReport.courseId,
      };
      http()
        .get("/getParticularCourse", {
          params: payload,
        })
        .then((response) => {
          for (let i = 0; i < response.data.data.enrollStudents.length; i++) {
            var studentId = {};
            studentId = response.data.data.enrollStudents[i];
            for (let j = 0; j < this.studentsData.length; j++) {
              if (studentId.studentId == this.studentsData[j]._id) {
                this.studentsData[j].enroll = true;
                this.studentsData[j].enrollId = studentId._id;
                this.selected.push(this.studentsData[j]);
                break;
              }
            }
          }
          if (message != "noSnackbar") {
            this.snackbar = true;
            this.text = response.data.message;
          }
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
        });
    },
    changeSort(column) {
      if (this.pagination.sortBy === column) {
        this.pagination.descending = !this.pagination.descending;
      } else {
        this.pagination.sortBy = column;
        this.pagination.descending = false;
      }
    },
    displaySearch() {
      this.show = false;
      this.showSearch = true;
    },
    closeSearch() {
      this.showSearch = false;
      this.show = true;
      this.search = "";
    },
  },
  mounted() {
    // this.getStudentList();
    this.token = this.$store.state.token;
    this.role = this.$store.state.role;
    this.getAllClass();
  },
};
</script>