<template>
  <v-container fluid class="body-color">
    <!-- LOADER -->
    <div class="loader" v-if="showLoader">
      <v-progress-circular indeterminate color="white"></v-progress-circular>
    </div>

    <!-- SNACKBAR -->
    <!-- <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      :color="snackbarColor"
    >
      {{ text }}
      <v-spacer></v-spacer>
      <v-btn flat text @click="snackbar = false">X</v-btn>
    </v-snackbar>-->

    <!-- DIALOG ENROLL TEACHER -->
    <v-dialog v-model="dialogEnrollTeacher" max-width="600px" scrollable persistent>
      <v-card flat class="card-style pa-3" dark>
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">View Course</label>
            <v-icon size="24" class="right" @click="profileStudentDialog = false">cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-card-text>
          <v-flex align-center justify-center layout text-xs-center class="mt-3">
            <v-avatar size="100px">
              <img src="/static/icon/user.png" v-if="!editedItem.courseImageUrl" />
              <img :src="editedItem.courseImageUrl" v-else-if="editedItem.courseImageUrl" />
            </v-avatar>
          </v-flex>
          <v-container grid-list-md>
            <v-layout wrap>
              <v-flex xs12>
                <v-layout>
                  <v-flex xs6 sm6>
                    <h5 class="right my-1">
                      <b>Course :</b>
                    </h5>
                  </v-flex>
                  <v-flex sm6 xs6>
                    <h5 class="my-1 left">{{ editedItem.courseName }}</h5>
                  </v-flex>
                </v-layout>
              </v-flex>
            </v-layout>
          </v-container>
        </v-card-text>
      </v-card>
    </v-dialog>

    <v-toolbar color="transparent" flat>
      <v-spacer></v-spacer>
      <v-flex xs12 sm4 md2>
        <v-select
          small
          :items="classesList"
          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="	getTeacherTable(getReport.classId)"
        ></v-select>
      </v-flex>
    </v-toolbar>

    <!-- LIST OF TEACHERS -->
    <v-data-table
      :headers="headers"
      :items="teachersList"
      :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="enrollTeacher(props.item)"
              primary
              hide-details
            ></v-checkbox>
          </td>

          <td class="text-xs-center td td-row">{{ props.item.name}}</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="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 moment from "moment";
import countryList from "@/script/country.js";
import parent from "@/script/parents.js";
import AllApicalls from "@/Services/AllApiCalls.js";

