<template>
  <v-container fluid class="body-color">
    <v-snackbar
      :timeout="timeout"
      :top="y === 'top'"
      :right="x === 'right'"
      :vertical="mode === 'vertical'"
      v-model="snackbar"
      color="success"
    >{{ text }}</v-snackbar>
    <!-- ****** ATTENDENCE STUDENTS TABLE ****** -->
    <!-- <download-csv :data="json_data">
            <v-btn>Download Data</v-btn>
    </download-csv>-->
    <v-toolbar color="transparent" flat>
      <v-btn
        fab
        dark
        class="open-dialog-button hidden-xl-only hidden-md-only hidden-lg-only"
        small
        @click="addStudentAttendenceDialog = true"
      >
        <v-icon dark>add</v-icon>
      </v-btn>
      <v-btn
        v-if="role != 'ADMIN' && schoolRole != 'SCHOOLADMIN' "
        round
        class="open-dialog-button hidden-sm-only hidden-xs-only"
        dark
        @click="addStudentAttendenceDialog = true"
      >
        <v-icon class="white--text pr-1" size="20">add</v-icon>Add Student Attendence
      </v-btn>

      <v-spacer></v-spacer>
      <v-flex xs12 sm4 md2>
        <v-select
          small
          :items="addclass"
          label="Select Class"
          v-model="getAttendence.classId"
          item-text="classNum"
          item-value="_id"
          name="Select Class"
          @change="getSection(getAttendence.classId)"
          class="px-2"
          required
        ></v-select>
      </v-flex>
      <v-flex xs12 sm4 md2>
        <v-select
          small
          :items="addSection"
          label="Select Section"
          v-model="getAttendence.sectionId"
          item-text="name"
          item-value="_id"
          name="Select Section"
          @change="getStudentsDetail(getAttendence.sectionId)"
          class="px-2"
          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
      :headers="headers"
      :items="studentsData"
      :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.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>
          <td class="text-xs-center td td-row">
            <router-link :to="{ name:'View Students Attendence',params: { id:props.item._id } }">
              <v-tooltip top>
                <img
                  slot="activator"
                  style="cursor:pointer; width:20px; height:25px; "
                  class="mr-3"
                  src="/static/icon/view.png"
                />
                <span>View</span>
              </v-tooltip>
            </router-link>
          </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 Students Attendece****** -->
    <v-dialog
      v-model="addStudentAttendenceDialog"
      width="1600"
      v-if="addStudentAttendenceDialog"
      persistent
    >
      <v-card flat class="pa-2">
        <v-layout>
          <v-flex xs12>
            <label class="title text-xs-center">Add Student Attendence</label>
            <v-icon
              size="24"
              class="right"
              @click="$refs.form.reset();addStudentAttendenceDialog = false"
            >cancel</v-icon>
          </v-flex>
        </v-layout>
        <v-flex xs12 class="mt-4">
          <v-form ref="form" v-model="valid" lazy-validation>
            <v-flex xs12 sm12 lg12>
              <v-layout wrap>
                <v-flex xs6 sm6 lg3 md4>
                  <v-layout>
                    <v-flex xs3 sm6 lg2 class="subheading mt-4">
                      <label class="right">Class:</label>
                    </v-flex>
                    <v-flex xs9 sm6 lg8 class="ml-2">
                      <v-select
                        v-model="getReport.classId"
                        label="Select your class"
                        type="text"
                        :items="addclass"
                        item-text="classNum"
                        item-value="_id"
                        :rules="classRules"
                        @change="getSection(getReport.classId)"
                        required
                      ></v-select>
                    </v-flex>
                  </v-layout>
                </v-flex>
                <v-flex xs6 sm6 lg3 md8>
                  <v-layout>
                    <v-flex xs3 sm6 lg2 class="subheading mt-4">
                      <label class="right">Section:</label>
                    </v-flex>
                    <v-flex xs9 sm6 lg8 class="ml-2">
                      <v-select
                        :items="addSection"
                        label="Select your Section"
                        v-model="getReport.sectionId"
                        item-text="name"
                        item-value="_id"
                        name="Select Section"
                        :rules="sectionRules"
                        required
                      ></v-select>
                    </v-flex>
                  </v-layout>
                </v-flex>
                <v-flex xs6 sm6 lg3 md4>
                  <v-menu
                    ref="menu"
                    :close-on-content-click="false"
                    v-model="menu"
                    :nudge-right="40"
                    lazy
                    transition="scale-transition"
                    offset-y
                    full-width
                    min-width="290px"
                  >
                    <v-text-field
                      slot="activator"
                      v-model="date"
                      label="Select Date"
                      append-icon="event"
                      :rules="dataValid"
                      readonly
                    ></v-text-field>
                    <v-date-picker
                      ref="picker"
                      v-model="date"
                      :max="new Date().toISOString().substr(0, 10)"
                      min="1950-01-01"
                      @change="save"
                    ></v-date-picker>
                  </v-menu>
                </v-flex>
                <v-flex xs6 sm6 lg9 md8>
                  <v-btn round dark class="add-button" @click="showTable">Attendence</v-btn>
                </v-flex>
              </v-layout>
            </v-flex>
          </v-form>
        </v-flex>
        <v-flex xs12 v-show="attendeceTable" class>
          <v-data-table
            :headers="headers"
            :items="studentsData"
            :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.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>
                <td class="text-xs-center td td-row">
                  <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>
          </v-data-table>
          <v-flex xs12>
            <v-card-actions>
              <v-spacer></v-spacer>
              <v-btn @click="update()" class="add-button" round dark>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="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,
    },
    imageData: {},
    imageName: "",
    imageUrl: "",
    imageFile: "",
    headers: [
      {
        text: "No",
        align: "",
        sortable: false,
        value: "index",
      },
      {
        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: "Attendance", value: "", sortable: false, align: "center" },
    ],
    // json_data: [],
    parentId: "",
    token: "",
    selectStudents: {
      select: "",
      selectSection: "",
    },

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

    getReport: {},
    getAttendence: {},
    studentsList: [],
    studentsData: [],
    addSection: [],

    SectionName: ["A", "B", "C", "D", "E", "F"],
    classRules: [(v) => !!v || "Class is required"],
    sectionRules: [(v) => !!v || "Class is required"],
    studentRules: [(v) => !!v || "Student is required"],
    dataValid: [(v) => !!v || "Date is required"],

    attendenceType: [
      {
        label: "Present",
        value: true,
      },
      {
        label: "Absent",
        value: false,
      },
    ],
  }),
  watch: {
    addStudentAttendenceDialog: function (val) {
      if (!val) {
        this.getReport = [];
        // this.studentsData = [];
      }
    },
  },
  methods: {
    save(date) {
      this.$refs.menu.save(date);
    },
    showTable() {
      this.attendeceTable = true;
      this.getStudents();
    },
    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: "/" });
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    getSection(_id) {
      this.showLoader = true;
      this.studentsData = [];
      http()
        .get(
          "/getSectionsList",
          { params: { classId: _id } },
          {
            headers: { Authorization: "Bearer " + this.token },
          }
        )
        .then((response) => {
          this.addSection = response.data.data;
          this.showLoader = false;
        })
        .catch((err) => {
          this.showLoader = false;
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
          // console.log("err====>", err);
        });
    },
    getStudents(_id) {
      this.showLoader = true;
      http()
        .get("/getStudentWithClass", {
          params: {
            classId: this.getReport.classId,
            sectionId: this.getReport.sectionId,
          },
        })
        .then((response) => {
          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;
          }
        })
        .catch((error) => {
          //   console.log("err====>", error);
          this.showLoader = false;
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    getStudentsDetail(_id) {
      this.showLoader = true;
      http()
        .get("/getStudentWithClass", {
          params: {
            classId: this.getAttendence.classId,
            sectionId: this.getAttendence.sectionId,
          },
        })
        .then((response) => {
          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;
          }
        })
        .catch((error) => {
          //   console.log("err====>", error);
          this.showLoader = false;
          this.snackbar = true;
          this.color = "error";
          this.text = error.response.data.message;
        });
    },
    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;
          });
      }
    },

    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.getAllClass();
    this.role = this.$store.state.role;
  },
};
</script>