<template>
  <v-container fluid class="body-color">
    <!-- *****  Exam Schedule TABLE****** -->
    <v-toolbar color="transparent" flat>
      <v-btn
        fab
        dark
        class="open-dialog-button hidden-xl-only hidden-md-only hidden-lg-only"
        small
        @click="addExamAttendenceDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addExamAttendenceDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Exam Attendence
      </v-btn>
      <v-spacer></v-spacer>
      <v-flex xs8 sm3 md2 class="mr-3">
        <v-select
          v-model="getAttendence.examId"
          label="Select Exam"
          :rules="examRules"
          :items="examList"
          item-text="examName"
          item-value="_id"
          required
        ></v-select>
      </v-flex>
      <v-flex xs8 sm3 md2 class="mr-3">
        <v-select
          v-model="getAttendence.classId"
          label="Select your class"
          type="text"
          :items="classList"
          item-text="classNum"
          item-value="_id"
          @change="getSections(getAttendence.classId)"
          required
        ></v-select>
      </v-flex>
      <v-flex xs8 sm3 md2 class="mr-3">
        <v-select
          v-model="getAttendence.sectionId"
          label="Select your section"
          type="text"
          :items="addSection"
          item-text="name"
          item-value="_id"
          @change="getClassSubject(getAttendence.classId)"
          required
        ></v-select>
      </v-flex>
      <v-flex xs8 sm3 md2 class="mr-3">
        <v-select
          v-model="getAttendence.subjectId"
          label="Select Subject"
          :rules="subjectRules"
          :items="subjectList.subjects"
          item-text="subjectName"
          item-value="_id"
          @change="getExamAttendenceList()"
          required
        ></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
      v-if="showData"
      :headers="headers"
      :items="examData.students"
      :pagination.sync="pagination"
      :search="search"
    >
      <template slot="items" slot-scope="props">
        <tr class="tr">
          <td class="td td-row">{{ props.index + 1}}</td>
          <td class="text-xs-center td td-row">
            <v-avatar size="40">
              <img
                :src="props.item.studentId.profilePicUrl"
                v-if="props.item.studentId.profilePicUrl"
              />
              <img src="/static/icon/user.png" v-else-if="!props.item.studentId.profilePicUrl" />
            </v-avatar>
          </td>
          <td class="td td-row text-xs-center">{{ props.item.studentId.name}}</td>
          <td class="td td-row text-xs-center">{{ props.item.studentId.rollNo}}</td>
          <td class="td td-row text-xs-center">{{ props.item.studentId.email }}</td>
          <td class="td td-row text-xs-center">
            <!-- <v-radio-group v-model="isPresent" row>
              <v-radio :value="props.item.isPresent"></v-radio>
            </v-radio-group>-->
            <v-checkbox
              v-model="props.item.isPresent"
              @click="markStudentAttendence(props.item)"
              primary
              hide-details
            ></v-checkbox>
          </td>
        </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>

    <!-- ****** ADD  Student Attendence ****** -->
    <v-dialog v-model="changeStudentAttendenceDialog" max-width="500px" persistent>
      <v-card flat>
        <v-layout class="pa-3 card-style white--text">
          <v-flex xs12>
            <label class="title text-xs-center">Change Student's Attendence</label>
            <v-icon
              size="24"
              class="right white--text"
              @click="changeStudentAttendenceDialog = false"
            >cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-container fluid>
          <v-flex xs12>
            <h3>Are you sure you want to change the attendence</h3>
          </v-flex>
          <v-spacer></v-spacer>

          <v-flex xs12>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn
                @click.native="closeStudentAttendenceDialog"
                round
                dark
                class="clear-button"
              >cancel</v-btn>
              <v-btn
                @click="selectParticularStudent"
                round
                dark
                :loading="loading"
                class="add-button"
              >Yes</v-btn>
            </v-card-actions>
          </v-flex>
        </v-container>
      </v-card>
    </v-dialog>

    <!-- ****** ADD  Exam Attendence ****** -->
    <v-dialog v-model="addExamAttendenceDialog" max-width="800px" v-if="addExamAttendenceDialog" persistent>
      <v-card flat>
        <v-layout class="pa-3 card-style white--text">
          <v-flex xs12>
            <label class="title text-xs-center">Add Exam Attendence</label>
            <v-icon size="24" class="right white--text" @click="closeAttendenceModel">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-form ref="form" v-model="valid" lazy-validation class="text-xs-center">
          <v-container fluid>
            <v-flex xs12>
              <v-layout>
                <v-flex xs5 class="pt-4 subheading">
                  <label class="right">Exam Name:</label>
                </v-flex>
                <v-flex xs7 sm7 md6 class="ml-3">
                  <v-select
                    label="Select Exam"
                    :rules="examRules"
                    :items="examList"
                    v-model="addAttendence.examId"
                    item-text="examName"
                    item-value="_id"
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs5 class="pt-4 subheading">
                  <label class="right">Class:</label>
                </v-flex>
                <v-flex xs7 sm7 md6 class="ml-3">
                  <v-select
                    v-model="addAttendence.classId"
                    label="Select Class"
                    type="text"
                    :items="classList"
                    item-text="classNum"
                    item-value="_id"
                    :rules="classRules"
                    @change="getSections(addAttendence.classId)"
                    required
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs5 class="pt-4 subheading">
                  <label class="right">Section:</label>
                </v-flex>
                <v-flex xs7 sm7 md6 class="ml-3">
                  <v-select
                    :items="addSection"
                    label="Select Section"
                    v-model="addAttendence.sectionId"
                    item-text="name"
                    item-value="_id"
                    name="Select Section"
                    :rules="sectionRules"
                    @change="getClassSubject(addAttendence.classId)"
                    required
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-flex xs12>
              <v-layout>
                <v-flex xs5 class="pt-4 subheading">
                  <label class="right">Subject Name:</label>
                </v-flex>
                <v-flex xs7 sm7 md6 class="ml-3">
                  <v-select
                    :items="subjectList.subjects"
                    label="Select Subject"
                    item-text="subjectName"
                    v-model="addAttendence.subjectId"
                    item-value="_id"
                    name="Select Subject"
                    :rules="subjectRules"
                    required
                  ></v-select>
                </v-flex>
              </v-layout>
            </v-flex>
            <v-layout>
              <v-flex xs12>
                <v-card-actions>
                  <v-spacer class="hidden-xs-only"></v-spacer>
                  <v-btn
                    round
                    dark
                    @click="showTable"
                    :loading="loading"
                    class="add-button"
                  >Attendence</v-btn>
                </v-card-actions>
              </v-flex>
            </v-layout>
          </v-container>
        </v-form>
        <v-flex xs12 v-show="attendeceTable" class>
          <v-data-table
            :headers="studentheader"
            :items="studentsData"
            :pagination.sync="pagination"
            :search="search"
            select-all
            v-model="selected"
            item-key="_id"
          >
            <template slot="items" slot-scope="props">
              <tr class="tr">
                <!-- <td class="td td-row">{{ props.index + 1}}</td> -->
                <td class="td td-row">
                  <v-checkbox
                    v-model="props.item.attendence"
                    @change="markParticularStudentAttendence(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="td td-row text-xs-center">{{ props.item.name}}</td>
                <td class="td td-row text-xs-center">{{ props.item.rollNo}}</td>
                <td class="td td-row text-xs-center">{{ props.item.email }}</td>
                <!-- <td class="td td-row text-xs-center">
                  <v-radio-group v-model="props.item.attendence" :mandatory="false" row>
                    <v-radio
                      v-for="attendences in attendenceType"
                      :key="attendences.value"
                      :label="`${attendences.label}`"
                      :value="attendences.value"
                    ></v-radio>
                  </v-radio-group>
                </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="selectAll"
                  ></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-flex xs12 sm12>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn @click="submit()" round dark :loading="loading" class="add-button">Submit</v-btn>
            </v-card-actions>
          </v-flex>
        </v-flex>
      </v-card>
    </v-dialog>
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="color"
    >{{ 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 Util from "@/util";
import moment from "moment";

export default {
  data: () => ({
    snackbar: false,
    editDate: false,
    menu1: false,
    menuB: false,
    menu2: false,
    menuEdit: false,
    timeToEdit: false,
    show: true,
    showSearch: false,
    addExamAttendenceDialog: false,
    color: "",
    y: "top",
    x: "right",
    mode: "",
    timeout: 10000,
    text: "",
    loading: false,
    search: "",
    showLoader: false,
    valid: true,
    role: "",
    pagination: {
      rowsPerPage: 10,
    },
    attendeceTable: false,
    isPresent: true,

    examRules: [(v) => !!v || "Exam Name is required"],
    classRules: [(v) => !!v || "Class Name is required"],
    sectionRules: [(v) => !!v || "section is required"],
    subjectRules: [(v) => !!v || "Subject is required"],
    timeInRules: [(v) => !!v || "Time In is required"],
    timeOutRules: [(v) => !!v || "time Out s is required"],
    roomRules: [(v) => !!v || "Room is required"],
    examScheduleDateRules: [(v) => !!v || "Date is required"],
    studentsData: [],
    examData: [],
    students: [],

    headers: [
      {
        align: "",
        text: "No",
        sortable: false,
        value: "No",
      },
      {
        text: "Profile Pic",
        value: "profilePicUrl",
        sortable: false,
        align: "center",
      },
      {
        text: "Name",
        value: "name",
        sortable: false,
        align: "center",
      },
      {
        text: "Roll No",
        value: "rollNo",
        sortable: false,
        align: "center",
      },
      {
        text: "Email",
        value: "email",
        sortable: false,
        align: "center",
      },
      {
        text: "Action",
        value: "isPresent",
        sortable: false,
        align: "center",
      },
    ],
    studentheader: [
      {
        text: "Profile Pic",
        value: "profilePicUrl",
        sortable: false,
        align: "center",
      },
      {
        text: "Name",
        value: "name",
        sortable: false,
        align: "center",
      },
      {
        text: "Roll No",
        value: "rollNo",
        sortable: false,
        align: "center",
      },
      {
        text: "Email",
        value: "email",
        sortable: false,
        align: "center",
      },
    ],
    attendenceType: [
      {
        label: "",
        value: true,
      },
    ],
    classList: [],
    addSection: [],
    examList: [],
    subjectList: [],
    subjects: [],
    addAttendence: {},
    getAttendence: {},
    editedItem: {
      sectionId: {
        name: "",
      },
    },
    getScheduleData: {},
    ScheduleData: [],
    token: "",
    showData: false,
    selected: [],
    changeStudentAttendenceDialog: false,
    closeStudentAttendenceDialog() {
      this.changeStudentAttendenceDialog = false;
    },
    selectedStudent: {},
    presentStudent: [],
    absentStudent: [],
  }),
  watch: {
    addExamAttendenceDialog: function (val) {
      if (!val) {
        this.studentsData = [];
        this.selected = [];
        this.attendeceTable = false;
        this.valid = false;
        this.addAttendence = [];
      }
    },
  },
  methods: {
    pickFile() {
      this.$refs.image.click();
    },
    markStudentAttendence(item) {
      this.selectedStudent = {
        id: item.studentId._id,
        isPresent: !item.isPresent,
      };
      this.changeStudentAttendenceDialog = true;
    },
    getSchedulesList() {
      this.showLoader = true;
      http()
        .get("/getSchedulesList", {
          params: { classId: this.getScheduleData.classId },
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.ScheduleData = response.data.data;
          this.showLoader = false;
        })
        .catch((error) => {
          // console.log("err====>", err);
          this.showLoader = false;
          this.loadingSearch = false;
          this.snackbar = true;
          this.text = error.response.data.message;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    close() {
      this.dialog = false;
    },
    closeAttendenceModel() {
      this.addExamAttendenceDialog = false;
      this.studentsData = [];
      this.selected = [];
      this.attendeceTable = false;
      this.valid = false;
      this.addAttendence = [];
    },
    submit() {
      var examAttendence = {
        examId: this.addAttendence.examId,
        classId: this.addAttendence.classId,
        sectionId: this.addAttendence.sectionId,
        subjectId: this.addAttendence.subjectId,
        students: [],
      };
      for (var j = 0; j < this.presentStudent.length; j++) {
        examAttendence.students.push({
          studentId: this.presentStudent[j],
          isPresent: true,
        });
      }
      for (var j = 0; j < this.absentStudent.length; j++) {
        examAttendence.students.push({
          studentId: this.absentStudent[j],
          isPresent: false,
        });
      }
      if (this.$refs.form.validate()) {
        http()
          .post("/createExamAttendance", examAttendence)
          .then((response) => {
            this.snackbar = true;
            this.color = "success";
            this.text = "Successfully created exam attendence";
            this.addExamAttendenceDialog = false;
            this.studentsData = [];
            this.selected = [];
            this.attendeceTable = false;
            this.valid = false;
            this.addAttendence = [];
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },
    clear() {
      this.$refs.form.reset();
      this.disable = false;
      this.loading = false;
    },
    getClass() {
      http()
        .get("/getClassesList", {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.classList = response.data.data;
        })
        .catch((err) => {
          // console.log("err====>", err);
        });
    },
    getSections(_id) {
      for (let i = 0; i < this.classList.length; i++) {
        if (_id == this.classList[i]._id) {
          // this.subjects = this.classList[i].subjects;
        }
      }
      http()
        .get(
          "/getSectionsList",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + this.token },
          }
        )
        .then((response) => {
          this.addSection = response.data.data;
        })
        .catch((err) => {});
    },
    getClassSubject(_id) {
      this.showLoader = true;
      // this.classId = this.classId;
      http()
        .get(
          "/getParticularClass",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + this.token },
          }
        )
        .then((response) => {
          this.subjectList = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          this.showLoader = false;
        });
    },
    getExamList() {
      this.showLoader = true;
      this.loadingSearch = true;
      http()
        .get("/getExamsList", {
          headers: { Authorization: "Bearer " + this.token },
        })
        .then((response) => {
          this.examList = response.data.data;
          this.showLoader = false;
          this.loadingSearch = false;
        })
        .catch((error) => {
          this.showLoader = false;
          this.loadingSearch = false;
          this.snackbar = true;
          this.text = error.response.data.message;
          if (error.response.status === 401) {
            this.$router.replace({ path: "/" });
            this.$store.dispatch("setToken", null);
            this.$store.dispatch("Id", null);
          }
        });
    },
    showTable() {
      this.attendeceTable = true;
      this.getStudentList();
    },
    getStudentList() {
      this.showLoader = true;
      http()
        .get("/getStudentWithClass", {
          params: {
            classId: this.addAttendence.classId,
            sectionId: this.addAttendence.sectionId,
          },
        })
        .then((response) => {
          this.studentsData = response.data.data;
          this.showLoader = false;
          // this.addExamAttendenceDialog = false;
          var attendence = "";
          for (let i = 0; i < this.studentsData.length; i++) {
            this.studentsData[i].attendence = false;
          }
        })
        .catch((err) => {
          console.log("err====>", err);
          this.showLoader = false;
        });
    },
    getExamAttendenceList() {
      this.showLoader = true;
      http()
        .get("/getExamAttendenceList", {
          params: {
            examId: this.getAttendence.examId,
            classId: this.getAttendence.classId,
            sectionId: this.getAttendence.sectionId,
            subjectId: this.getAttendence.subjectId,
          },
        })
        .then((response) => {
          this.examData = response.data.data;
          if (this.examData.length === 0) {
            this.showLoader = false;
            this.snackbar = true;
            this.text = "No Attendence found!";
            this.color = "error";
            return;
          }
          this.examData = this.examData[0];
          //   if (this.examData.students.length === 0) {
          //     this.showLoader = false;
          //     this.snackbar = true;
          //     this.text = "No Students found!";
          //     this.color = "error";
          //     return;
          //   }
          this.showData = true;
          this.showLoader = false;
        })
        .catch((error) => {
          console.log("error", error);
          this.showLoader = false;
        });
    },
    markParticularStudentAttendence(selected) {
      if (selected.attendence) {
        this.selected.push(selected);
      } else {
        for (var i = 0; i < this.selected.length; i++) {
          if (this.selected[i]._id === selected._id) {
            this.selected.splice(i, 1);
            break;
          }
        }
      }
      let presentIndex = this.presentStudent.indexOf(selected._id);
      let absentIndex = this.absentStudent.indexOf(selected._id);
      if (presentIndex > -1) {
        this.presentStudent.splice(presentIndex, 1);
        this.absentStudent.push(selected._id);
      } else {
        if (absentIndex > -1) {
          this.absentStudent.splice(absentIndex, 1);
        }
        this.presentStudent.push(selected._id);
      }
    },
    selectAll() {
      let markAbsent = false;
      if (this.selected.length === this.studentsData.length) markAbsent = true;

      this.presentStudent = [];
      this.absentStudent = [];
      this.selected = [];

      for (let i = 0; i < this.studentsData.length; i++) {
        if (markAbsent) {
          this.studentsData[i].attendence = false;
          this.absentStudent.push(this.studentsData[i]._id);
        } else {
          this.studentsData[i].attendence = true;
          this.presentStudent.push(this.studentsData[i]._id);
          this.selected.push(this.studentsData[i]);
        }
      }
    },
    selectParticularStudent(_id) {
      var payload = {
        examAttendanceId: this.examData._id,
        studentId: this.selectedStudent.id,
        isPresent: this.selectedStudent.isPresent,
      };

      http()
        .put("/updateExamAttendance", payload)
        .then((response) => {
          this.snackbar = true;
          this.color = "success";
          this.text = "Successfully change attendence";
          this.changeStudentAttendenceDialog = false;
          this.selectedStudent = {};
          this.getExamAttendenceList();
        })
        .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.token = this.$store.state.token;
    this.getClass();
    this.getExamList();
    this.role = this.$store.state.role;
  },
};
</script>