export default {
  mixins: [AllApicalls],
  data: () => ({
    showNext: false,
    snackbar: false,
    y: "top",
    x: "right",
    role: "",
    mode: "",
    append: "",
    timeout: 3000,
    text: "",
    show: true,
    color: "",
    showSearch: false,
    showLoader: false,
    loading: false,
    editLoading: false,
    date: null,
    search: "",
    menu: false,
    menu1: false,
    editStudentDialog: false,
    profileStudentDialog: false,
    addCourseDialog: false,
    valid: true,

    addSection: [],
    pagination: {
      rowsPerPage: 10,
    },
    imageData: {},
    imageName: "",
    imageUrl: "",
    imageFile: "",
    editImageName: "",
    editImageUrl: "",
    courseRules: [(v) => !!v || " Course Name is required"],
    classRules: [(v) => !!v || " Class Name is required"],
    sectionRules: [(v) => !!v || " Section Name is required"],
    errorMessages: "",
    /* LIST OF TEACHERS */
    headers: [
      {
        text: "Teacher Name",
        value: "name",
        sortable: false,
        align: "center",
      },
      {
        text: "Email",
        value: "email",
        sortable: false,
        align: "center",
      },
    ],
    getReport: {},
    selected: [],
    teachers: [],
    // courseData: [],
    editedIndex: -1,
    addCourses: {},
    selectStudents: {
      select: "",
      selectSection: "",
    },
    editedItem: {},
    /* DIALOG ENROLL TEACHER */
    dialogEnrollTeacher: false,
    /* SELECT CLASS*/
    classesList: [],
    classId: "",
    /* SELECT COURSE */
    courseId: "",
  }),

  methods: {
    // async populateCourses() {
    //   let response = await this.getCourseesList({ classId: getReport.classId });
    // },
    enrollTeacher(selected) {
      let selectedTeachersArray = [];
      selectedTeachersArray.push({ teacherId: 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,
          teacherId: selected._id,
        };
        http()
          .put("/assignTeacherToCourse", payload)
          .then((response) => {
            // console.log("===response===", response);
            this.snackbar = true;
            this.color = "success";
            this.text = response.data.message;
            this.getParticularCourse("noSnackbar");
          })
          .catch((error) => {
            this.snackbar = true;
            this.color = "error";
            this.text = error.response.data.message;
          });
      }
      if (
        selected.enroll == false &&
        selected.enroll != undefined &&
        selected.enroll != null
      ) {
        var payloadDeleteTeacher = {
          courseId: this.getReport.courseId,
          assignedId: selected.enrollId,
        };
        http()
          .put("/removeTeacherToCourse", payloadDeleteTeacher)
          .then((response) => {
            this.snackbar = true;
            this.color = "success";
            this.text = response.data.message;
            this.getParticularCourse("noSnackbar");
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },

    toggleAll() {
      let withdraw = false;
      if (this.selected.length === this.teachersList.length) withdraw = true;

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

        var payload = {
          courseId: this.courseId,
          teacherId: selectedTeachersArray,
        };
        http()
          .put("/assignTeacherToCourse", payload)
          .then((response) => {
            this.snackbar = true;
            this.text = response.data.message;
            for (let i = 0; i < this.teachersList.length; i++) {
              this.teachersList[i].enroll = true;
            }
            this.getParticularCourse();
          })
          .catch((error) => {
            this.snackbar = true;
            this.text = error.response.data.message;
          });
      }
    },
    getTeacherTable(id) {
      // console.log("id", this.getReport.courseId);
      this.getTeachersList("noSnackbar");
    },
    getTeachersList(message) {
      this.showLoader = true;
      http()
        .get("/getTeachersList", {
          params: {
            classId: this.getReport.classId,
          },
        })
        .then((response) => {
          this.teachersList = response.data.data;
          this.showLoader = false;
          // this.addStudentAttendenceDialog = false;
          var attendence = "";
          for (let i = 0; i < this.teachersList.length; i++) {
            this.teachersList[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;
        });
    },
    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.assignedTeacher.length; i++) {
            var teacherId = {};
            teacherId = response.data.data.assignedTeacher[i];
            for (let j = 0; j < this.teachersList.length; j++) {
              if (teacherId.teacherId == this.teachersList[j]._id) {
                this.teachersList[j].enroll = true;
                this.teachersList[j].enrollId = teacherId._id;
                this.selected.push(this.teachersList[j]);
                break;
              }
            }
          }
          if (message != "noSnackbar") {
            this.snackbar = true;
            this.text = response.data.message;
          }
        })
        .catch((error) => {
          this.snackbar = true;
          this.text = error.response.data.message;
        });
    },
    getCourses(classId) {
      this.showLoader = true;
      this.teachersList = [];
      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;
        });
    },
    // getSections(_id) {
    //   var token = this.$store.state.token;
    //   this.showLoader = true;
    //   http()
    //     .get(
    //       "/getSectionsList",
    //       { params: { classId: _id } },
    //       {
    //         headers: { Authorization: "Bearer " + token },
    //       }
    //     )
    //     .then((response) => {
    //       this.addSection = response.data.data;
    //       this.showLoader = false;
    //     })
    //     .catch((err) => {
    //       this.showLoader = false;
    //     });
    // },
  },
  mounted() {
    var token = this.$store.state.token;
    http()
      .get("/getClassesList", {
        headers: { Authorization: "Bearer " + token },
      })
      .then((response) => {
        this.classesList = response.data.data;
      })
      .catch((error) => {
        this.showLoader = false;
        if (error.response.status === 401) {
          this.$router.replace({ path: "/" });
          this.$store.dispatch("setToken", null);
          this.$store.dispatch("Id", null);
          this.$store.dispatch("Role", null);
        }
      });
  },
};
</script>
<style scoped>
.active {
  background-color: gray;
  color: white !important;
}
.activebtn {
  color: black !important;
}
</style>